Subversion Repositories PEEPS

Rev

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