#!/usr/bin/perl

#######################################################
#  Name:     ticket_list.pl
#  version:  1.4.1
#  Date:     May 29, 2007
#  Author:   Mathew Snyder
#  Comments: A script which gathers the tickets
#			 worked on by each person in Ops and
#			 Engineering during the prior week.
#			 It places them in individual files for
#			 each user.  It then emails them to each
#			 person that has requested it.
#######################################################

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

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

# Declare our global variables
#my @users = qw/sveirs rbates msnyder mhanson mclemson koporto jgoode jcurran dsd datreides cwhite/;
my @users = qw/msnyder/;
my (%tickets, %tikSubj);

# These are dates which will be either searched against or inserted into the email
my $startDate   = startDate;
my $endDate     = endDate;
my $searchStart = searchStart;
my $searchEnd   = searchEnd;
my @searchDate  = Reports::Dates::searchDate;

my $tix = new RT::Tickets(RT::SystemUser);
$tix->FromSQL('LastUpdated >= "' . $searchStart. '" AND 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) {
		$tikSubj{$ticket->id} = $ticket->Subject;
		my $subject = $ticket->Subject;
		my $id = $ticket->id;
		my $env = $ticket->FirstCustomFieldValue('Environment');
		my $transactions = $ticket->Transactions;
		while (my $transaction  = $transactions->Next) {
			my $creator     = $transaction->CreatorObj;
			my $user = $creator->Name;
			# 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 TimeWorked
			# set, and the creator of which is one of the actual users and not someone 
			# that was created upon ticket submission or Cc addition
			next unless (($checkDate eq $date) && ($creator->Privileged) && ($transaction->TimeTaken));

			# if all of the above stipulations are met add the time worked to the hash
		#	$tickets{$user}{$env}{$id} += $transaction->TimeTaken;
			$tickets{$user}{$env}{$id}{$subject} += $transaction->TimeTaken;
		}
	}
}

# Format the time spent on each ticket as hh:mm
foreach my $user (keys %tickets) {
	foreach my $env (keys %{ $tickets{$user} }) {
		foreach my $tikID (keys %{ $tickets{$user}{$env} }) {
			foreach my $subject (keys %{ $tickets{$user}{$env}{$tikID} }) {
				my @endTime;
#				my $temp          = $tickets{$user}{$env}{$tikID};
				my $temp          = $tickets{$user}{$env}{$tikID}{$subject};
				my $temp2         = $temp / 60;
				my @temp          = split /\./, $temp2;
				$endTime[0]       = $temp[0];
				$endTime[1]       = $temp % 60;
#				$tickets{$user}{$env}{$tikID} = sprintf '%d:%02d', @endTime[0,1];
				$tickets{$user}{$env}{$tikID}{$subject} = sprintf '%d:%02d', @endTime[0,1];
			}
		}
	}
}

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

foreach my $user (keys %tickets) {
	open TIMESHEET, ">/work_reports/ticketlists/ticketlists_$endDate/ticketlist_$user" . "_" . "$endDate.txt" or die "Can't open file: $!";
	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 %{ $tickets{$user} }){

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

		write TIMESHEET_TOP;

		foreach my $id (sort keys %{ $tickets{$user}{$env} }) {
			foreach my $subject (keys %{ $tickets{$user}{$env}{$id} }) {
format TIMESHEET =
@#########  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  @>>>>
	   $id, $tickets{$user}{$env}{$id},                      $tickets{$user}{$env}{$id}{$subject}
~~          ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            $tickets{$user}{$env}{$id}
.

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

close TIMESHEET;

# build and send the ticket lists for everyone in the "mailing list"
foreach my $user (@users) {
        my $emailTo      = "$user\@servervault.com";
        my $emailFrom    = "RT-Devel";
        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.\n\nFor some reason, some ticket subjects are not being inserted into the report.  I have yet to figure out why.  Rest assured, thought, that I am working on sorting that out.  In the meantime, please enjoy the alterations that were requested.  :)";

        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/ticketlists_$endDate/ticketlist_$user" . "_" . "$endDate.txt",
                           Disposition => "attachment");

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

exit;
