#######################################################
#  Name:    ticket_list.pl
#  version: 1.3
#  Date:    May 15, 2007
#  Author:  Mathew Snyder
#######################################################

#!/usr/bin/perl

use warnings;
use strict;
use lib '/usr/local/rt-3.6.1/lib';
use lib '/usr/local/rt-3.6.1/local/lib';
use RT;
use RT::Tickets;
use RT::Users;
use MIME::Lite;

RT::LoadConfig();
RT::Init();

# Declare our global variables
my @users = qw/username/;
my (@days, @months, @years, @date, @searchDate);
my $time = time();
my (%tikNums, %tikSubj);

# Create the array containing our date range
for (1 .. 7) {
  $time -= 24*60*60;
  @date = (localtime($time))[3 .. 5];
  push @days, (sprintf '%02d', $date[0]);
  push @months,(sprintf '%02d',$date[1] + 1);
  push @years, $date[2] + 1900;
  push @searchDate, join "-", ($date[2] + 1900), (sprintf '%02d',$date[1] + 1), (sprintf '%02d', $date[0]);
}

# These are dates which will be either searched against or inserted into the email
my $startDate   = join "-", $months[$#months], $days[$#days], $years[$#years];
my $endDate     = join "-", $months[0], $days[0], $years[0];
my $searchStart = join "-", $years[$#years], $months[$#months], $days[$#days];
my $searchEnd   = join "-", $years[0], $months[0], $days[0];

my $tix = new RT::Tickets(RT::SystemUser);
$tix->FromSQL('(LastUpdated > "' . $searchStart . '" AND LastUpdated < "' . $searchEnd . '") OR (LastUpdated = "' . $searchStart . '" OR LastUpdated = "' . $searchEnd. '")');

# gather up all of the tickets, transactions, and time for each user and successively place 
# all data into a HoHoH working down from user to environment to ticket
# we go through each date in the range individually so we can make sure we only get the transactions that
# have been added during the date range
foreach my $date (@searchDate) {
        while (my $ticket = $tix->Next) {
                my $env = $ticket->FirstCustomFieldValue('Environment');
                my $transactions = $ticket->Transactions;
                while (my $transaction  = $transactions->Next) {
                        my $creator     = $transaction->CreatorObj;

			# we need to make sure the transaction is in the date range requested
			# it's set up like this so we can chop the timestamp off of the Created string
                        (my $checkDate  = $transaction->Created) =~ s/\s.*$//;

			# we only want transactions that are within the date range, have a time worked
			# added, and that the creator of the transaction is one of the actual users
			# and not someone that was created upon ticket submission or Cc addition
                        next unless ($checkDate eq $date);
                        next unless ($creator->Privileged);
                        next unless ($transaction->TimeTaken);
                        $tikNums{$creator->Name}{$env}{$ticket->id} += $transaction->TimeTaken;
                }
                $tikSubj{$ticket->id} = $ticket->Subject;
        }
}

# Format the time spent on each ticket as hh:mm
foreach my $user (keys %tikNums) {
        foreach my $env (keys %{ $tikNums{$user} }) {
                foreach my $tikID (keys %{ $tikNums{$user}{$env} }) {

			# The array which will hold our formatted time
                        my @endTime;
                        my $temp          = $tikNums{$user}{$env}{$tikID};

			# convert the time in minutes to a number of hours with a decimal remainder
                        my $temp2         = $temp / 60;

			# split the result from above into two distinct values and place them into the @temp array
                        my @temp          = split /\./, $temp2;

			# assign our hour to the first element of @endtime
                        $endTime[0]       = $temp[0];

			# assign the remaining minutes to the second element of @endtime
                        $endTime[1]       = $temp % 60;

			# put the formatted time string into the hash
                        $tikNums{$user}{$env}{$tikID} = sprintf '%d:%02d', @endTime[0,1];
                }
        }
}

mkdir "/work_reports/ticketlists_$endDate", 0777;

foreach my $user (keys %tikNums) {
        open TIMESHEET, ">/work_reports/ticketlists_$endDate/ticketlist_$user.txt";
        print TIMESHEET "List of tickets worked on by $user during week ending $endDate", "\n\n";

	# Print the header for our data using preset formats.  They are offset the way they are due to the
	# requirement that the closing "." be in the first column of the script.  All lines have subsequently
	# been aligned similarly so as not to confuse anyone regarding the association.  I would have
	# declared them earlier in the script but due to the use of scoped variables the compilation
	# will fail if I do.
        foreach my $env (sort keys %{ $tikNums{$user} }){

format TIMESHEET_TOP =
@<<<<<<<<<<<<<<<<<<<<
$env
 Ticket ID                           Subject                           hh:mm
----------------------------------------------------------------------------
.

                write TIMESHEET_TOP;


                foreach my $id (sort keys %{ $tikNums{$user}{$env} }) {

format TIMESHEET =
@#########  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  @>>>>
       $id, $tikSubj{$id},                   $tikNums{$user}{$env}{$id}
~~          ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            $tikSubj{$id}
.

                        write TIMESHEET;
                }
                print TIMESHEET "\n";
        }
        close TIMESHEET;
}

# build and send the ticket lists for everyone in the "mailing list"
foreach my $user (@users) {
        my $emailTo      = "$user\@xxxxxxxx.com";
        my $emailFrom    = "root";
        my $emailSubj    = "RT Ticket List for The Week Ending $endDate";
        my $emailMsg     = "Attached is a file containing a list of tickets worked on by you during the last week.  If you made a comment on a ticket but did not add any time it will not show up.  Only tickets on which you've actually marked down time worked will appear in this list.";

        my $fullEmail    = new MIME::Lite(From    => $emailFrom,
                                          To      => $emailTo,
                                          Subject => $emailSubj,
                                          Type    => "multipart/mixed");

        $fullEmail->attach(Type        => "TEXT",
                           Data        => $emailMsg);

        $fullEmail->attach(Type        => "text/plain",
                           Path        => "/work_reports/ticketlists_$endDate/ticketlist_$user.txt",
                           Disposition => "attachment");

        $fullEmail->send("sendmail", "/usr/sbin/sendmail -t");
}

exit;