Subversion Repositories PEEPS

Rev

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