Subversion Repositories VORC

Rev

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