Subversion Repositories VORC

Rev

Rev 62 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
56 bgadell 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 cPanelUserConfig;
11
use WebDB;
12
use HTML::Tiny;
13
use RollerCon;
14
use CGI qw/param header start_html url/;
15
my $h = HTML::Tiny->new( mode => 'html' );
16
 
17
my %F;
18
 
19
my $cookie_string = authenticate (1) || die;
20
our ($EML, $PWD, $LVL) = split /&/, $cookie_string;
21
my $user = getUser ($EML);
22
$user->{department} = convertDepartments $user->{department};
23
my $DepartmentNames = getDepartments ();
24
my $username = $user->{derby_name};
25
my $RCid = $user->{RCid};
26
my $RCAUTH_cookie = CGI::Cookie->new(-name=>'RCAUTH',-value=>"$cookie_string",-expires=>"+30m");
27
my $YEAR = 1900 + (localtime)[5];
28
 
29
 
30
my $pageTitle = "View MVP Class";
31
my $homeURL = "/schedule/";
32
my $DBTable = "class";
33
my %FIELDS = (
34
	id          => [qw(ClassID        5    auto        static )],
35
	name        => [qw(ClassName     10    text        required )],
36
	coach       => [qw(Coach         15    select      required )],
37
	date        => [qw(Date          20    date        required )],
38
	location    => [qw(Location      25    text        required )],
39
	start_time  => [qw(Start         30    time        required )],
40
	end_time    => [qw(End           35    time        required )],
41
	capacity    => [qw(Capacity      40    number      required )],
42
	note        => [qw(Notes         45    textarea       )],
43
);
44
 
45
 
46
my %fieldDisplayName = map  { $_ => $FIELDS{$_}->[0]   } keys %FIELDS;
47
my %fieldType        = map  { $_ => $FIELDS{$_}->[2]   } keys %FIELDS;
48
my @requiredFields   = sort fieldOrder grep { defined $FIELDS{$_}->[3] } keys %FIELDS;
49
my @DBFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(text|select|number|switch|date|time|auto)/ } keys %FIELDS;
50
my @ROFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(readonly)/ } keys %FIELDS;
51
my $primary = $DBFields[0];
52
 
53
sub fieldOrder {
54
	$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];
55
}
56
 
57
sub saveForm {
58
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
59
 
60
  my $FTS = shift;
61
 
62
  my $dbh = WebDB::connect ();
63
  if ($FTS->{$DBFields[0]} eq "NEW") {
64
    $dbh->do (
65
      "INSERT INTO $DBTable
66
      (name,coach,date,location,start_time,end_time,capacity,note)
67
      VALUES(?,?,?,?,?,?,?,?)",
68
    	undef,
69
    	$FTS->{name}, $FTS->{coach}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity}, $FTS->{note}
70
    );
71
  	($FTS->{id}) = $dbh-> selectrow_array ("select max(id) from $DBTable where name = ? and date = ? and location = ? and start_time = ? and end_time = ?", undef, $FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time});
72
    logit ($RCid, "$username created new class ($FTS->{id}, $FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity})");
73
 
74
    # Each class has a volunteer shift for the coach.
75
    $dbh->do (
76
      "INSERT INTO shift
77
      (dept,role,type,date,location,start_time,end_time,doubletime,note,assignee_id)
78
      VALUES (?,?,?,?,?,?,?,?,?,?)",
79
      undef,
80
      "COA", "Coach", "selected", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, 1, $FTS->{name}, $FTS->{coach}
81
    );
82
  } else {
83
    $dbh->do (
84
      "UPDATE $DBTable
85
      SET name=?, coach=?, date=?, location=?, start_time=?, end_time=?, capacity=?, note=?
86
      WHERE id = ?",
87
      undef,
88
      $FTS->{name}, $FTS->{coach}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity}, $FTS->{note}, $FTS->{id}
89
    );
90
    logit ($RCid, "$username updated class ($FTS->{id}, $FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity})");
91
 
92
    # Update the volunteer shift for the coach too.
93
    $dbh->do (
94
      "UPDATE shift
95
      SET date=?, location=?, start_time=?, end_time=?, note=?, assignee_id=?
96
      WHERE id = ?",
97
      undef,
98
      $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{name}, $FTS->{coach}, $FTS->{classshiftid}
99
    );
100
 
101
	}
102
 
103
	$dbh->disconnect ();	 # stored into database successfully.
