Subversion Repositories PEEPS

Rev

Rev 31 | Rev 48 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
#!/usr/bin/perl
2
 
3
# Redirect error messages to a log of my choosing. (it's annoying to filter for errors in the shared env)
4
#my $error_log_path = $ENV{SERVER_NAME} eq "volunteers.rollercon.com" ? "/home3/rollerco/logs/" : "/tmp/";
5
#close STDERR;
6
#open STDERR, '>>', $error_log_path.'vorc_error.log' or warn "Failed to open redirected logfile ($0): $!";
7
#warn "Redirecting errors to ${error_log_path}vorc_error.log";
8
 
9
use strict;
10
use WebDB;
11
use HTML::Tiny;
12
use PEEPS;
13
use CGI qw/param header start_html url url_param/;
14
my $h = HTML::Tiny->new( mode => 'html' );
4 - 15
$ENV{HTTPS} = 'ON' if $ENV{SERVER_NAME} =~ /^peeps/;
2 - 16
 
17
my %F;
18
 
19
my $cookie_string = authenticate (1) || die;
20
our ($EML, $PWD, $LVL) = split /&/, $cookie_string;
21
my $user = $ORCUSER;
22
my @adminleagues = isLeagueAdmin ($user->{person_id});
23
my $username = $user->{derby_name};
24
my $PEEPSAUTH_cookie = CGI::Cookie->new(-name=>'PEEPSAUTH',-value=>"$cookie_string",-expires=>"+30m");
25
my $YEAR = 1900 + (localtime)[5];
26
my $dbh = getDBConnection ();
27
 
28
my $pageTitle = "View League";
29
my $homeURL = "/";
30
my $DBTable = "organization";
31
my %FIELDS = (
14 - 32
	id                  => [qw(ID                    5    auto      static   )],
33
	league_name         => ["League Display Name",  10,  'text',   'required' ],
34
	business_name       => ["Business Name",        15,  'text'               ],
35
	city                => [qw(City                 20    text               )],
36
	state_province      => [qw(State/Province       25    text               )],
37
	country             => [qw(Country              30    text               )],
38
	url                 => [qw(URL                  35    text               )],
39
	type                => [qw(Type                 40    select    required )],
40
	status              => [qw(Status               45    select    required )],
41
	legal_entity_type   => ["Legal Org Type",       50,  'text',              ],
42
	tax_id              => [qw(TaxID                55    text               )],
43
	date_established    => [qw(Established          60    date               )],
44
	updated             => [qw(Updated              65    readonly  static   )],
2 - 45
);
46
 
16 - 47
if ($user->{SYSADMIN}) {
31 - 48
  $FIELDS{alcohol_liability_eligible} = ["AL Eligible", 69, "switch"];
16 - 49
  $FIELDS{visible} = [qw(Visible 70 switch)];
50
}
2 - 51
 
52
my %fieldDisplayName = map  { $_ => $FIELDS{$_}->[0]   } keys %FIELDS;
53
my %fieldType        = map  { $_ => $FIELDS{$_}->[2]   } keys %FIELDS;
54
my @requiredFields   = sort fieldOrder grep { defined $FIELDS{$_}->[3] } keys %FIELDS;
55
my @DBFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(text|select|number|switch|date|time|auto)/ } keys %FIELDS;
56
my @ROFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(readonly)/ } keys %FIELDS;
31 - 57
my @SAFields = qw/ type status alcohol_liability_eligible visible/;
2 - 58
my $primary = $DBFields[0];
59
 
60
sub fieldOrder {
61
	$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];
62
}
63
 
64
 
65
 
66
print header (-cookie=>$PEEPSAUTH_cookie),
67
			start_html (-title => $pageTitle, -style => {'src' => "/style.css"} );
68
 
69
print $h->div ({ class => "accent pageheader" }, [
70
  $h->h1 ($pageTitle),
71
  $h->div ({ class=>"sp0" }, [
72
    $h->div ({ class=>"spLeft" }, [
73
    ]),
74
    $h->div ({ class=>"spRight" }, [
75
      $h->input ({ type=>"button", value=>"Home", onClick=>"window.location.href='$homeURL'" }),
76
    ]),
77
  ]),
78
]);
79
 
80
my %GETFORM = map { split /=/ } split /&/, $ENV{QUERY_STRING};
81
$GETFORM{$primary} = WebDB::trim scalar param ("id") unless $GETFORM{$primary};
82
my $choice = param ("choice") || $GETFORM{choice} // "";
83
 
