Subversion Repositories VORC

Rev

Rev 195 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
7 - 1
#!/usr/bin/perl
2
 
56 bgadell 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
 
7 - 9
use strict;
8 - 10
use cPanelUserConfig;
7 - 11
use WebDB;
12
use HTML::Tiny;
13
use RollerCon;
226 - 14
use CGI qw/param header start_html url url_param/;
7 - 15
my $h = HTML::Tiny->new( mode => 'html' );
16
 
17
my %F;
18
 
56 bgadell 19
my $cookie_string = authenticate (RollerCon::USER) || die;
7 - 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");
53 bgadell 27
my $YEAR = 1900 + (localtime)[5];
7 - 28
 
29
 
30
my $pageTitle = "Manage Shift";
8 - 31
my $homeURL = "/schedule/";
7 - 32
my $DBTable = "shift";
33
my %FIELDS = (
34
	id          => [qw(ShiftID        5    auto      static )],
35
	dept        => [qw(Department    10    select      required )],
36
	role        => [qw(Role          15    text      required )],
37
	type        => [qw(Type          20    select      required )],
38
	date        => [qw(Date          25    date        required )],
39
	location    => [qw(Location      30    text      required )],
40
	start_time  => [qw(Start         35    time        required )],
41
	end_time    => [qw(End           40    time        required )],
29 - 42
	doubletime  => [qw(DoubleHours   42    switch        )],
7 - 43
	assignee_id => [qw(Assignee      50    auto         )],
44
	mod_time    => [qw(ModTime       45    number         )],
45
	note        => [qw(Notes         55    textarea       )],
46
);
47
 
48
 
49
my %fieldDisplayName = map  { $_ => $FIELDS{$_}->[0]   } keys %FIELDS;
50
my %fieldType        = map  { $_ => $FIELDS{$_}->[2]   } keys %FIELDS;
51
my @requiredFields   = sort fieldOrder grep { defined $FIELDS{$_}->[3] } keys %FIELDS;
29 - 52
my @DBFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(text|select|number|switch|date|time|auto)/ } keys %FIELDS;
7 - 53
my @ROFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(readonly)/ } keys %FIELDS;
54
my $primary = $DBFields[0];
55
 
56
sub fieldOrder {
57
	$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];
58
}
59
 
60
sub saveForm {
56 bgadell 61
  error ("ERROR: Only SysAdmins can change shifts.") unless $LVL >= RollerCon::ADMIN;
62
 
7 - 63
  my $FTS = shift;
64
 
65
  my $dbh = WebDB::connect ();
66
  if ($FTS->{$DBFields[0]} eq "NEW") {
29 - 67
    if ($FTS->{mod_time}) {
68
      $dbh->do (
69
    	  "INSERT INTO $DBTable
70
        (dept,role,type,date,location,start_time,end_time,mod_time,doubletime,note)
71
        VALUES(?,?,?,?,?,?,?,?,?,?)",
72
    	  undef,
73
    	  $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{mod_time}, $FTS->{doubletime}, $FTS->{note}
74
    	);
75
    } else {
76
      $dbh->do (
77
    	  "INSERT INTO $DBTable
78
        (dept,role,type,date,location,start_time,end_time,doubletime,note)
79
        VALUES(?,?,?,?,?,?,?,?,?)",
80
    	  undef,
81
    	  $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{doubletime}, $FTS->{note}
82
    	);
83
    }
7 - 84
  	($FTS->{id}) = $dbh-> selectrow_array ("select max(id) from $DBTable where dept = ? and role = ? and type = ? and date = ? and location = ? and start_time = ? and end_time = ? and note = ?", undef, $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note});
29 - 85
    logit ($RCid, "$username created new shift ($FTS->{id}, $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{mod_time}, $FTS->{doubletime})");
7 - 86
  } else {
87
    if ($FTS->{mod_time}) {
88
      $dbh->do (
89
        "UPDATE $DBTable
29 - 90
        SET dept=?, role=?, type=?, date=?, location=?, start_time=?, end_time=?, mod_time=?, doubletime=?, note=?
7 - 91
        WHERE id = ?",
92
        undef,
29 - 93
        $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{mod_time}, $FTS->{doubletime}, $FTS->{note}, $FTS->{id}
7 - 94
      );
95
    } else {
96
      $dbh->do (
97
        "UPDATE $DBTable
29 - 98
        SET dept=?, role=?, type=?, date=?, location=?, start_time=?, end_time=?, mod_time=null, doubletime=?, note=?
7 - 99
        WHERE id = ?",
100
        undef,
29 - 101
        $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{doubletime}, $FTS->{note}, $FTS->{id}
7 - 102
      );
103
    }
104
    logit ($RCid, "$username updated shift ($FTS->{id}, $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time})");
105
	}