104
	return $FTS->{id};
105
}
106
 
107
sub delete_item {
108
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
109
 
110
  my $X = shift;
111
  my $dbh = WebDB::connect ();
112
 
113
  ## First get the shift ID of the volunteer shift of the coach (and then delete it)
114
  my ($classshiftid) = $dbh->selectrow_array (
115
    "select shift.id from shift
116
    join class where shift.date = class.date and shift.start_time = class.start_time and shift.location = class.location and dept = ? and class.id = ?",
117
    undef, "COA", $X->{$primary}
118
  );
119
  $dbh->do ("delete from shift where id = ?", undef, $classshiftid);
120
 
121
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
122
  ## If we're deleting a class, we need to also delete all of the sign-ups
123
  ##    TBD: Maybe email all of the attendees that their class is being deleted first?
124
  $dbh->do ("delete from assignment where Gid = ? and role like ?", undef, $X->{$primary}, "CLA".'%');
125
 
126
  $dbh->disconnect ();
127
  logit ($RCid, "$username deleted Class ($X->{$primary})");
128
  print "Class Deleted: $X->{$primary}", $h->br;
129
  print &formField ("Cancel", "Back", "POSTSAVE");
130
}
131
 
132
 
133
sub select_coach {
134
	my $selection = shift // "";
135
 
136
  return $h->select ({ name=>"coach" }, [ $h->option (""), fetchDerbyNameWithRCid ("COA", $selection) ]);
137
};
138
 
139
 
140
print header (),
141
			start_html (-title => $pageTitle, -style => {'src' => "/style.css"} );
142
 
143
print $h->div ({ class => "accent pageheader" }, [
144
  $h->h1 ($pageTitle),
145
  $h->div ({ class=>"sp0" }, [
146
    $h->div ({ class=>"spLeft" }, [
147
    ]),
148
    $h->div ({ class=>"spRight" }, [
149
      $h->input ({ type=>"button", value=>"Home", onClick=>"window.location.href='$homeURL'" }),
150
    ]),
151
  ]),
152
]);
153
 
154
my $choice = param ("choice") // "";
155
if ($choice eq "Save") {
156
	process_form ();
157
} elsif (defined (param ($primary))) {
158
  my $thing = param ($primary);
159
  if ($choice eq "Delete") {
160
    delete_item ({ $primary => $thing });
161
  } else {
162
	  display_form ({ $primary => $thing }, $choice);
163
	}
164
} else {
165
	display_form (); # blank form
166
}
167
 
168
print $h->close ("html");
169
 
170
sub display_form  {
171
  my $R = shift;
172
  my $view = shift // "";
173
	my $actionbutton;
174
 
175
  $view = "View" unless $LVL >= RollerCon::ADMIN;
176
 
177
  if ($view eq "POSTSAVE" and $R->{$primary} eq "NEW") {
178
      print &formField ("Cancel", "Back", "POSTSAVE");
179
      return;
180
  }
181
 
182
  if ($R) {
183
    # we're dealing with an existing thing.  Get the current values out of the DB...
184
    my $dbh = WebDB::connect ();
185
 
186
	  @F{@DBFields} = $dbh->selectrow_array (
187
                     "SELECT ". join (", ", @DBFields) ." FROM $DBTable WHERE $primary = ?",
188
                      undef, $R->{$primary});
189
 
190
	  my ($classshiftid) = $dbh->selectrow_array (
191
	    "select id from shift where dept = ? and date = ? and start_time = ? and location = ?",
192
	    undef, "COA", $F{date}, $F{start_time}, $F{location}
193
	  );
194
	  $dbh->disconnect ();
195
 
196
	  # did we find a record?
197
	  error ("Cannot find a database entry for Class with id: '$R->{$primary}'") unless defined $F{$DBFields[0]};
198
 
199
    # If the DB returns a null value, HTML::Tiny doesn't like it, so make sure nulls are converted to empty strings.
200
    map { $F{$_} = "" unless $F{$_} } @DBFields;
201
 
202
    if ($view eq "Update") {
203
      # We'd like to update that thing, give the user a form...
204
      print $h->p ("Updating Class: $R->{$primary}...");
205
 
206
      foreach (@DBFields) {
207
        $F{$_} = formField ($_, $F{$_});
208
      }
209
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0],   value=> $F{$DBFields[0]} });
210
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>"classshiftid", value=> $classshiftid    });
211
 