84
my $org = getLeagueAffiliation ($ORCUSER->{person_id});
85
my $leagueAdmin = inArray ("League Admin", $org->{$GETFORM{$primary}}) unless !$org->{$GETFORM{$primary}};
86
 
87
if ($choice eq "Save") {
88
	process_form ();
89
} elsif (defined (param ($primary)) || $GETFORM{$primary} || url_param ($primary)) {
90
  my $thing = param ($primary) || $GETFORM{$primary}; $thing //= url_param ($primary);
91
  if ($choice eq "Delete") {
92
    delete_item ({ $primary => $thing });
93
  } else {
94
	  display_form ({ $primary => $thing }, $choice);
95
	}
96
} else {
97
	display_form (); # blank form
98
}
99
 
100
print $h->close ("html");
101
 
102
sub display_form  {
103
  my $R = shift;
104
  my $view = shift // "";
105
	my $actionbutton;
106
 
14 - 107
  $view = "View" unless $ORCUSER->{SYSADMIN} or $leagueAdmin;
2 - 108
 
109
  if ($view eq "POSTSAVE" and $R->{$primary} eq "NEW") {
110
      print &formField ("Cancel", "Back", "POSTSAVE");
111
      return;
112
  }
113
 
114
  if ($R) {
115
    # we're dealing with an existing thing.  Get the current values out of the DB...
116
 
117
	  @F{@DBFields,@ROFields} = $dbh->selectrow_array (
118
                     "SELECT ". join (", ", @DBFields, @ROFields) ." FROM $DBTable WHERE $primary = ?",
119
                      undef, $R->{$primary});
120
 
121
	  # did we find a record?
122
	  error ("Cannot find a database entry with id: '$R->{$primary}'") unless defined $F{$DBFields[0]};
123
 
124
    # If the DB returns a null value, HTML::Tiny doesn't like it, so make sure nulls are converted to empty strings.
125
    map { $F{$_} = "" unless $F{$_} } @DBFields, @ROFields;
126
 
127
 
128
    if ($view eq "Update") {
129
      # We'd like to update that thing, give the user a form...
130
      print $h->p ("Updating League: $R->{$primary}...");
131
 
132
      foreach (@DBFields) {
14 - 133
        if (notInArray ($_, \@SAFields) or $ORCUSER->{SYSADMIN}) {
134
          $F{$_} = formField ($_, $F{$_});
135
        }
136
 
2 - 137
      }
138
 
139
      $actionbutton = formField ("choice", "Save");
140
      $actionbutton .= formField ("Cancel");
141
    } elsif ($view eq "Copy") {
142
      # We'd like to copy that thing, give the user a form...
143
      print $h->p ("Copying League: $R->{$primary}...");
144
 
145
      foreach (@DBFields) {
146
        $F{$_} = formField ($_, $F{$_});
147
      }
148
#      $F{$DBFields[0]} = "COPY".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
149
 
150
      $actionbutton = formField ("choice", "Save");
151
      $actionbutton .= formField ("Cancel");
152
    } else {
153
      # We're just looking at it...
154
      print $h->p ("Viewing League: $R->{$primary}...");
155
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
156
 
157
      # Put the time fields into the user's preference
158
      map { $F{$_} = convertTime $F{$_} } grep { $fieldType{$_} eq "time" } keys %FIELDS;
14 - 159
      $F{url} = $h->a ({href => $F{url}, target=>"_blank"}, $F{url}) unless !$F{url};
31 - 160
      $F{alcohol_liability_eligible} = $F{alcohol_liability_eligible} ? "True" : "False";
16 - 161
      $F{visible} = $F{visible} ? "True" : "False";
2 - 162
 
14 - 163
      $actionbutton = formField ("choice", "Update") if $ORCUSER->{SYSADMIN} or $leagueAdmin;
2 - 164
      if ($view eq "POSTSAVE" or $choice eq "View") {
165
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
166
      } else {
167
        $actionbutton .= formField ("Cancel", "Back");
168
      }
169
    }
170
  } else {
171
    error ("No Organization ID provided.") unless $ORCUSER->{SYSADMIN};
26 - 172
 
2 - 173
    print $h->p ("Adding a new League...");
26 - 174
 
2 - 175
    foreach (@DBFields) {
176
      $F{$_} = formField ($_);
177
    }
26 - 178
		$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
2 - 179
 
180
    $actionbutton = formField ("choice", "Save");
181
    $actionbutton .= formField ("Cancel");
182
  }
183
 
184
 
185
	print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });
