#!/usr/bin/perl
#
# Copyright 1999 -- 2001, onShore Development Inc. <URL:http://www.onshore-devel.com/>
#
#
# This program is free software under the terms of the GNU General Public
# License (GPL). A copy of the GPL, "COPYING", should have been made
# available with this software.  If not, a copy may be obtained at 
# http://www.fsf.org/copyleft/gpl.html
#
# $Id: timesheet-daily-report,v 1.14 2001/08/29 22:23:15 adam Exp $
# 

=head1 NAME

timesheet-daily-report - create daily supervisor reports

=cut

require '../etc/timesheet.conf';
use ADB;
use FileHandle;

$bounce = "timesheet\@onshore.com";
my $MAILER = "/usr/sbin/sendmail -f$bounce -t";

my $dbconn;   # ADB connection
my $supers;   # ADB result of query to get supervisors
my %supervisor;  # a single supervisor hash
my $oops;     # temp var to hold error strings
my $numrows;  # number of rows in the $supers result
my $i;        # iterator
my $verbose = 0;		# whether to be verbose


# Get connection to SQL backend
$dbconn = new ADB($Conf::DBADDR, $Conf::SQLDB);
if (!$dbconn->is_ok) {
    $oops = $dbconn->errorstring;
    die "Error opening $Conf::DBADDR->$Conf::SQLDB: $oops\n";
}

