Rev 192 | Blame | Compare with Previous | Last modification | View Log | RSS feed
#!/usr/bin/perl# Redirect error messages to a log of my choosing. (it's annoying to filter for errors in the shared env)my $error_log_path = $ENV{SERVER_NAME} eq "volunteers.rollercon.com" ? "/home3/rollerco/logs/" : "/tmp/";close STDERR;open STDERR, '>>', $error_log_path.'vorc_error.log' or warn "Failed to open redirected logfile ($0): $!";#warn "Redirecting errors to ${error_log_path}vorc_error.log";use strict;use cPanelUserConfig;use WebDB;use HTML::Tiny;use RollerCon;use CGI qw/param header start_html url url_param/;my $h = HTML::Tiny->new( mode => 'html' );my %F;my $cookie_string = authenticate (RollerCon::USER) || die;our ($EML, $PWD, $LVL) = split /&/, $cookie_string;my $user = getUser ($EML);$user->{department} = convertDepartments $user->{department};my $DepartmentNames = getDepartments ();my $username = $user->{derby_name};my $RCid = $user->{RCid};my $RCAUTH_cookie = CGI::Cookie->new(-name=>'RCAUTH',-value=>"$cookie_string",-expires=>"+30m");my $YEAR = 1900 + (localtime)[5];my $pageTitle = "Missing Hours";my $homeURL = "/schedule/";my $DBTable = "shift";my %FIELDS = (id => [qw(ShiftID 5 auto static )],dept => [qw(Department 10 select required )],role => [qw(Role 15 text required )],type => [qw(Type 20 select manager )],date => [qw(Date 25 date required )],location => [qw(Location 30 text required )],start_time => [qw(Start 35 time required )],end_time => [qw(End 40 time required )],doubletime => [qw(DoubleHours 42 switch manager )],assignee_id => [qw(Assignee 50 auto manager )],mod_time => [qw(ModTime 45 number manager )],note => [qw(Notes 55 textarea )],);my %fieldDisplayName = map { $_ => $FIELDS{$_}->[0] } keys %FIELDS;my %fieldType = map { $_ => $FIELDS{$_}->[2] } keys %FIELDS;my @requiredFields = sort fieldOrder grep { defined $FIELDS{$_}->[3] and $FIELDS{$_}->[3] ne "manager" } keys %FIELDS;my @DBFields = sort fieldOrder grep { $fieldType{$_} =~ /^(text|select|number|switch|date|time|auto)/ } keys %FIELDS;my @ROFields = sort fieldOrder grep { $fieldType{$_} =~ /^(readonly)/ } keys %FIELDS;my @MGRFields = sort fieldOrder grep { $FIELDS{$_}->[3] eq "manager" } keys %FIELDS;my $primary = $DBFields[0];print header (-cookie=>$RCAUTH_cookie),start_html (-title => $pageTitle, -style => {'src' => "/style.css"} );print $h->div ({ class => "accent pageheader" }, [$h->h1 ($pageTitle),$h->div ({ class=>"sp0" }, [$h->div ({ class=>"spLeft" }, []),$h->div ({ class=>"spRight" }, [$h->input ({ type=>"button", value=>"Home", onClick=>"window.location.href='$homeURL'" }),]),]),]);my $choice = param ("choice") // "";if ($choice eq "Save") {process_form ();} elsif (defined (param ($primary) || url_param ($primary))) {my $thing = param ($primary); $thing //= url_param ($primary);if ($choice eq "Delete") {delete_item ({ $primary => $thing });} elsif ($choice eq "Approve") {decide_hours ({ $primary => $thing }, "approved");} elsif ($choice eq "Deny") {decide_hours ({ $primary => $thing }, "denied");} elsif ($choice eq "Pend") {decide_hours ({ $primary => $thing }, "request");} else {display_form ({ $primary => $thing }, $choice);}} else {display_form (); # blank form}print $h->close ("html");sub fieldOrder {$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];}sub saveForm {my $FTS = shift;my $dbh = WebDB::connect ();if ($FTS->{$DBFields[0]} eq "NEW") {# Check to make sure the user is requesting hours from one of their volunteer departments.error ("You need to be a volunteer in the Department that you're requesting hours from.") unless $user->{department}->{$FTS->{dept}} > 0;# Check to see if their request overlaps with any existing shifts?my $conflicts = findConflict ($user->{RCid}, [$FTS->{date}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{id}], "personal");if ($conflicts) {error ("You already have a shift that conflicts with that time [$conflicts].");}$dbh->do ("INSERT INTO $DBTable(dept,role,type,date,location,start_time,end_time,doubletime,note,assignee_id)VALUES(?,?,?,?,?,?,?,?,?,?)",undef,$FTS->{dept}, $FTS->{role}, "request", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, 0, $FTS->{note}, $user->{RCid});($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}, "request", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note});logit ($RCid, "$username requested missing hours ($FTS->{id}, $FTS->{dept}, $FTS->{role}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time})");} else {($FTS->{assignee_id}) = $dbh->selectrow_array ("select assignee_id from $DBTable where $primary = ?", undef, $FTS->{$primary});if ($FTS->{assignee_id} != $user->{RCid} and$user->{department}->{$FTS->{dept}} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {error ("This isn't your request, and you're not a Manager in the $DepartmentNames->{$FTS->{dept}} department!");}if ($FTS->{assignee_id} == $user->{RCid} and$user->{department}->{$FTS->{dept}} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {$dbh->do ("UPDATE $DBTableSET dept=?, role=?, date=?, location=?, start_time=?, end_time=?, note=?WHERE id = ?",undef,$FTS->{dept}, $FTS->{role}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note}, $FTS->{id});} else {$FTS->{type} = "request" unless $FTS->{type};if ($FTS->{mod_time}) {$dbh->do ("UPDATE $DBTableSET dept=?, role=?, type=?, date=?, location=?, start_time=?, end_time=?, mod_time=?, doubletime=?, note=?WHERE id = ?",undef,$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});} else {$dbh->do ("UPDATE $DBTableSET dept=?, role=?, type=?, date=?, location=?, start_time=?, end_time=?, mod_time=null, doubletime=?, note=?WHERE id = ?",undef,$FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{doubletime}, $FTS->{note}, $FTS->{id});}}logit ($RCid, "$username updated hours request ($FTS->{id}, $FTS->{dept}, $FTS->{role}, $FTS->{type}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time})");}$dbh->disconnect (); # stored into database successfully.return $FTS->{id};}sub delete_item {my $X = shift;my $dbh = WebDB::connect ();my ($assignee, $hours_dept) = $dbh->selectrow_array ("select assignee_id, dept from $DBTable where $primary = ?", undef, $X->{$primary});if ($assignee != $user->{RCid} and$user->{department}->{$hours_dept} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {logit ($RCid, "$username tried to delete hours request ($X->{$primary})");error ("ERROR: You don't have permission to delete this hours request!");}$dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});$dbh->disconnect ();logit ($RCid, "$username deleted hours request ($X->{$primary})");print "Hours Request Deleted: $X->{$primary}", $h->br;print &formField ("Cancel", "Back", "POSTSAVE");}sub decide_hours {my $X = shift;my $decision = shift;my $dbh = WebDB::connect ();my ($hours_dept) = $dbh-> selectrow_array ("select dept from $DBTable where id = ?", undef, $X->{$primary});error ("Hours Request not found [$X->{$primary}]") unless $hours_dept;if ($user->{department}->{$hours_dept} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {error ("You're not a Manager in the $DepartmentNames->{$hours_dept} department!");}$dbh->do ("update $DBTable set type = ? where $primary = ?", undef, $decision, $X->{$primary});$dbh->disconnect ();logit ($RCid, "$username $decision hours request ($X->{$primary})");$decision = "pended" if $decision eq "request";print "Hours ".ucfirst $decision.": $X->{$primary}", $h->br;# print &formField ("Cancel", "Back", "POSTSAVE");display_form ({ $primary => $X->{$primary} }, "View");}sub select_dept {my $selection = shift;my @optionList;@optionList = grep { $user->{department}->{$_} >= 1 } keys %{ $user->{department} };return $h->select ({ name=>"dept" },[ map { $selection eq $_ ?$h->option ({ value=>$_, selected=>[] }, $DepartmentNames->{$_}) :$h->option ({ value=>$_ }, $DepartmentNames->{$_})} "", @optionList ]);};sub select_type {my $value = shift // "";return $h->select ({ name=>"type" },[ map { $value eq $_ ?$h->option ({ value=>$_, selected=>[] }, $_) :$h->option ({ value=>$_ }, $_)} "", qw(open lead manager selected)]);};sub display_form {my $R = shift;my $view = shift // "";my $actionbutton;#$view = "View" unless $LVL >= RollerCon::ADMIN;if ($view eq "POSTSAVE" and $R->{$primary} eq "NEW") {print &formField ("Cancel", "Back", "POSTSAVE");return;}if ($R) {# we're dealing with an existing thing. Get the current values out of the DB...my $dbh = WebDB::connect ();@F{@DBFields} = $dbh->selectrow_array ("SELECT ". join (", ", @DBFields) ." FROM $DBTable WHERE $primary = ?",undef, $R->{$primary});$dbh->disconnect ();# did we find a record?error ("Cannot find a database entry for '$R->{$primary}'") unless defined $F{$DBFields[0]};# If the DB returns a null value, HTML::Tiny doesn't like it, so make sure nulls are converted to empty strings.map { $F{$_} = "" unless $F{$_} } @DBFields;## Check to make sure the user can actually see the shiftif ($F{assignee_id} != $user->{RCid} and$user->{department}->{$F{dept}} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {error ("This isn't your request, and you're not a Manager in the $DepartmentNames->{$F{dept}} department!");}if ($view eq "Update") {# We'd like to update that thing, give the user a form...print $h->p ("Updating Hours Request: $R->{$primary}...");foreach (@DBFields) {$F{$_} = formField ($_, $F{$_});}$F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });$actionbutton = formField ("choice", "Save");$actionbutton .= formField ("Cancel");} else {# We're just looking at it...print $h->p ("Viewing Hours Request: $R->{$primary}...");$F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });if ($F{assignee_id} == $user->{RCid} and $F{type} eq "request") {# Users can update or delete their own requests.$actionbutton = formField ("choice", "Update");$actionbutton .= formField ("choice", "Delete");}if ($user->{department}->{$F{dept}} >= RollerCon::MANAGER or$user->{department}->{VCI} >= RollerCon::MANAGER or$LVL >= RollerCon::ADMIN) {# Department (and VCI) Managers + SysAdmins have more capabilities$actionbutton = formField ("choice", "Update");$actionbutton .= formField ("choice", "Pend") unless $F{type} eq "request";$actionbutton .= formField ("choice", "Approve") unless $F{type} eq "approved";$actionbutton .= formField ("choice", "Deny") unless $F{type} eq "denied";$actionbutton .= formField ("choice", "Delete");}if ($view eq "POSTSAVE" or $choice eq "View") {$actionbutton .= formField ("Cancel", "Back", "POSTSAVE");} else {$actionbutton .= formField ("Cancel", "Back");}$F{assignee_id} = getUserDerbyName ($F{assignee_id});$F{dept} = $DepartmentNames->{$F{dept}};$F{doubletime} = $F{doubletime} ? "TRUE" : "FALSE";}} else {# Display the blank form for a new submission...print $h->p ("Request missing volunteer hours...");if (!scalar grep { $user->{department}->{$_} >= 1 } keys %{ $user->{department} }) {error ("You need to be a volunteer in at least one department to request missing volunteer hours.");}foreach (@DBFields) {$F{$_} = formField ($_) unless inArray($_, \@MGRFields);}$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });# Users shouldn't see some of the fields that are reserved for Manager updates.foreach (@MGRFields) { delete $FIELDS{$_}; }$actionbutton = $h->p ({ class=>"hint" }, "Providing extra details of what you were doing or which lead / manager you".$h->br."worked with in the Notes field will help reviewers approve your submission.");$actionbutton .= formField ("choice", "Save");$actionbutton .= formField ("Cancel");}print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });print $h->div ({ class=>"sp0" },$h->div ({ class=>"rTable" }, [ map ({$h->div ({ class=>"rTableRow" }, [$h->div ({ class=>"rTableCell right top" }, "$fieldDisplayName{$_}: "),$h->div ({ class=>"rTableCell" }, $F{$_})])} sort fieldOrder keys %FIELDS),]));print $actionbutton;print $h->close ("form");}sub process_form {my %FORM;foreach (keys %FIELDS) {if ($fieldType{$_} =~ /^text/) {$FORM{$_} = WebDB::trim param ($_) // "";} else {$FORM{$_} = param ($_) // "";}}if ($FORM{id} ne "NEW" and$FORM{assignee_id} != $user->{RCid} and$user->{department}->{$FORM{dept}} < RollerCon::MANAGER and$user->{department}->{VCI} < RollerCon::MANAGER and$LVL < RollerCon::ADMIN) {error ("This isn't your request, and you're not a Manager in the $DepartmentNames->{$FORM{dept}} department!");}my @errors = ();# check for required fieldsforeach (@requiredFields) {push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "";}if (@errors) {print $h->div ({ class=>"error" }, [$h->p ("The following errors occurred:"),$h->ul ($h->li (@errors)),# TO-DO: Give the users a back button?$h->p ("Please click your Browser's Back button to\n". "return to the previous page and correct the problem.")]);return;} # Form was okay.$FORM{id} = saveForm (\%FORM);print $h->p ({ class=>"success" }, "Hours request successfully saved.");display_form ({ $primary=>$FORM{id} }, "POSTSAVE");}sub error {my $msg = shift;print $h->p ({ class=>"error" }, "Error: $msg");print $h->close("html");exit (0);}sub formField {my $name = shift;my $value = shift // '';my $context = shift // '';my $type = $fieldType{$name} // "button";if ($type eq "button") {if ($name eq "Cancel") {if ($context eq "POSTSAVE") {return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"shifts.pl\"; return false;" });} else {return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });}} else {if ($value eq "Delete") {return $h->input ({ type=>"submit", value => $value, name=>$name, onClick=>"return confirm('Are you sure?\\nYou can NOT undelete!')" })}return $h->input ({ type=>"submit", value => $value, name=>$name })}} elsif ($type eq "textarea") {return $h->tag ("textarea", {name => $name,override => 1,cols => 30,rows => 4}, $value);} elsif ($type eq "select") {no strict;return &{"select_".$name} ($value);} elsif ($type eq "auto") {return $name eq "assignee_id" ? getUserDerbyName ($value) : $value;} elsif ($type eq "time") {return $h->input ({name => $name,type => $type,value => $value,step => 900,required => [],override => 1,size => 30});} elsif ($type eq "number") {return $h->input ({ name=>$name, type=>"number", value=>$value, step=>.25 });} elsif ($type eq "switch") {if ($value) {return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);} else {return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);}# $F->{department}->{$_} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$_", value=>0, checked=>[] }), $h->span ({ class=>"slider round" })]);} else {use tableViewer;if (inArray ($name, \@requiredFields)) {return $h->input ({name => $name,type => $type,value => $value,required => [],override => 1,size => 30});} else {return $h->input ({name => $name,type => $type,value => $value,override => 1,size => 30});}}}