Subversion Repositories PEEPS

Rev

Rev 5 | Rev 14 | 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 WebDB;
use HTML::Tiny;
use PEEPS;
use CGI qw/param header start_html url url_param/;
my $h = HTML::Tiny->new( mode => 'html' );
$ENV{HTTPS} = 'ON' if $ENV{SERVER_NAME} =~ /^peeps/;

my %F;

my $cookie_string = authenticate (1) || die;
our ($EML, $PWD, $LVL) = split /&/, $cookie_string;
my $user = $ORCUSER;
my @adminleagues = isLeagueAdmin ($user->{person_id});
my $username = $user->{derby_name};
my $PEEPSAUTH_cookie = CGI::Cookie->new(-name=>'PEEPSAUTH',-value=>"$cookie_string",-expires=>"+30m");
my $YEAR = 1900 + (localtime)[5];
my $dbh = getDBConnection ();

my $pageTitle = "View League";
my $homeURL = "/";
my $DBTable = "organization";
my %FIELDS = (
        id                  => [qw(ID               5    auto      static   )],
        league_name         => [qw(DisplayName     10    text      required )],
        business_name       => [qw(BusinessName    15    text               )],
        city                => [qw(City            20    text               )],
        state_province      => [qw(State/Province  25    text               )],
        country             => [qw(Country         30    text               )],
        url                 => [qw(URL             35    text               )],
        type                => [qw(Type            40    select    required )],
        status              => [qw(Status          45    select    required )],
        legal_entity_type   => [qw(LegalType       50    text               )],
        tax_id              => [qw(TaxID           55    text               )],
        date_established    => [qw(Established     60    date               )],
        updated             => [qw(Updated         65    readonly  static   )],
);


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 @SAFields = qw/ league_name business_name type status legal_entity_type /;
my $primary = $DBFields[0];

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



print header (-cookie=>$PEEPSAUTH_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 %GETFORM = map { split /=/ } split /&/, $ENV{QUERY_STRING};
$GETFORM{$primary} = WebDB::trim scalar param ("id") unless $GETFORM{$primary};
my $choice = param ("choice") || $GETFORM{choice} // "";

my $org = getLeagueAffiliation ($ORCUSER->{person_id});
my $leagueAdmin = inArray ("League Admin", $org->{$GETFORM{$primary}}) unless !$org->{$GETFORM{$primary}};

if ($choice eq "Save") {
        process_form ();
} elsif (defined (param ($primary)) || $GETFORM{$primary} || url_param ($primary)) {
  my $thing = param ($primary) || $GETFORM{$primary}; $thing //= url_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;
  
  $view = "View" unless $ORCUSER->{SYSADMIN};
  
  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...
    
          @F{@DBFields,@ROFields} = $dbh->selectrow_array (
                     "SELECT ". join (", ", @DBFields, @ROFields) ." FROM $DBTable WHERE $primary = ?",
                      undef, $R->{$primary});
          
          # did we find a record?
          error ("Cannot find a database entry 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, @ROFields;
    
          
    if ($view eq "Update") {
      # We'd like to update that thing, give the user a form...
      print $h->p ("Updating League: $R->{$primary}...");
      
      foreach (@DBFields) {
        $F{$_} = formField ($_, $F{$_});
      }
      
      $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 League: $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 League: $R->{$primary}...");
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });

      # Put the time fields into the user's preference
      map { $F{$_} = convertTime $F{$_} } grep { $fieldType{$_} eq "time" } keys %FIELDS;
      
      $actionbutton = formField ("choice", "Update") if $ORCUSER->{SYSADMIN};
      if ($view eq "POSTSAVE" or $choice eq "View") {
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
      } else {
        $actionbutton .= formField ("Cancel", "Back");
      }
    }
  } else {
    error ("No Organization ID provided.") unless $ORCUSER->{SYSADMIN};

    print $h->p ("Adding a new League...");

    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 (), 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;
  
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
  my @policy_columns = qw(id organization_id policy_name fee created start end active);
  
  my @policies = @{ $dbh->selectall_arrayref ("select ".join (", ", @policy_columns)." from org_coverage where organization_id = ? order by start desc, end", undef, $R->{$primary}) };
  my $active_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA General Liability Insurance");
  my $active_alcohol_policy = isLeagueCovered ($R->{$primary}, undef, "WFTDA League Alcohol Liability");
  foreach (@policies) {
    my %policy;
    @policy{@policy_columns} = @{$_};
    
    push @policyhistory, $h->div ({ class=>"rTableRow ".(inArray ($policy{id}, [$active_policy, $active_alcohol_policy]) ? "highlighted" : "shaded"), onClick=>"window.location.href='view_org_policy?id=$policy{id}'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, $policy{id}, $policy{policy_name}, $policy{start}, $policy{end}) ]);
  }
  push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr hint", style=>"font-size: smaller;" }, 'No Policy History') ]) unless scalar @policies;
  
  if (!$active_policy or !$active_alcohol_policy or remainingOrgPolicyDays ($active_policy) <= 90 or remainingOrgPolicyDays ($active_alcohol_policy) <= 90) {
    push @policyhistory, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, '&nbsp;') ]);
    push @policyhistory, $h->div ({ style=>"font-size: smaller;" }, [
                                   ((!$active_policy or remainingOrgPolicyDays ($R->{$primary}, $active_policy) <= 90) ? $h->button (($active_policy ? "Renew" : "Purchase")." General Liability") : ""),
                                   ((!$active_alcohol_policy or remainingOrgPolicyDays ($R->{$primary}, $active_alcohol_policy) <= 90) ? $h->button (($active_alcohol_policy ? "Renew" : "Purchase")." Alcohol Liability") : "")
                                 ]);
  }
  
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "League Insurance Policy History:"), $h->ul ([ @policyhistory ])]);
  
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getOrgLog ($R->{$primary})]) unless $R->{$primary} !~ /^\d+$/;
  
  print $h->close ("form");
}