212
      $actionbutton = formField ("choice", "Save");
213
      $actionbutton .= formField ("Cancel");
214
    } elsif ($view eq "Copy") {
215
      # We'd like to copy that thing, give the user a form...
216
      print $h->p ("Copying Class: $R->{$primary}...");
217
 
218
      foreach (@DBFields) {
219
        $F{$_} = formField ($_, $F{$_});
220
      }
221
      $F{$DBFields[0]} = "COPY".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
222
 
223
      $actionbutton = formField ("choice", "Save");
224
      $actionbutton .= formField ("Cancel");
225
    } else {
226
      # We're just looking at it...
227
      print $h->p ("Viewing Class: $R->{$primary}...");
228
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
229
      $F{coach} = $h->a ({ href=>"/schedule/view_user.pl?RCid=$F{coach}" }, getUserDerbyName $F{coach});
230
 
231
      $F{start_time} = convertTime $F{start_time};
232
      $F{end_time}   = convertTime $F{end_time};
233
#      if ($F{assignee_id}) {
234
#        my $temp;
235
#        $temp = getUserDerbyName ($F{assignee_id});
236
#        $temp .= "&nbsp;".$h->a ({ onClick=>"if (confirm('Really? You want to drop this person from the shift?')==true) { window.open('make_shift_change.pl?change=del&RCid=$F{assignee_id}&id=$R->{$primary}','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "[DROP]");
237
#        $F{assignee_id} = $temp;
238
#      } else {
239
#        $F{assignee_id} = $h->a ({ onClick=>"window.open('make_shift_change.pl?change=lookup&id=$R->{$primary}','Confirm Shift Change','resizable,height=260,width=370'); return false;" }, "[ADD USER]");
240
#      }
241
 
242
      $actionbutton = formField ("choice", "Update") unless $LVL < RollerCon::ADMIN;
243
      if ($view eq "POSTSAVE" or $choice eq "View") {
244
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
245
      } else {
246
        $actionbutton .= formField ("Cancel", "Back");
247
      }
248
    }
249
  } else {
250
    error ("No Game id provided.") unless $LVL >= RollerCon::ADMIN;
251
 
252
    print $h->p ("Adding a new Class...");
253
 
254
    foreach (@DBFields) {
255
      $F{$_} = formField ($_);
256
    }
257
		$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
258
 
259
    $actionbutton = formField ("choice", "Save");
260
    $actionbutton .= formField ("Cancel");
261
  }
262
 
263
 
264
	print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });
265
	print $h->div ({ class=>"sp0" },
266
	  $h->div ({ class=>"rTable" }, [ map ({
267
      $h->div ({ class=>"rTableRow" }, [
268
        $h->div ({ class=>"rTableCell right top", style=>"font-size:unset;" }, "$fieldDisplayName{$_}: "),
269
        $h->div ({ class=>"rTableCell", style=>"font-size:unset;" }, $F{$_})
270
      ])
271
       } sort fieldOrder keys %FIELDS),
272
   ])
273
  );
274
 
275
  print $actionbutton;
276
  print $h->close ("form");
277
 
278
  if ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::VOLUNTEER) {
279
    my $dbh = WebDB::connect ();
280
    my ($count) = $dbh->selectrow_array ("select count from v_class where $primary = ?", undef, $R->{$primary});
281
 
282
    if ($F{$DBFields[0]} !~ /^(NEW|COPY)/) {
283
      my @A = $dbh->selectall_array ("select role, official.RCid, derby_name from v_class_signup join official on v_class_signup.RCid = official.RCid where $primary = ? order by role", undef, $R->{$primary});
284
 
285
      my $classkey = join '|', $F{date}, $F{start_time}, $F{location};
286
      my $adduserlink  = (scalar @A < $F{capacity} and ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::LEAD)) ? $h->a ({ style=>"color:unset;font-size:x-small;", onClick=>"window.open('make_shift_change.pl?change=lookup&RCid=$RCid&id=$classkey','Confirm Shift Change','resizable,height=260,width=370'); return false;" }, "[ADD USER]") : "";
287
 
288
      print $h->br, $h->br;
289
      print $h->div ({ class=>"index", style=>"max-width:610px" }, [ $h->p ({ class=>"heading" }, [ "Sign-ups:&nbsp;&nbsp;", $adduserlink ]),
290
        $h->ul ( [ map { $h->li ({ class=>"shaded", style=>"margin:4px;" },
291
    	    $h->div ({ class=>"lisp0" }, [
292
            $h->div ({ class=>"liLeft"  }, [ $$_[0], ":&nbsp;&nbsp;", $h->a ({ href=>"/schedule/view_user.pl?RCid=$$_[1]" }, $$_[2]) ]),
293
            $h->div ({ class=>"liRight" }, ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::LEAD) ? $h->a ({ style=>"font-size:small", onClick=>"if (confirm('Really? Delete $$_[2] from this class?')==true) { window.open('make_shift_change.pl?change=del&RCid=$$_[1]&id=$R->{$primary}&role=$$_[0]','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "[DROP]") : "")
294
          ])
295
        ) } @A ])
296
      ]);
297
    }
298
    $dbh->disconnect;
299
  }
300
}
301
 
