Subversion Repositories VORC

Rev

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