186
	print $h->div ({ class=>"sp0" },
187
	  $h->div ({ class=>"rTable" }, [ map ({
188
      $h->div ({ class=>"rTableRow" }, [
189
        $h->div ({ class=>"rTableCell right top", style=>"font-size:unset;" }, "$fieldDisplayName{$_}: "),
190
        $h->div ({ class=>"rTableCell", style=>"font-size:unset;" }, $F{$_})
191
      ])
192
       } sort fieldOrder keys %FIELDS),
193
   ])
194
  );
195
 
196
  print $actionbutton;
197
 
40 - 198
  return unless $leagueAdmin or inArray ($R->{$primary} ,[keys %{$org}]) or $user->{SYSADMIN} or $user->{SANCTIONING};
14 - 199
 
200
  my @role_section = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(Role Count) ) ]));
201
  my @roles = @{ $dbh->selectall_arrayref ("select role, count(role) from role where member_org_id = ? group by role order by role", undef, $R->{$primary}) };
202
  my ($total_members) = $dbh->selectrow_array ("select count(distinct person_id) from role where member_org_id = ?", undef, $R->{$primary});
203
  foreach (@roles) {
204
    my %role;
205
    @role{qw/role count/} = @{$_};
206
 
207
    push @role_section, $h->div ({ class=>"rTableRow shaded", onClick=>"window.location.href='people?excel=0&autoload=1&id=true&name_first=true&name_last=true&derby_name=true&league_id=true&role=true&created=true&updated=true&filter-id=&filter-name_first=&filter-name_last=&filter-derby_name=&filter-league_id=".$R->{$primary}."&filter-role=".$role{role}."&filter-created=&filter-updated=&sortby=id&limit=25&page=1'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, $role{role}, $role{count}) ]);
208
  }
209
  push @role_section, $h->div ({ class=>"rTableRow shaded", onClick=>"window.location.href='people?excel=0&autoload=1&id=true&name_first=true&name_last=true&derby_name=true&league_id=true&role=true&created=true&updated=true&filter-id=&filter-name_first=&filter-name_last=&filter-derby_name=&filter-league_id=".$R->{$primary}."&filter-role=&filter-created=&filter-updated=&sortby=id&limit=25&page=1'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;font-weight: bold;" }, "Total Members", $total_members) ]);
210
 
2 - 211
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
212
  my @policy_columns = qw(id organization_id policy_name fee created start end active);
213
 
214
  my @policies = @{ $dbh->selectall_arrayref ("select ".join (", ", @policy_columns)." from org_coverage where organization_id = ? order by start desc, end", undef, $R->{$primary}) };
215
  my $active_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA General Liability Insurance");
216
  my $active_alcohol_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA League Alcohol Liability");
217
  foreach (@policies) {
218
    my %policy;
219
    @policy{@policy_columns} = @{$_};
220
 
29 - 221
    push @policyhistory, $h->div ({ class=>"rTableRow ".(inArray ($policy{id}, [$active_policy, $active_alcohol_policy]) ? "highlighted" : "shaded"), onClick=>"window.location.href='view_org_policy?id=$policy{id}&leagueid=$R->{$primary}'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, $policy{id}, $policy{policy_name}, $policy{start}, $policy{end}) ]);
2 - 222
  }
223
  push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr hint", style=>"font-size: smaller;" }, 'No Policy History') ]) unless scalar @policies;
224
 
27 - 225
  if ($leagueAdmin and (!$active_policy or !$active_alcohol_policy or remainingOrgPolicyDays ($active_policy) <= 90 or remainingOrgPolicyDays ($active_alcohol_policy) <= 90)) {
2 - 226
    push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, '&nbsp;') ]);
227
    push @policyhistory, $h->div ({ style=>"font-size: smaller;" }, [
22 - 228
                                   ((!$active_policy or remainingOrgPolicyDays ($R->{$primary}, $active_policy) <= 90) ? $h->button ({ onClick=>"window.location.href='attestation?policy=2&league=".$R->{$primary}."'; return false;" }, ($active_policy ? "Renew" : "Purchase")." General Liability") : ""),
31 - 229
                                   (($F{alcohol_liability_eligible} eq "True" and (!$active_alcohol_policy or remainingOrgPolicyDays ($R->{$primary}, $active_alcohol_policy) <= 90)) ? $h->button ({ onClick=>"window.location.href='attestation?policy=3&league=".$R->{$primary}."'; return false;" }, ($active_alcohol_policy ? "Renew" : "Purchase")." Alcohol Liability") : "")
2 - 230
                                 ]);