sub process_form  {
  error ("ERROR: Only SysAdmins can change leagues.") unless $ORCUSER->{SYSADMIN};

  my %FORM;  
  foreach (keys %FIELDS) {
        if ($fieldType{$_} =~ /^text/ and $_ ne "title") {
                $FORM{$_} = WebDB::trim param ($_) // "";
        } else {
                $FORM{$_} = param ($_) // "";           
        }
  }
        
         # check for required fields
        my @errors = ();
        foreach (@requiredFields) {
                push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "" and $FIELDS{$_}->[3] ne "static";
        }
        
  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{$primary} = saveForm (\%FORM);
        
        print $h->p ({ class=>"success" }, "League successfully saved.");

  display_form ({ $primary=>$FORM{$primary} }, "POSTSAVE");
}

sub saveForm {
  error ("ERROR: Only SysAdmins can change league details.") unless $ORCUSER->{SYSADMIN};
  
  my $FTS = shift;
  
  if ($FTS->{$DBFields[0]} eq "NEW") {
    $dbh->do (
      "INSERT INTO $DBTable (".
      join (", ", @DBFields)
      .") VALUES (". join (", ", map { '?' } @DBFields) .")",
        undef,
        map { $FTS->{$_} } @DBFields
    );
    if (!$FTS->{$primary}) {
      ($FTS->{$primary}) = $dbh->selectrow_array ("select max($primary) from $DBTable");
    }
    logit ($user->{person_id}, "$username edited a league (".join (", ", map { $FTS->{$_} } @DBFields).")");
  } else {
    my $OG = $dbh->selectrow_hashref ("select * from organization where id = ?", undef, $FTS->{$primary});
    
    error ("ERROR: Attempting to edit existing league, but league ID not found [$FTS->{$primary}]!") unless $OG->{$primary} =~ /^\d+$/;
    my $league_name = getLeagueName ($FTS->{$primary});
    
    foreach my $field (grep { notInArray ($_, \@ROFields) } keys %{$FTS}) {
      if ($FTS->{$field} ne $OG->{$field}) {
        $dbh->do ("update $DBTable set $field = ?, updated = now() where $primary = ?", undef, $FTS->{$field}, $FTS->{$primary});
        logit ($ORCUSER->{person_id}, "Updated league $league_name [$FTS->{$primary}]: $field -> $FTS->{$field}");
        orglogit ($ORCUSER->{person_id}, $FTS->{$primary}, "Updated league: $field -> $FTS->{$field}");
      }
    }
    
    
  }  
        return $FTS->{$primary};
}

sub delete_item {
  error ("ERROR: Only SysAdmins can delete leagues.") unless $ORCUSER->{SYSADMIN};

  my $X = shift;
  
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
    
  logit ($user->{person_id}, "$username deleted League ($X->{$primary})");
  print "League Deleted: $X->{$primary}", $h->br;
  print &formField ("Cancel", "Back", "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 = \"organizations.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 $value.$h->input ({ type=>"hidden", name=>$name, 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" })]);
    }
        }       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
          });
        }
        }
}

sub select_type {
  my $selection = shift // "";
  my @options = ("");
  
  my $sub_name = (caller(0))[3];
  $sub_name =~ s/^main::select_//;
  
        push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct type from $DBTable order by type")};

  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
}

sub select_status {
  my $selection = shift // "";
  my @options = ("");
  
  my $sub_name = (caller(0))[3];
  $sub_name =~ s/^main::select_//;
  
        push @options, map { @{$_} } @{$dbh->selectall_arrayref ("select distinct status from $DBTable order by type")};

  return $h->select ({ name=>$sub_name }, [ map { $_ eq $selection ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
}

sub getOrgLog {
  my $org_id = shift;
  
  my @activity_log;
  my $alog = $dbh->prepare("select timestamp, person_id, event from organization_log where organization_id = ? order by eventid desc limit 10");
  $alog->execute($org_id);
  while (my @logs = $alog->fetchrow_array) {
    $logs[1] = getUser ($logs[1])->{derby_name};
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
  }
  
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"org_log?filter-organization_id=".$org_id }, "[Entire log history]"));
}