# Get a result froma  query gathering information on all supervisors
$supers = $dbconn->query("SELECT DISTINCT ON fksupervisor_id 
   $Conf::JOB_DB.fksupervisor_id as fksupervisor_id, 
   $Conf::USER_DB.* from $Conf::JOB_DB 
   WHERE $Conf::JOB_DB.fksupervisor_id = $Conf::USER_DB.personnel_id");

	
if ( !$supers ) {
    $oops = $dbconn->errorstring;
    die "Unable to get list of all supervisors: $oops\n";
}


$numrows = $supers->get_num_rows;

$i = 0;

# Proccess each supervisor in turn
while ( $i < $numrows ) {
    %supervisor = $supers->get_row($i);  
    process_supervisor_report($dbconn, %supervisor);
    $i++;
}


# We take a single supervisor and generate a report for them.
# it contains the following:
# 1. List of all unnaproved hours on jobs they supervise.
# 2. List of all jobs over estimated hours, or over flag_hrs.
# 3. List of all jobs they currently supervise and a status report
sub process_supervisor_report
{
    my $dbconn = shift;
    my %user = @_;
    my $jobtable;            # temp table holding all jobs for this user
    my $result;              # Generic ADB result
    my $sql;                 # Generic sql statement
    my $subject;             # Subject line for email
    my $datestamp;           # Time/Date stamp for the email
    my $numrows; 
    my $i;
    my $handle_saved;
    
    verbose("processing report for $user{'email'}:");
    $datestamp = localtime;
    chomp($datestamp);
    $subject = "onShore TimeSheet Supervisor Report for $datestamp";
    
    verbose(" running query for supervisor report...");
    # Find all unnaproved hours for jobs they supervise
    $sql = "SELECT job.job_id, client.client_name, hours.fkpersonnel_id, " .
	    "hours.hours_description, hours.total_hours, hours.date_entered, hours.hours_id " .
	    "FROM hours, job, client WHERE " .
	    "job.fksupervisor_id = '$user{'personnel_id'}' AND " .
	    "job.fkclient_id = client.client_id AND del = 'n' AND " .
	    "job.job_id = hours.fkjob_id AND hours.approval_date = '01-01-0001' AND " .
	    "job.open = 1;";
  
    $result = $dbconn->query($sql);
    if ( ! $result ) {
	$oops = $dbconn->errorstring;
	warn "Error processing $user{'personnel_id'}: $oops\n";
	return 0;
    }

    verbose(" query for supervisor report done");
    $numrows = $result->get_num_rows;
    $i = 0;
    if ( $numrows == 0 ) {
	return 0;
    } else {
	print MAIL "Unapproved Hours Against Jobs You Supervise\n";
	print MAIL "-------------------------------------------\n";
	print MAIL "JobID    Client                User    Hours       Date        HoursID\n";
    }
  
    format UNAPPROVED = 
@<<<<<<< @<<<<<<<<<<<<<<<<<<<< @<<<<<< @<<<<<<<<<< @<<<<<<<<<< @<<<<<<<<
$hours{'job_id'},$hours{'client_name'},$hours{'total_hours'},$hours{'fkpersonnel_id'},$hours{'date_entered'},$hours{'hours_id'}
.

    open(MAIL, "|$MAILER") || die "cannot open mailer $MAILER: $!\n";

    print MAIL "To: $user{'email'}\n";
    print MAIL "Subject: Timesheet Nightly Report for $datestamp\n";
    print MAIL "From: $bounce\n";
    
    print MAIL "\n\n";
    print MAIL "Timesheet Supervisor Report for $datestamp\n\n\n";
  
    if ( open(NOTE, "nite-report-note") ) {
	print MAIL "onShore TimeSheet Supervisory Note.\nPLEASE READ!\n";
	while (<NOTE>) {
	    print MAIL $_;
	}
	print MAIL "\n\n\n";
    }
  
    $jobtable = "supervisor_report_$user{'personnel_id'}";
  
    $handle_saved = select; # save STDOUT, otherwise verbose() will not work later
    select MAIL; 
    $~ = UNAPPROVED;
    while ($i < $numrows) {
	%hours = $result->get_row($i);
	write;
	$i++;
    }
    select $handle_saved; # restore STDOUT
    print MAIL "\n";
    print MAIL "<A HREF=\"$Conf::TIMESHEET_URL/viewedithours.cgi?fksupervisor_id=$user{'personnel_id'}&approved=n&searchsubmit.x=1&output=short\">Click here to get your Unapproved Hours</A>";
    print MAIL "\n\n";
    print MAIL "Jobs Summary\n";
    print MAIL "------------\n\n";
    $sql = "";

    verbose(" preparing statement to generate job summary...");
    $sql = "select sum(hours.total_hours) as job_hours, job.job_id, job.estimated_hours, job.flag_hrs, client.client_name, job.job_description from client, job, hours WHERE job.job_id = hours.fkjob_id AND hours.del = 'n' AND job.fksupervisor_id = '$user{'personnel_id'}' AND job.open = 1 AND job.fkclient_id = client.client_id GROUP BY job.job_id, job.estimated_hours, job.flag_hrs, client.client_name, job.job_description;";

    $result = $dbconn->query($sql);
    if (!$result) {
	$oops = $dbconn->errorstring;
	warn "error getting job summary while processing $user{'personnel_id'}: $oops\n";
	return 0;
    }

    verbose(" job summary query complete");
    verbose(" generating report...");
    $numrows = $result->get_num_rows;
    $i = 0;
    print MAIL "
                                                            Total Est.  Flag
Flags    JobID    Client Name   Description                 Hours Hours Hours\n\n";


    format JOBSUMMARY =
@<<<<<<< @<<<<<<< @<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<< @<<< @<<<<
$flags,$hours{job_id},$hours{client_name},$hours{job_description},$hours{job_hours},$hours{estimated_hours},$hours{flag_hrs}
.

    $handle_saved = select; # save STDOUT, otherwise verbose() will not work later
    select MAIL;
    $~ = JOBSUMMARY;

    while ($i < $numrows) {
	%hours = $result->get_row($i);
	$flags = '';
	if (!$hours{'job_id'}) {
	    print MAIL "No jobs under your supervision\n";
	    $i++;
	    return;
	}
	if ($hours{'flag_hrs'} < $hours{'job_hours'}) {
	    $flags .= "OF ";
	}
	if ($hours{'estimated_hours'} < $hours{'job_hours'}) {
	    $flags .= "OE ";
	}
	write;
	$i++;
    }
    select $handle_saved; # restore STDOUT
    print MAIL "\n\nLegend: OF = Over Flag hours Value\n";
    print MAIL "        OE = Over estimated Hours Value\n";
    close MAIL;
    verbose("report done for $user{'email'}");
}


# verbose status message
sub verbose {
    print @_, "\n" if $verbose;
}

