Subversion Repositories PEEPS

Rev

Rev 3 | Rev 5 | 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 = (
32
	id                  => [qw(ID               5    auto      static   )],
33
	league_name         => [qw(DisplayName     10    text      required )],
34
	business_name       => [qw(BusinessName    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   => [qw(LegalType       50    text               )],
42
	tax_id              => [qw(TaxID           55    text               )],
43
	date_established    => [qw(Established     60    date               )],
44
	updated             => [qw(Updated         65    readonly  static   )],
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;
53
my @SAFields = qw/ league_name business_name type status legal_entity_type /;
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
 
103
  $view = "View" unless $ORCUSER->{SYSADMIN};
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) {
129
        $F{$_} = formField ($_, $F{$_});
130
      }
131
 
132
      $actionbutton = formField ("choice", "Save");
133
      $actionbutton .= formField ("Cancel");
134
    } elsif ($view eq "Copy") {
135
      # We'd like to copy that thing, give the user a form...
136
      print $h->p ("Copying League: $R->{$primary}...");
137
 
138
      foreach (@DBFields) {
139
        $F{$_} = formField ($_, $F{$_});
140
      }
141
#      $F{$DBFields[0]} = "COPY".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
142
 
143
      $actionbutton = formField ("choice", "Save");
144
      $actionbutton .= formField ("Cancel");
145
    } else {
146
      # We're just looking at it...
147
      print $h->p ("Viewing League: $R->{$primary}...");
148
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
149
 
150
      # Put the time fields into the user's preference
151
      map { $F{$_} = convertTime $F{$_} } grep { $fieldType{$_} eq "time" } keys %FIELDS;
152
 
153
      $actionbutton = formField ("choice", "Update") if $ORCUSER->{SYSADMIN};
154
      if ($view eq "POSTSAVE" or $choice eq "View") {
155
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
156
      } else {
157
        $actionbutton .= formField ("Cancel", "Back");
158
      }
159
    }
160
  } else {
161
    error ("No Organization ID provided.") unless $ORCUSER->{SYSADMIN};
162
 
163
    print $h->p ("Adding a new League...");
164
 
165
    foreach (@DBFields) {
166
      $F{$_} = formField ($_);
167
    }
168
#		$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
169
 
170
    $actionbutton = formField ("choice", "Save");
171
    $actionbutton .= formField ("Cancel");
172
  }
173
 
174
 
175
	print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });
176
	print $h->div ({ class=>"sp0" },
177
	  $h->div ({ class=>"rTable" }, [ map ({
178
      $h->div ({ class=>"rTableRow" }, [
179
        $h->div ({ class=>"rTableCell right top", style=>"font-size:unset;" }, "$fieldDisplayName{$_}: "),
180
        $h->div ({ class=>"rTableCell", style=>"font-size:unset;" }, $F{$_})
181
      ])
182
       } sort fieldOrder keys %FIELDS),
183
   ])
184
  );
185
 
186
  print $actionbutton;
187
 
188
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
189
  my @policy_columns = qw(id organization_id policy_name fee created start end active);
190
 
191
  my @policies = @{ $dbh->selectall_arrayref ("select ".join (", ", @policy_columns)." from org_coverage where organization_id = ? order by start desc, end", undef, $R->{$primary}) };
192
  my $active_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA General Liability Insurance");
193
  my $active_alcohol_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA League Alcohol Liability");
194
  foreach (@policies) {
195
    my %policy;
196
    @policy{@policy_columns} = @{$_};
197
 
198
    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}) ]);
199
  }
200
  push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr hint", style=>"font-size: smaller;" }, 'No Policy History') ]) unless scalar @policies;
201
 
202
  if (!$active_policy or !$active_alcohol_policy or remainingOrgPolicyDays ($active_policy) <= 90 or remainingOrgPolicyDays ($active_alcohol_policy) <= 90) {
203
    push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, '&nbsp;') ]);