231
  }
232
 
14 - 233
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "League Role Counts:"), $h->ul ([ @role_section ])]);
234
 
2 - 235
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "League Insurance Policy History:"), $h->ul ([ @policyhistory ])]);
236
 
237
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getOrgLog ($R->{$primary})]) unless $R->{$primary} !~ /^\d+$/;
238
 
239
  print $h->close ("form");
240
}
241
 
242
sub process_form  {
14 - 243
  error ("ERROR: Only SysAdmins or League Admins can change leagues.") unless $ORCUSER->{SYSADMIN} or $leagueAdmin;
2 - 244
 
245
  my %FORM;
246
  foreach (keys %FIELDS) {
247
  	if ($fieldType{$_} =~ /^text/ and $_ ne "title") {
248
  		$FORM{$_} = WebDB::trim param ($_) // "";
249
  	} else {
250
	  	$FORM{$_} = param ($_) // "";
251
  	}
252
  }
253
 
254
  	 # check for required fields
255
	my @errors = ();
14 - 256
	foreach (grep {notInArray ($_, \@SAFields) unless $ORCUSER->{SYSADMIN} } @requiredFields) {
2 - 257
		push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "" and $FIELDS{$_}->[3] ne "static";
258
	}
259
 
260
  if (@errors)	 {
261
    print $h->div ({ class=>"error" }, [
262
  	  $h->p ("The following errors occurred:"),
263
  	  $h->ul ($h->li (@errors)),
264
  	  $h->p ("Please click your Browser's Back button to\n"
265
  	  	   . "return to the previous page and correct the problem.")
266
  	]);
267
  	return;
268
  }	 # Form was okay.
269
 
270
  $FORM{$primary} = saveForm (\%FORM);
271
 
272
	print $h->p ({ class=>"success" }, "League successfully saved.");
273
 
274
  display_form ({ $primary=>$FORM{$primary} }, "POSTSAVE");
275
}
276
 
277
sub saveForm {
14 - 278
  error ("ERROR: Only SysAdmins or League Admins can change league details.") unless $ORCUSER->{SYSADMIN} or $leagueAdmin;
2 - 279
 
280
  my $FTS = shift;
281
 
282
  if ($FTS->{$DBFields[0]} eq "NEW") {
283
    $dbh->do (
284
      "INSERT INTO $DBTable (".
26 - 285
      join (", ", grep { $FTS->{$_} } grep { $_ ne $primary } @DBFields)
286
      .") VALUES (". join (", ", map { '?' } grep { $FTS->{$_} } grep { $_ ne $primary } @DBFields) .")",
2 - 287
    	undef,
26 - 288
    	map { $FTS->{$_} } grep { $FTS->{$_} } grep { $_ ne $primary } @DBFields
289
    ) or warn $dbh->errstr;
290
    if ($FTS->{$primary} eq "NEW") {
2 - 291
      ($FTS->{$primary}) = $dbh->selectrow_array ("select max($primary) from $DBTable");
292
    }
26 - 293
    logit ($user->{person_id}, "$username added a league (".join (", ", map { $FTS->{$_} } @DBFields).")");
2 - 294
  } else {
295
    my $OG = $dbh->selectrow_hashref ("select * from organization where id = ?", undef, $FTS->{$primary});
296
 
297
    error ("ERROR: Attempting to edit existing league, but league ID not found [$FTS->{$primary}]!") unless $OG->{$primary} =~ /^\d+$/;
298
    my $league_name = getLeagueName ($FTS->{$primary});
299
 
300
    foreach my $field (grep { notInArray ($_, \@ROFields) } keys %{$FTS}) {
14 - 301
      if (notInArray ($field, \@SAFields) or $ORCUSER->{SYSADMIN}) {
302
        if ($FTS->{$field} ne $OG->{$field}) {
31 - 303
        	if ($field eq "visible" or $field eq "alcohol_liability_eligible") {
16 - 304
        		$FTS->{$field} = $FTS->{$field} ? 1 : 0;
305
        	}
14 - 306
          $dbh->do ("update $DBTable set $field = ?, updated = now() where $primary = ?", undef, $FTS->{$field}, $FTS->{$primary});
307
          logit ($ORCUSER->{person_id}, "Updated league $league_name [$FTS->{$primary}]: $field -> $FTS->{$field}");
308
          orglogit ($ORCUSER->{person_id}, $FTS->{$primary}, "Updated league: $field -> $FTS->{$field}");
309
        }
2 - 310
      }
311
    }
312
 
313
 
314
  }
315
	return $FTS->{$primary};
316
}
317
 
