Rev 204 | Rev 215 | Go to most recent revision | 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/;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 = "View MVP Class";my $homeURL = "/schedule/";my $DBTable = "class";my %FIELDS = (id => [qw(ClassID 5 auto static )],name => [qw(ClassName 10 text required )],coach => [qw(Coach 15 placeholder )],assistant => [qw(Assistant 17 placeholder )],date => [qw(Date 20 date required )],location => [qw(Location 25 text required )],level => [qw(Level 27 text required )],start_time => [qw(Start 30 time required )],end_time => [qw(End 35 time required )],capacity => [qw(Capacity 40 number required )],note => [qw(Notes 45 textarea )],);my %fieldDisplayName = map { $_ => $FIELDS{$_}->[0] } keys %FIELDS;my %fieldType = map { $_ => $FIELDS{$_}->[2] } keys %FIELDS;my @requiredFields = sort fieldOrder grep { defined $FIELDS{$_}->[3] } 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 $primary = $DBFields[0];sub fieldOrder {$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];}sub saveForm {my $FTS = shift;my $context = shift // "";error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN or ($context eq "Save Note" and $user->{department}->{MVP} >= RollerCon::LEAD);my $dbh = WebDB::connect ();if ($FTS->{$DBFields[0]} eq "NEW") {$dbh->do ("INSERT INTO $DBTable(name,date,location,level,start_time,end_time,capacity,note)VALUES(?,?,?,?,?,?,?,?)",undef,$FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{level}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity}, $FTS->{note});($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});logit ($RCid, "$username created new class ($FTS->{id}, $FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity})");# Coach and Asst Coach need to be added after the class is created so that we have the class id...if ($FTS->{coach}) { change_coach ("save", "coach", $FTS->{id}, $FTS->{coach}); }if ($FTS->{assistant}) { change_coach ("save", "assistant", $FTS->{id}, $FTS->{assistant}); }} elsif ($context eq "Save Note") {# We're just updating the Note...$dbh->do ("update class set note = ? where id = ?", undef, $FTS->{note}, $FTS->{id});logit ($RCid, "$username updated class ($FTS->{id}) with Note: $FTS->{note})");} else {# Update the Coach and Asst Coach volunteer shifts first (so that the original date, time, location still matches...)$dbh->do ("update shift setstart_time = ?,end_time = ?,date = ?,location = ?,note = ?wheredept = ? anddate = (select date from class where id = ?) andlocation = (select location from class where id = ?) andstart_time = (select start_time from class where id = ?)",undef,$FTS->{start_time}, $FTS->{end_time}, $FTS->{date}, $FTS->{location}, $FTS->{name}, "COA", $FTS->{id}, $FTS->{id}, $FTS->{id});# Now update the class.$dbh->do ("UPDATE $DBTableSET name=?, date=?, location=?, level=?, start_time=?, end_time=?, capacity=?, note=?WHERE id = ?",undef,$FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{level}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity}, $FTS->{note}, $FTS->{id});logit ($RCid, "$username updated class ($FTS->{id}, $FTS->{name}, $FTS->{date}, $FTS->{location}, $FTS->{level}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{capacity})");}$dbh->disconnect (); # stored into database successfully.return $FTS->{id};}sub delete_item {error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;my $X = shift;my $dbh = WebDB::connect ();# Delete the Coach and Asst Coach first while we can still do a subselect with the class id...$dbh->do ("delete from shiftwheredept = ? anddate = (select date from class where id = ?) andlocation = (select location from class where id = ?) andstart_time = (select start_time from class where id = ?)",undef,"COA", $X->{$primary}, $X->{$primary}, $X->{$primary});$dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});## If we're deleting a class, we need to also delete all of the sign-ups## TBD: Maybe email all of the attendees that their class is being deleted first?$dbh->do ("delete from assignment where Gid = ? and role like ?", undef, $X->{$primary}, "CLA".'%');$dbh->disconnect ();logit ($RCid, "$username deleted Class ($X->{$primary})");print "Class Deleted: $X->{$primary}", $h->br;print &formField ("Cancel", "Back", "POSTSAVE");}sub select_coach {my $selection = shift // "";return $h->select ({ name=>"coach" }, [ $h->option (""), fetchDerbyNameWithRCid ("COA", $selection) ]);};sub select_assistant {my $selection = shift // "";return $h->select ({ name=>"assistant" }, [ $h->option (""), fetchDerbyNameWithRCid ("COA", $selection) ]);};sub change_coach {my $change = shift // "";my $role = shift // "";my $class_id = shift // "";my $coach_id = shift // "";error ("SECURITY: You're not allowed to change the class coaches!") unless ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::MANAGER or $user->{department}->{VCI} >= RollerCon::MANAGER);my $dbh = WebDB::connect ();if ($change eq "delete") {my ($r1, $r2);if ($role eq "assistant") {$r1 = "Assistant (TA)";$r2 = "Assistant Coach";} else {$r1 = "Coach";$r2 = "Coach";}$dbh->do ("delete from shift whereassignee_id = ? anddept = ? androle in (?, ?) anddate = (select date from class where id = ?) andstart_time = (select start_time from class where id = ?) andlocation = (select location from class where id = ?)", undef,$coach_id, "COA", $r1, $r2, $class_id, $class_id, $class_id);} elsif ($change eq "save") {my $r1 = ($role eq "assistant") ? "Assistant Coach" : "Coach";$dbh->do ("insert into shift (dept, role, type, date, location, start_time, end_time, doubletime, note, assignee_id)select ?, ?, ?, date, location, start_time, end_time, 1, name, ? from class where id = ?", undef,"COA", $r1, "selected", $coach_id, $class_id);}logit ($RCid, "Class Coach Change: $change $role for class $class_id with RCid $coach_id");$dbh->disconnect ();}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 $coaching_change = param ("coachchange") // "";if ($coaching_change =~ /^(save|delete)_/) {my ($change, $role, $class, $coach);$class = param ("id");($change, $role) = split /_/, $coaching_change;if ($change eq "save") {$coach = param ($role);} elsif ($change eq "delete") {($role, $coach) = split /:/, $role;}change_coach ($change, $role, $class, $coach);}my $choice = param ("choice") // "";if ($choice =~ /^Save/) {process_form ($choice);} elsif (defined (param ($primary))) {my $thing = param ($primary);if ($choice eq "Delete") {delete_item ({ $primary => $thing });} else {display_form ({ $primary => $thing }, $choice);}} else {display_form (); # blank form}print $h->close ("html");sub display_form {my $R = shift;my $view = shift // "";my $actionbutton;my $coachRCid;my (@CoachRCids, @AsstCoachRCids);$view = "View" unless $LVL >= RollerCon::ADMIN or ($view eq "Add Note" and $user->{department}->{MVP} >= RollerCon::LEAD);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});# Get the Coach and Assistant Coach shifts...my (@CoachShifts, @AsstCoachShifts);my $shifthand = $dbh->prepare ("select id from shift where dept = ? and role = ? and date = ? and start_time = ? and location = ?");$shifthand->execute ("COA", "Coach", $F{date}, $F{start_time}, $F{location});while (my ($classshiftid) = $shifthand->fetchrow_array ()) {push @CoachShifts, $classshiftid;}$shifthand->execute ("COA", "Assistant Coach", $F{date}, $F{start_time}, $F{location});while (my ($classshiftid) = $shifthand->fetchrow_array ()) {push @AsstCoachShifts, $classshiftid;}$shifthand->execute ("COA", "Assistant (TA)", $F{date}, $F{start_time}, $F{location});while (my ($classshiftid) = $shifthand->fetchrow_array ()) {push @AsstCoachShifts, $classshiftid;}$dbh->disconnect ();# did we find a record?error ("Cannot find a database entry for Class with id: '$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;if ($view eq "Update") {# We'd like to update that thing, give the user a form...print $h->p ("Updating Class: $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");} elsif ($view eq "Add Note") {# Leads may add a note to the class (to include an Asst Coach that doesn't have Coach access yet)print $h->p ("Add a Note to Class: $R->{$primary}...");$F{note} = formField ("note", $F{note});$F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });$actionbutton = formField ("choice", "Save Note");$actionbutton .= formField ("Cancel");} elsif ($view eq "Copy") {# We'd like to copy that thing, give the user a form...print $h->p ("Copying Class: $R->{$primary}...");foreach (@DBFields) {$F{$_} = formField ($_, $F{$_});}$F{$DBFields[0]} = "COPY".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });$actionbutton = formField ("choice", "Save");$actionbutton .= formField ("Cancel");} else {# We're just looking at it...print $h->p ("Viewing Class: $R->{$primary}...");$F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });my $coachEditor = ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::MANAGER or $user->{department}->{VCI} >= RollerCon::MANAGER) ? 1 : 0;$coachRCid = $F{coach};$F{coach} = "";foreach (@CoachShifts) {my $sr = getShiftRef ($_);$F{coach} .= $h->a ({ href=>"/schedule/view_user.pl?RCid=$sr->{assignee_id}" }, getUserDerbyName ($sr->{assignee_id}));$F{coach} .= ' ' . $h->button ({name => "coachchange", value => "delete_coach:$sr->{assignee_id}"}, "Remove") if $coachEditor;$F{coach} .= $h->br;push @CoachRCids, $sr->{assignee_id};}if ($coachEditor) {my $context = param ("coachchange");if ($context eq "add_coach") {$F{coach} .= select_coach () . $h->button ({name => "coachchange", value => "save_coach"}, "Save");} else {$F{coach} .= $h->button ({name => "coachchange", value => "add_coach"}, "Add Coach");}}$F{assistant} = "";foreach (@AsstCoachShifts) {my $sr = getShiftRef ($_);$F{assistant} .= $h->a ({ href=>"/schedule/view_user.pl?RCid=$sr->{assignee_id}" }, getUserDerbyName $sr->{assignee_id});$F{assistant} .= ' ' . $h->button ({name => "coachchange", value => "delete_assistant:$sr->{assignee_id}"}, "Remove") if $coachEditor;$F{assistant} .= $h->br;push @AsstCoachRCids, $sr->{assignee_id};}if ($coachEditor) {my $context = param ("coachchange");if ($context eq "add_assistant") {$F{assistant} .= select_assistant () . $h->button ({name => "coachchange", value => "save_assistant"}, "Save");} else {$F{assistant} .= $h->button ({name => "coachchange", value => "add_assistant"}, "Add Assistant");}}$F{start_time} = convertTime $F{start_time};$F{end_time} = convertTime $F{end_time};$actionbutton = formField ("choice", "Update") unless $LVL < RollerCon::ADMIN;$actionbutton .= formField ("choice", "Add Note") if $user->{department}->{MVP} >= RollerCon::LEAD;if ($view eq "POSTSAVE" or $choice eq "View") {$actionbutton .= formField ("Cancel", "Back", "POSTSAVE");} else {$actionbutton .= formField ("Cancel", "Back");}}} else {error ("No Game id provided.") unless $LVL >= RollerCon::ADMIN;print $h->p ("Adding a new Class...");foreach (@DBFields) {$F{$_} = formField ($_);}$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });$F{coach} = select_coach ();$F{assistant} = select_assistant ();$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", style=>"font-size:unset;" }, "$fieldDisplayName{$_}: "),$h->div ({ class=>"rTableCell", style=>"font-size:unset;" }, $F{$_})])} sort fieldOrder keys %FIELDS),]));print $actionbutton;print $h->close ("form");print $h->p ($h->input ({ type=>"button", onClick=>"window.location.href='email_users.pl?type=class&ID=$R->{$primary}';", value=>"Email Users" })) unless $LVL < RollerCon::ADMIN;my $dbh = WebDB::connect ();my ($class_is_over) = $dbh->selectrow_array ("select 1 from v_class_new where $primary = ? and concat_ws(' ', date, end_time) < date_sub(now(), interval 2 hour)", undef, $R->{$primary});# View the list of people signed up for the class...if ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::LEAD) {my ($count) = $dbh->selectrow_array ("select count from v_class_new where $primary = ?", undef, $R->{$primary});if ($F{$DBFields[0]} !~ /^(NEW|COPY)/) {my @A = @{$dbh->selectall_arrayref ("select role, official.RCid, derby_name from v_class_signup_new join official on v_class_signup_new.RCid = official.RCid where $primary = ? order by role", undef, $R->{$primary})};my $classkey = join '|', $F{date}, $F{start_time}, $F{location};my $adduserlink = ($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]") : "";print $h->br, $h->br;print $h->div ({ class=>"index", style=>"max-width:610px" }, [ $h->p ({ class=>"heading" }, [ "Sign-ups: ", $adduserlink ]),$h->ul ( [ map { $h->li ({ class=>"shaded", style=>"margin:4px;" },$h->div ({ class=>"lisp0" }, [$h->div ({ class=>"liLeft" }, [ $$_[0], ": ", $h->a ({ href=>"/schedule/view_user.pl?RCid=$$_[1]" }, $$_[2]) ]),$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]") : "")])) } @A ])]);}}# View the survey results...use tableViewer qw/inArray/;if (($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::LEAD or inArray ($ORCUSER->{RCid}, \@CoachRCids)) and $class_is_over) {my ($response_count) = $dbh->selectrow_array ("select count(distinct(RCid)) from v_survey_answer where classid = ?", undef, $R->{$primary});my $exclude_private = ($LVL >= RollerCon::ADMIN or $user->{department}->{MVP} >= RollerCon::LEAD) ? "" : "and private = 0";my @RESPONSES = @{$dbh->selectall_arrayref ("select qorder, type, question, average, qid from v_survey_results where classid = ? $exclude_private order by qorder", undef, $R->{$primary})};print $h->br, $h->br;print $h->div ({ class=>"index", style=>"max-width:610px" }, [ $h->p ({ class=>"heading" }, [ "Survey Results: ", $response_count." Response".(($response_count > 1) ? "s" : "") ]),$h->ul ( [ map { $h->li ({ class=>"shaded", style=>"margin:4px;" },$h->div ({ class=>"lisp0" }, [$h->div ({ class=>"liLeft" }, [ $$_[0], ": ", $$_[2] ]),$h->div ({ class=>"liRight" }, [ $$_[1] eq "text" ?$h->a ({ href=>"view_survey_comments.pl?classid=$R->{$primary}&qid=$$_[4]" }, [ $$_[3], (($$_[3] == 1) ? " comment" : " comments") ]) :$$_[3] ])])) } @RESPONSES ])]);}$dbh->disconnect;}sub process_form {my $context = shift // "";error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN or ($context eq "Save Note" and $user->{department}->{MVP} >= RollerCon::LEAD);my %FORM;foreach (keys %FIELDS) {if ($fieldType{$_} =~ /^text/) {$FORM{$_} = WebDB::trim param ($_) // "";} else {$FORM{$_} = param ($_) // "";}}# check for required fieldsmy @errors = ();foreach (@requiredFields) {push @errors, "$fieldDisplayName{$_} is missing." if ($FORM{$_} eq "" and $context ne "Save Note");}push @errors, "Capacity should be a whole number." unless ($FORM{capacity} =~ /^\d+$/ or $context eq "Save Note");if (@errors) {print $h->div ({ class=>"error" }, [$h->p ("The following errors occurred:"),$h->ul ($h->li (@errors)),$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, $context);print $h->p ({ class=>"success" }, "Class 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 = \"classes.pl\"; return false;" });} else {return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });}} else {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=>1 });} 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" })]);}} elsif ($type eq "placeholder") {} else {use tableViewer qw/inArray/;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});}}}