Subversion Repositories ORC

Rev

Rev 8 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/perl

use strict;
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 (1) || 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 = "2022";


my $pageTitle = "Block Personal Time";
my $homeURL = "/";
my $DBTable = "shift";
my %FIELDS = (
        id          => [qw(ID        5    auto      static )],
#       dept        => [qw(Department    10    select      required )],
        role        => [qw(Brief         15    text      required )],
#       type        => [qw(Type          20    select      required )],
        date        => [qw(Date          25    date        required )],
        location    => [qw(Location      30    text       )],
        start_time  => [qw(Start         35    time        required )],
        end_time    => [qw(End           40    time        required )],
        note        => [qw(Notes         45    textarea         )],
        assignee_id => [qw(AssigneeID    50    readonly         )],
);


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|date|time|auto)/ } keys %FIELDS;
my $primary = $DBFields[0];

sub fieldOrder {
        $FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];
}

sub saveForm {
  my $FTS = shift;
  
  my $dbh = WebDB::connect ();
  
  if (findConflict ($RCid, [$FTS->{date}, $FTS->{start_time}, $FTS->{end_time}], "personal")) {
    
    error ("You already have a shift that conflicts with that time.");
    
    return;
  }
  if ($FTS->{$DBFields[0]} eq "NEW") {
    $dbh->do (
          "INSERT INTO $DBTable
      (dept,role,type,date,location,start_time,end_time,note,assignee_id)
      VALUES(?,?,?,?,?,?,?,?,?)",
          undef,
          "PER", $FTS->{role}, "personal", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note}, $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 = ? and assignee_id = ?", undef, "PER", $FTS->{role}, "personal", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note}, $RCid);
    logit ($RCid, "$username created personal time ($FTS->{id}, $FTS->{role}, $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time})");
  } else {
    $dbh->do (
          "REPLACE INTO $DBTable
      (id,dept,role,type,date,location,start_time,end_time,note,assignee_id)
      VALUES(?,?,?,?,?,?,?,?,?,?)",
          undef,
          $FTS->{id}, "PER", $FTS->{role}, "personal", $FTS->{date}, $FTS->{location}, $FTS->{start_time}, $FTS->{end_time}, $FTS->{note}, $RCid);
    logit ($RCid, "$username updated personal time ($FTS->{id}, $FTS->{role}, $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 ();
  $dbh->do ("delete from $DBTable where $primary = ? and assignee_id = ?", undef, $X->{$primary}, $RCid);
  $dbh->disconnect ();
  logit ($RCid, "$username deleted personal time ($X->{$primary})");
  print "Shift Deleted: $X->{$primary}", $h->br;
  print &formField ("Cancel", "Back", "POSTSAVE");
}


#sub select_dept {
#       my $selection = shift;
#       my @optionList;
#
#  if ($LVL > 4) {
#    @optionList = grep { !/^PER$/ } sort keys %{ $DepartmentNames };
#  } else {
#    @optionList = grep { $user->{department}->{$_} > 2 } 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)]);
#};





print header (),
                        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'" }),
    ]),
  ]),
]);

print $h->div (["Personal time isn't visible to other RollerCon Volunteers or most of leadership*,", $h->br,
                "but it will block your schedule from signing up for conflicting shifts."]);
print $h->h5 (["* It is visible in the database..."]);

my $choice = param ("choice") // "";
if ($choice eq "Save") {
        process_form ();
} 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;
  
  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 = ? and dept = 'PER' and assignee_id = ?",
                      undef, $R->{$primary}, $RCid);
          $dbh->disconnect ();
          
          # did we find a record?
          error ("You don't seem to have Personal Time with that database ID ($R->{$primary}).") unless defined $F{$DBFields[0]};
    
    if ($view eq "Update") {
      # We'd like to update that thing, give the user a form...
      print $h->p ("Updating Personal Time: $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 "Copy") {
      # We'd like to copy that thing, give the user a form...
      print $h->p ("Copying Personal Time: $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 Personal Time: $R->{$primary}...");
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
      $actionbutton = formField ("choice", "Update");
      if ($view eq "POSTSAVE") {
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
      } else {
        $actionbutton .= formField ("Cancel", "Back");
      }
    }
  } else {
    print $h->p ("Adding new Personal Time...");

    foreach (@DBFields) {
      $F{$_} = formField ($_);
    }
                $F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
                
    $actionbutton = formField ("choice", "Save");
    $actionbutton .= formField ("Cancel");
  }
  
  
        print $h->open ("form", { action => url (), 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{$_})
      ])
      } @DBFields),
    ])
  );

  print $actionbutton;
  print $h->close ("form");

}

sub process_form  {
  my %FORM;  
  foreach (keys %FIELDS) {
        if ($fieldType{$_} =~ /^text/) {
                $FORM{$_} = WebDB::trim param ($_) // "";
        } else {
                $FORM{$_} = param ($_) // "";           
        }
  }
        
         # check for required fields
        my @errors = ();
        foreach (@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)),
          $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" }, "Shift 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 = \"/\"; 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 $value;
  }     else {
          return $h->input ({
            name => $name,
            type => $type,
            value => $value,
            required => [],
            override => 1,
            size => 30
          });           
        }
}