#!/usr/bin/perl
#
# Copyright 1999 -- 2001, onShore Development Inc. <URL:http://www.onshore-devel.com/>
#
#
# This free software 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-export-hours,v 1.11 2001/08/29 22:23:15 adam Exp $ 
#

=head1 NAME

timesheet-export-hours - export TimeSheet hours, i.e., for billing system


=cut

require '../etc/timesheet.conf';
require '../lib/common-funcs.pl';
use ADB;
use Getopt::Long;

my %state;
my $dbconn;
my $reply;
my $oops;
my $verbose = 0;
my $hoursexportfile = $Conf::EXPORTDIR . "/" . &date_download . "-hours.txt";
my @variables = ('hours_id', 'fkjob_id', 'fkclient_id','fkpersonnel_id',
		 'jobdate', 'date_entered', 'time_in', 'time_out',
		 'total_hours', 'billable', 'hours_description',
		 'comment', 'parking', 'expense_amount', 'fkapprover_id',
		 'approval_date');

=head1 SYNOPSIS

 B<timesheet-export-hours> [ -v ]

=head1 DESCRIPTION

B<timesheet-export-hours> exports newly approved hours to a flat file
on disk.  Generally, its purpose is to move logged hours from onShore
TimeSheet into your billing system.

The script looks for all hours which are marked as approved, not
deleted, and not marked as downloaded.  These hours are then
downloaded to a dated file in Conf::EXPORTDIR, and then marked as
downloaded in the database.

=head1 OPTIONS

=over 4

=item B<-v>

Be verbose.

=back

=cut

# switch handling
if ( ! GetOptions( "v" => \$verbose ) ) {
    die("Usage:\n  $0 [ -v ]\n");
}

verbose("exporting hours to file '$hoursexportfile'");

$dbconn = new ADB($Conf::DBADDR, $Conf::SQLDB);
if ( ! $dbconn->is_ok ) {
    $oops = $dbconn->errorstring;
    die("cannot connect to backend: $oops\n");
}

( -f $hoursexportfile ) &&
    die("export file already exists, won't overwrite\n");

open(EXPORT, ">$hoursexportfile") ||
    die("cannot open exportfile '$hoursexportfile': $!\n");

# do superuser download
my $sql = "SELECT HR.*, JB.*, CL.client_name from hours HR, client CL,
           job JB WHERE CL.client_id = HR.fkclient_id
           AND HR.approval_date > '$Conf::DUMMY_APPROVAL_DATE' AND HR.downloaded = 'n'
           AND JB.job_id = HR.fkjob_id AND HR.del = 'n' ORDER BY hours_id;";

$reply = $dbconn->query($sql);
if ( ! $reply ) {
    $oops = $dbconn->errorstring;
    die("error getting your hours: $oops (SQL is $sql)\n");
}
my $numrows = $reply->get_num_rows;
my %row;  
my @hrs;   
my $i = 0;
&print_heading;

open(LOG, ">>$Conf::EXPORT_LOG") ||
    die("cannot write to logfile '$Conf::EXPORT_LOG': $!\n");

while ( $i < $numrows ) {
    %row = $reply->get_row($i);
    &print_row(%row);
    push @hrs, $row{'hours_id'};
    $i++;
}

my $date = &dbdate_today;
print LOG "exporthours:$date:@hrs";
print LOG "\n";
close LOG;

verbose("exported hours IDs:@hrs");

# FIXME: can be optimized -- run in one statement
# FIXME: check for errors
my $var;
foreach $var (@hrs) {
    $reply = $dbconn->query("UPDATE hours set downloaded = 'y' where hours_id = $var;");
}

sub print_row {
    my %rec = @_;
    my $var;
    my $first;
    $first = 0;
    
    if ( $rec{"billable"} > 0 ) {
	$rec{'billable'} = "yes";
    } else {
	$rec{'billable'} = "no";
    }
    
    # char date_entered in the DB to jobdate for Stel
    $rec{'jobdate'} = $rec{'date_entered'};
    
    # just give Stel the "date" from "time" which is renamed to date_entered
    $rec{'intime'} =~ /.*:.*:(.*)/;
    $rec{'date_entered'} = $1;
    
    foreach $var (@variables) {
	$rec{$var} =~ s/\t/    /g;
	$rec{$var} =~ s/\n/ /g;
	$rec{$var} =~ s/\r/ /g;
	$rec{$var} =~ s/\f/ /g;
	if ( $first == 0 ) {
	    $first = 1;
	    print EXPORT "$rec{$var}";
	} else {
	    print EXPORT "\t$rec{$var}";
	}
    } 
    print EXPORT "\r";
}

sub print_heading {
    my $first;
    my $var;

    $first = 0;
    foreach $var (@variables) {
	$var =~ s/\n/ /g;
	$var =~ s/\r/ /g;
	$var =~ s/\f/ /g;
	if ($first == 0) {
            $first = 1;
            print EXPORT "$var";
        } else {
            print EXPORT "\t$var";
        }
    }
    print EXPORT"\r";
}


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