318
sub delete_item {
319
  error ("ERROR: Only SysAdmins can delete leagues.") unless $ORCUSER->{SYSADMIN};
320
 
321
  my $X = shift;
322
 
323
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
324
 
325
  logit ($user->{person_id}, "$username deleted League ($X->{$primary})");
326
  print "League Deleted: $X->{$primary}", $h->br;
327
  print &formField ("Cancel", "Back", "POSTSAVE");
328
}
329
 
330
sub error {
331
	my $msg = shift;
332
	print $h->p ({ class=>"error" }, "Error: $msg");
333
  print $h->close("html");
334
	exit (0);
335
}
336
 
337
sub formField {
338
	my $name  = shift;
339
	my $value = shift // '';
340
	my $context = shift // '';
341
	my $type = $fieldType{$name} // "button";
342
 
343
  if ($type eq "button") {
344
		if ($name eq "Cancel") {
345
		  if ($context eq "POSTSAVE") {
346
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"organizations.pl\"; return false;" });
347
		  } else {
348
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });
349
		  }
350
		} else {
351
			return $h->input ({ type=>"submit", value => $value, name=>$name })
352
		}
353
 
354
	} elsif ($type eq "textarea") {
355
	  return $h->tag ("textarea", {
356
	    name => $name,
357
	    override => 1,
358
			cols => 30,
359
			rows => 4
360
	  }, $value);
361
 
362
  } elsif ($type eq "select") {
363
    no strict;
364
    return &{"select_".$name} ($value);
365
	}	elsif ($type eq "auto") {
366
	  return $value.$h->input ({ type=>"hidden", name=>$name, value=>$value });
367
  }	elsif ($type eq "time") {
368
	  return $h->input ({
369
	    name => $name,
370
	    type => $type,
371
	    value => $value,
372
	    step => 900,
373
	    required => [],
374
	    override => 1,
375
	    size => 30
376
	  });
377
  }	elsif ($type eq "number") {
378
    return $h->input ({ name=>$name, type=>"number", value=>$value, step=>1 });
379
  }	elsif ($type eq "switch") {
380
    if ($value) {
381
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
382
    } else {
383
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);
384
    }
385
	}	else {
386
	  use tableViewer;
387
	  if (inArray ($name, \@requiredFields)) {
388
  	  return $h->input ({
389
  	    name => $name,
390
  	    type => $type,
391
  	    value => $value,
392
  	    required => [],
393
  	    override => 1,
394
  	    size => 30
395
  	  });
396
	  } else {
397
  	  return $h->input ({
398
  	    name => $name,
399
  	    type => $type,
400
  	    value => $value,
401
  	    override => 1,
402
  	    size => 30
403
  	  });
404
  	}
405
	}
406
}
407
 
408
sub select_type {
409
  my $selection = shift // "";
410
  my @options = ("");
411
 
412
  my $sub_name = (caller(0))[3];
413
  $sub_name =~ s/^main::select_//;
414
 
415
 	push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct type from $DBTable order by type")};
416
 
417
  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
418
}
419
 
420
sub select_status {
421
  my $selection = shift // "";
422
  my @options = ("");
423
 
424
  my $sub_name = (caller(0))[3];
425
  $sub_name =~ s/^main::select_//;
426
 
427
 	push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct status from $DBTable order by type")};
428
 
429
  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
430
}
431
 
432
sub getOrgLog {
433
  my $org_id = shift;
434
 
435
  my @activity_log;
436
  my $alog = $dbh->prepare("select timestamp, person_id, event from organization_log where organization_id = ? order by eventid desc limit 10");
437
  $alog->execute($org_id);
438
  while (my @logs = $alog->fetchrow_array) {
439
    $logs[1] = getUser ($logs[1])->{derby_name};
440
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
441
  }
442
 
443
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"org_log?filter-organization_id=".$org_id }, "[Entire log history]"));
444
}
5 - 445