Subversion Repositories PEEPS

Rev

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