302
sub process_form  {
303
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
304
 
305
  my %FORM;
306
  foreach (keys %FIELDS) {
307
  	if ($fieldType{$_} =~ /^text/) {
308
  		$FORM{$_} = WebDB::trim param ($_) // "";
309
  	} else {
310
	  	$FORM{$_} = param ($_) // "";
311
  	}
312
  }
313
	$FORM{classshiftid} = param ("classshiftid") unless !param ("classshiftid");
314
 
315
  	 # check for required fields
316
	my @errors = ();
317
	foreach (@requiredFields) {
318
		push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "";
319
	}
320
	push @errors, "Capacity should be a whole number." unless $FORM{capacity} =~ /^\d+$/;
321
 
322
  if (@errors)	 {
323
    print $h->div ({ class=>"error" }, [
324
  	  $h->p ("The following errors occurred:"),
325
  	  $h->ul ($h->li (@errors)),
326
  	  $h->p ("Please click your Browser's Back button to\n"
327
  	  	   . "return to the previous page and correct the problem.")
328
  	]);
329
  	return;
330
  }	 # Form was okay.
331
 
332
  $FORM{id} = saveForm (\%FORM);
333
 
334
	print $h->p ({ class=>"success" }, "Class successfully saved.");
335
 
336
  display_form ({ $primary=>$FORM{id} }, "POSTSAVE");
337
}
338
 
339
sub error {
340
	my $msg = shift;
341
	print $h->p ({ class=>"error" }, "Error: $msg");
342
  print $h->close("html");
343
	exit (0);
344
}
345
 
346
sub formField {
347
	my $name  = shift;
348
	my $value = shift // '';
349
	my $context = shift // '';
350
	my $type = $fieldType{$name} // "button";
351
 
352
  if ($type eq "button") {
353
		if ($name eq "Cancel") {
354
		  if ($context eq "POSTSAVE") {
355
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"classes.pl\"; return false;" });
356
		  } else {
357
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });
358
		  }
359
		} else {
360
			return $h->input ({ type=>"submit", value => $value, name=>$name })
361
		}
362
 
363
	} elsif ($type eq "textarea") {
364
	  return $h->tag ("textarea", {
365
	    name => $name,
366
	    override => 1,
367
			cols => 30,
368
			rows => 4
369
	  }, $value);
370
 
371
  } elsif ($type eq "select") {
372
    no strict;
373
    return &{"select_".$name} ($value);
374
	}	elsif ($type eq "auto") {
375
	  return $name eq "assignee_id" ? getUserDerbyName ($value) : $value;
376
  }	elsif ($type eq "time") {
377
	  return $h->input ({
378
	    name => $name,
379
	    type => $type,
380
	    value => $value,
381
	    step => 900,
382
	    required => [],
383
	    override => 1,
384
	    size => 30
385
	  });
386
  }	elsif ($type eq "number") {
387
    return $h->input ({ name=>$name, type=>"number", value=>$value, step=>1 });
388
  }	elsif ($type eq "switch") {
389
    if ($value) {
390
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
391
    } else {
392
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);
393
    }
394
	}	else {
395
	  use tableViewer;
396
	  if (inArray ($name, \@requiredFields)) {
397
  	  return $h->input ({
398
  	    name => $name,
399
  	    type => $type,
400
  	    value => $value,
401
  	    required => [],
402
  	    override => 1,
403
  	    size => 30
404
  	  });
405
	  } else {
406
  	  return $h->input ({
407
  	    name => $name,
408
  	    type => $type,
409
  	    value => $value,
410
  	    override => 1,
411
  	    size => 30
412
  	  });
413
  	}
414
	}
415
}
416