204
    push @policyhistory, $h->div ({ style=>"font-size: smaller;" }, [
205
                                   ((!$active_policy or remainingOrgPolicyDays ($R->{$primary}, $active_policy) <= 90) ? $h->button (($active_policy ? "Renew" : "Purchase")." General Liability") : ""),
206
                                   ((!$active_alcohol_policy or remainingOrgPolicyDays ($R->{$primary}, $active_alcohol_policy) <= 90) ? $h->button (($active_alcohol_policy ? "Renew" : "Purchase")." Alcohol Liability") : "")
207
                                 ]);
208
  }
209
 
210
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "League Insurance Policy History:"), $h->ul ([ @policyhistory ])]);
211
 
212
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getOrgLog ($R->{$primary})]) unless $R->{$primary} !~ /^\d+$/;
213
 
214
  print $h->close ("form");
215
}
216
 
217
sub process_form  {
218
  error ("ERROR: Only SysAdmins can change leagues.") unless $ORCUSER->{SYSADMIN};
219
 
220
  my %FORM;
221
  foreach (keys %FIELDS) {
222
  	if ($fieldType{$_} =~ /^text/ and $_ ne "title") {
223
  		$FORM{$_} = WebDB::trim param ($_) // "";
224
  	} else {
225
	  	$FORM{$_} = param ($_) // "";
226
  	}
227
  }
228
 
229
  	 # check for required fields
230
	my @errors = ();
231
	foreach (@requiredFields) {
232
		push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "" and $FIELDS{$_}->[3] ne "static";
233
	}
234
 
235
  if (@errors)	 {
236
    print $h->div ({ class=>"error" }, [
237
  	  $h->p ("The following errors occurred:"),
238
  	  $h->ul ($h->li (@errors)),
239
  	  $h->p ("Please click your Browser's Back button to\n"
240
  	  	   . "return to the previous page and correct the problem.")
241
  	]);
242
  	return;
243
  }	 # Form was okay.
244
 
245
  $FORM{$primary} = saveForm (\%FORM);
246
 
247
	print $h->p ({ class=>"success" }, "League successfully saved.");
248
 
249
  display_form ({ $primary=>$FORM{$primary} }, "POSTSAVE");
250
}
251
 
252
sub saveForm {
253
  error ("ERROR: Only SysAdmins can change league details.") unless $ORCUSER->{SYSADMIN};
254
 
255
  my $FTS = shift;
256
 
257
  if ($FTS->{$DBFields[0]} eq "NEW") {
258
    $dbh->do (
259
      "INSERT INTO $DBTable (".
260
      join (", ", @DBFields)
261
      .") VALUES (". join (", ", map { '?' } @DBFields) .")",
262
    	undef,
263
    	map { $FTS->{$_} } @DBFields
264
    );
265
    if (!$FTS->{$primary}) {
266
      ($FTS->{$primary}) = $dbh->selectrow_array ("select max($primary) from $DBTable");
267
    }
268
    logit ($user->{person_id}, "$username edited a league (".join (", ", map { $FTS->{$_} } @DBFields).")");
269
  } else {
270
    my $OG = $dbh->selectrow_hashref ("select * from organization where id = ?", undef, $FTS->{$primary});
271
 
272
    error ("ERROR: Attempting to edit existing league, but league ID not found [$FTS->{$primary}]!") unless $OG->{$primary} =~ /^\d+$/;
273
    my $league_name = getLeagueName ($FTS->{$primary});
274
 
275
    foreach my $field (grep { notInArray ($_, \@ROFields) } keys %{$FTS}) {
276
      if ($FTS->{$field} ne $OG->{$field}) {
277
        $dbh->do ("update $DBTable set $field = ?, updated = now() where $primary = ?", undef, $FTS->{$field}, $FTS->{$primary});
278
        logit ($ORCUSER->{person_id}, "Updated league $league_name [$FTS->{$primary}]: $field -> $FTS->{$field}");
279
        orglogit ($ORCUSER->{person_id}, $FTS->{$primary}, "Updated league: $field -> $FTS->{$field}");
280
      }
281
    }
282
 
283
 
284
  }
285
	return $FTS->{$primary};
286
}
287
 