106
 
107
	$dbh->disconnect ();	 # stored into database successfully.
108
	return $FTS->{id};
109
}
110
 
111
sub delete_item {
56 bgadell 112
  error ("ERROR: Only SysAdmins can delete shifts.") unless $LVL >= RollerCon::ADMIN;
113
 
7 - 114
  my $X = shift;
115
  my $dbh = WebDB::connect ();
116
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
117
  $dbh->disconnect ();
118
  logit ($RCid, "$username deleted shift ($X->{$primary})");
119
  print "Shift Deleted: $X->{$primary}", $h->br;
120
  print &formField ("Cancel", "Back", "POSTSAVE");
121
}
122
 
123
 
124
sub select_dept {
125
	my $selection = shift;
126
	my @optionList;
127
 
128
  if ($LVL > 4) {
129
    @optionList = grep { !/^PER$/ } sort keys %{ $DepartmentNames };
130
  } else {
131
    @optionList = grep { $user->{department}->{$_} > 2 } keys %{ $user->{department} };
132
  }
133
 
134
  return $h->select ({ name=>"dept" },
135
    [ map { $selection eq $_ ?
136
              $h->option ({ value=>$_, selected=>[] }, $DepartmentNames->{$_}) :
137
              $h->option ({ value=>$_ }, $DepartmentNames->{$_})
138
          } "", @optionList ]);
139
};
140
 
141
sub select_type {
142
  my $value = shift // "";
143
 
144
  return $h->select ({ name=>"type" },
145
    [ map { $value eq $_ ?
146
              $h->option ({ value=>$_, selected=>[] }, $_) :
147
              $h->option ({ value=>$_ }, $_)
148
          } "", qw(open lead manager selected)]);
149
};
150
 
195 - 151
print header (-cookie=>$RCAUTH_cookie),
7 - 152
			start_html (-title => $pageTitle, -style => {'src' => "/style.css"} );
153
 
154
print $h->div ({ class => "accent pageheader" }, [
155
  $h->h1 ($pageTitle),
156
  $h->div ({ class=>"sp0" }, [
157
    $h->div ({ class=>"spLeft" }, [
158
    ]),
159
    $h->div ({ class=>"spRight" }, [
160
      $h->input ({ type=>"button", value=>"Home", onClick=>"window.location.href='$homeURL'" }),
161
    ]),
162
  ]),
163
]);
164
 
165
my $choice = param ("choice") // "";
166
if ($choice eq "Save") {
167
	process_form ();
226 - 168
} elsif (defined (param ($primary) || url_param ($primary))) {
169
  my $thing = param ($primary); $thing //= url_param ($primary);
7 - 170
  if ($choice eq "Delete") {
171
    delete_item ({ $primary => $thing });
172
  } else {
173
	  display_form ({ $primary => $thing }, $choice);
174
	}
175
} else {
176
	display_form (); # blank form
177
}
178
 
179
print $h->close ("html");
180
 