288
sub delete_item {
289
  error ("ERROR: Only SysAdmins can delete leagues.") unless $ORCUSER->{SYSADMIN};
290
 
291
  my $X = shift;
292
 
293
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
294
 
295
  logit ($user->{person_id}, "$username deleted League ($X->{$primary})");
296
  print "League Deleted: $X->{$primary}", $h->br;
297
  print &formField ("Cancel", "Back", "POSTSAVE");
298
}
299
 
300
sub error {
301
	my $msg = shift;
302
	print $h->p ({ class=>"error" }, "Error: $msg");
303
  print $h->close("html");
304
	exit (0);
305
}
306
 
307
sub formField {
308
	my $name  = shift;
309
	my $value = shift // '';
310
	my $context = shift // '';
311
	my $type = $fieldType{$name} // "button";
312
 
313
  if ($type eq "button") {
314
		if ($name eq "Cancel") {
315
		  if ($context eq "POSTSAVE") {
316
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"organizations.pl\"; return false;" });
317
		  } else {
318
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });
319
		  }
320
		} else {
321
			return $h->input ({ type=>"submit", value => $value, name=>$name })
322
		}
323
 
324
	} elsif ($type eq "textarea") {
325
	  return $h->tag ("textarea", {
326
	    name => $name,
327
	    override => 1,
328
			cols => 30,
329
			rows => 4
330
	  }, $value);
331
 
332
  } elsif ($type eq "select") {
333
    no strict;
334
    return &{"select_".$name} ($value);
335
	}	elsif ($type eq "auto") {
336
	  return $value.$h->input ({ type=>"hidden", name=>$name, value=>$value });
337
  }	elsif ($type eq "time") {
338
	  return $h->input ({
339
	    name => $name,
340
	    type => $type,
341
	    value => $value,
342
	    step => 900,
343
	    required => [],
344
	    override => 1,
345
	    size => 30
346
	  });
347
  }	elsif ($type eq "number") {
348
    return $h->input ({ name=>$name, type=>"number", value=>$value, step=>1 });
349
  }	elsif ($type eq "switch") {
350
    if ($value) {
351
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
352
    } else {
353
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);
354
    }
355
	}	else {
356
	  use tableViewer;
357
	  if (inArray ($name, \@requiredFields)) {
358
  	  return $h->input ({
359
  	    name => $name,
360
  	    type => $type,
361
  	    value => $value,
362
  	    required => [],
363
  	    override => 1,
364
  	    size => 30
365
  	  });
366
	  } else {
367
  	  return $h->input ({
368
  	    name => $name,
369
  	    type => $type,
370
  	    value => $value,
371
  	    override => 1,
372
  	    size => 30
373
  	  });
374
  	}
375
	}
376
}
377
 
378
sub select_type {
379
  my $selection = shift // "";
380
  my @options = ("");
381
 
382
  my $sub_name = (caller(0))[3];
383
  $sub_name =~ s/^main::select_//;
384
 
385
 	push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct type from $DBTable order by type")};
386
 
387
  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
388
}
389
 
390
sub select_status {
391
  my $selection = shift // "";
392
  my @options = ("");
393
 
394
  my $sub_name = (caller(0))[3];
395
  $sub_name =~ s/^main::select_//;
396
 
397
 	push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct status from $DBTable order by type")};
398
 
399
  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
400
}
401
 
402
sub getOrgLog {
403
  my $org_id = shift;
404
 
405
  my @activity_log;
406
  my $alog = $dbh->prepare("select timestamp, person_id, event from organization_log where organization_id = ? order by eventid desc limit 10");
407
  $alog->execute($org_id);
408
  while (my @logs = $alog->fetchrow_array) {
409
    $logs[1] = getUser ($logs[1])->{derby_name};
410
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
411
  }
412
 
413
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"org_log?filter-organization_id=".$org_id }, "[Entire log history]"));
414
}