181
sub display_form  {
182
  my $R = shift;
183
  my $view = shift // "";
184
	my $actionbutton;
185
 
56 bgadell 186
  $view = "View" unless $LVL >= RollerCon::ADMIN;
187
 
7 - 188
  if ($view eq "POSTSAVE" and $R->{$primary} eq "NEW") {
189
      print &formField ("Cancel", "Back", "POSTSAVE");
190
      return;
191
  }
192
 
193
  if ($R) {
194
    # we're dealing with an existing thing.  Get the current values out of the DB...
195
    my $dbh = WebDB::connect ();
196
 
197
	  @F{@DBFields} = $dbh->selectrow_array (
198
                     "SELECT ". join (", ", @DBFields) ." FROM $DBTable WHERE $primary = ?",
199
                      undef, $R->{$primary});
200
	  $dbh->disconnect ();
201
 
202
	  # did we find a record?
203
	  error ("Cannot find a database entry for '$R->{$primary}'") unless defined $F{$DBFields[0]};
204
 
56 bgadell 205
    # If the DB returns a null value, HTML::Tiny doesn't like it, so make sure nulls are converted to empty strings.
206
    map { $F{$_} = "" unless $F{$_} } @DBFields;
207
 
208
    ## Check to make sure the user can actually see the shift
209
    if ($user->{department}->{$F{dept}} < RollerCon::USER and $LVL < RollerCon::ADMIN) {
210
  	  error ("You're not a volunteer in the $DepartmentNames->{$F{dept}} department!");
7 - 211
    }
212
 
213
    if ($view eq "Update") {
214
      # We'd like to update that thing, give the user a form...
215
      print $h->p ("Updating Shift: $R->{$primary}...");
216
 
217
      foreach (@DBFields) {
218
        $F{$_} = formField ($_, $F{$_});
219
      }
220
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
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 Shift: $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 Shift: $R->{$primary}...");
238
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
56 bgadell 239
 
240
      use DateTime;
241
      my $now = DateTime->now (time_zone => 'America/Los_Angeles');
242
 
243
     	my ($yyyy, $mm, $dd) = split /\-/, $F{date};
244
    	my $cutoff = DateTime->new(
245
            year => $yyyy,
246
            month => $mm,
247
            day => $dd,
248
            hour => 5,
249
            minute => 0,
250
            second => 0,
251
            time_zone => 'America/Los_Angeles'
252
      );
253
 
254
     	if (!$F{assignee_id}) {
255
     	  $F{assignee_id} = "OPEN";
256
     		if (signUpEligible ($ORCUSER, \%F, "vol") and $now < $cutoff) {
257
     			# SIGN UP
258
     			$F{assignee_id} .= " | <A HREF='#' onClick=\"event.stopPropagation(); window.open('make_shift_change.pl?change=add&RCid=$RCid&id=$R->{$primary}','Confirm Shift Change','resizable,height=260,width=370'); return false;\">[SIGN UP]</a>";
259
     		}
260
     		if ($user->{department}->{$F{dept}} >= RollerCon::LEAD or $LVL >= RollerCon::ADMIN) {
261
     			# ADD USER
262
     			$F{assignee_id} .= " | <A HREF='#' onClick=\"event.stopPropagation(); window.open('make_shift_change.pl?change=lookup&RCid=$RCid&id=$R->{$primary}','Confirm Shift Change','resizable,height=260,width=370'); return false;\">[ADD USER]</a>";
263
     		}
264
     	} elsif (($F{assignee_id} == $RCid and $F{type} ne "selected" and $now < $cutoff) or $user->{department}->{$F{dept}} >= RollerCon::LEAD or $LVL >= RollerCon::ADMIN) {
265
     	  my $temp = $h->a ({ href=>"/schedule/view_user.pl?RCid=$F{assignee_id}" }, getUserDerbyName ($F{assignee_id}));
266
     		# DROP
267
     		$temp .= " | <A HREF='#' onClick=\"event.stopPropagation(); 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]</a>";
268
     		if ($user->{department}->{$F{dept}} >= RollerCon::LEAD or $LVL >= RollerCon::ADMIN) {
269
     		  # NO SHOW
270
     		  $temp .= " | <A HREF='#' onClick=\"event.stopPropagation(); if (confirm('Really? They were a no show?')==true) { window.open('make_shift_change.pl?noshow=true&change=del&RCid=$F{assignee_id}&id=$R->{$primary}','Confirm Shift Change','resizable,height=260,width=370'); return false; }\">[NO SHOW]</a>";
271
     		}
272
     		$F{assignee_id} = $temp;
273
     	} else {
274
     	  $F{assignee_id} = "FILLED";
275
     	}
276
 
23 - 277
      $F{dept} = $DepartmentNames->{$F{dept}};
29 - 278
      $F{doubletime} = $F{doubletime} ? "TRUE" : "FALSE";
7 - 279
 
56 bgadell 280
      $actionbutton = formField ("choice", "Update") unless $F{dept} eq "Coaching" or $LVL < RollerCon::ADMIN;
55 bgadell 281
      if ($view eq "POSTSAVE" or $choice eq "View") {
7 - 282
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
283
      } else {
284
        $actionbutton .= formField ("Cancel", "Back");
285
      }
286
    }
287
  } else {
56 bgadell 288
    error ("No Shift ID provided.") unless $LVL >= RollerCon::ADMIN;
289
 
7 - 290
    print $h->p ("Adding a new Shift...");
291
 
292
    foreach (@DBFields) {
293
      $F{$_} = formField ($_);
294
    }
295
		$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
296
 
297
    $actionbutton = formField ("choice", "Save");
298
    $actionbutton .= formField ("Cancel");
299
  }
300
 
301
 
302
	print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });
303
	print $h->div ({ class=>"sp0" },
304
	  $h->div ({ class=>"rTable" }, [ map ({
305
      $h->div ({ class=>"rTableRow" }, [
306
        $h->div ({ class=>"rTableCell right top" }, "$fieldDisplayName{$_}: "),
307
        $h->div ({ class=>"rTableCell" }, $F{$_})
308
      ])
309
#      } @DBFields),
310
       } sort fieldOrder keys %FIELDS),
311
   ])
312
  );
313
 
314
  print $actionbutton;
315
  print $h->close ("form");
316
 
317
}
318
 
319
sub process_form  {
56 bgadell 320
  error ("ERROR: Only SysAdmins can change shifts.") unless $LVL >= RollerCon::ADMIN;
321
 
322
  my %FORM;
7 - 323
  foreach (keys %FIELDS) {
324
  	if ($fieldType{$_} =~ /^text/) {
325
  		$FORM{$_} = WebDB::trim param ($_) // "";
326
  	} else {
327
	  	$FORM{$_} = param ($_) // "";
328
  	}
329
  }
330
 
331
  	 # check for required fields
332
	my @errors = ();
333
	foreach (@requiredFields) {
334
		push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "";
335
	}
336
 
337
  if (@errors)	 {
338
    print $h->div ({ class=>"error" }, [
339
  	  $h->p ("The following errors occurred:"),
340
  	  $h->ul ($h->li (@errors)),
341
  	  $h->p ("Please click your Browser's Back button to\n"
342
  	  	   . "return to the previous page and correct the problem.")
343
  	]);
344
  	return;
345
  }	 # Form was okay.
346
 
347
  $FORM{id} = saveForm (\%FORM);
348
 
349
	print $h->p ({ class=>"success" }, "Shift successfully saved.");
350
 
351
  display_form ({ $primary=>$FORM{id} }, "POSTSAVE");
352
}
353
 
354
sub error {
355
	my $msg = shift;
356
	print $h->p ({ class=>"error" }, "Error: $msg");
357
  print $h->close("html");
358
	exit (0);
359
}
360
 
361
sub formField {
362
	my $name  = shift;
363
	my $value = shift // '';
364
	my $context = shift // '';
365
	my $type = $fieldType{$name} // "button";
29 - 366
 
7 - 367
  if ($type eq "button") {
368
		if ($name eq "Cancel") {
369
		  if ($context eq "POSTSAVE") {
56 bgadell 370
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"shifts.pl\"; return false;" });
7 - 371
		  } else {
16 - 372
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });
7 - 373
		  }
374
		} else {
375
			return $h->input ({ type=>"submit", value => $value, name=>$name })
376
		}
377
 
378
	} elsif ($type eq "textarea") {
379
	  return $h->tag ("textarea", {
380
	    name => $name,
381
	    override => 1,
382
			cols => 30,
383
			rows => 4
384
	  }, $value);
385
 
386
  } elsif ($type eq "select") {
387
    no strict;
388
    return &{"select_".$name} ($value);
389
	}	elsif ($type eq "auto") {
390
	  return $name eq "assignee_id" ? getUserDerbyName ($value) : $value;
391
  }	elsif ($type eq "time") {
392
	  return $h->input ({
393
	    name => $name,
394
	    type => $type,
395
	    value => $value,
396
	    step => 900,
397
	    required => [],
398
	    override => 1,
399
	    size => 30
400
	  });
401
  }	elsif ($type eq "number") {
29 - 402
    return $h->input ({ name=>$name, type=>"number", value=>$value, step=>.25 });
403
  }	elsif ($type eq "switch") {
404
    if ($value) {
405
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
406
    } else {
407
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);
408
    }
409
# $F->{department}->{$_} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$_", value=>0, checked=>[] }), $h->span ({ class=>"slider round" })]);
7 - 410
	}	else {
411
	  use tableViewer;
412
	  if (inArray ($name, \@requiredFields)) {
413
  	  return $h->input ({
414
  	    name => $name,
415
  	    type => $type,
416
  	    value => $value,
417
  	    required => [],
418
  	    override => 1,
419
  	    size => 30
420
  	  });
421
	  } else {
422
  	  return $h->input ({
423
  	    name => $name,
424
  	    type => $type,
425
  	    value => $value,
426
  	    override => 1,
427
  	    size => 30
428
  	  });
429
  	}
430
	}
431
}
432