+ WHERE Transactions.ObjectType = 'RT::Ticket'
+ AND Transactions.ObjectId = Tickets.Id
+";
+
+my $cfname = '';
+if ( $cgi->param('cfname') =~ /^\w(\w|\s)*$/ ) {
+
+ $cfname = $cgi->param('cfname');
+
+ $transaction_time = "(CASE Transactions.Type
+ WHEN 'CustomField' THEN
+ ( coalesce(to_number(ocfv_new.Content,'999999'),0)
+ - coalesce(to_number(ocfv_old.Content,'999999'),0) )
+ ELSE ( to_number(ocfv_main.Content,'999999') )
+ END) * 60";
+
+ $join .= "
+ LEFT JOIN ObjectCustomFieldValues ocfv_new
+ ON ( ocfv_new.Id = Transactions.NewReference )
+ LEFT JOIN ObjectCustomFieldValues ocfv_old
+ ON ( ocfv_old.Id = Transactions.OldReference )
+ LEFT JOIN ObjectCustomFieldValues ocfv_main
+ ON ( ocfv_main.ObjectType = 'RT::Transaction'
+ AND ocfv_main.ObjectId = Transactions.Id )
+ JOIN CustomFields
+ ON ( ( CustomFields.LookupType = 'RT::Queue-RT::Ticket-RT::Transaction'
+ AND CustomFields.Id = ocfv_main.CustomField
+ AND ocfv_main.Id IS NOT NULL
+ )
+ OR
+ ( CustomFields.LookupType = 'RT::Queue-RT::Ticket'
+ AND (CustomFields.Id = ocfv_new.CustomField OR ocfv_new.Id IS NULL)
+ AND (CustomFields.Id = ocfv_old.CustomField OR ocfv_old.Id IS NULL)
+ AND ocfv_main.Id IS NULL
+ ) )
+ ";
+
+ $twhere .= " AND CustomFields.Name = '$cfname'
+ AND (ocfv_new.Id IS NOT NULL OR ocfv_old.Id IS NOT NULL OR ocfv_main.Id IS NOT NULL)";
+
+}
+else {
+ $transaction_time = "
+ CASE transactions.type when 'Set'
+ THEN (to_number(newvalue,'999999')-to_number(oldvalue, '999999')) * 60
+ ELSE timetaken*60
+ END";
+
+ my $applied = '';
+ if ( $cgi->param('svcnum') =~ /^\s*(\d+)\s*$/ ) {
+ $twhere .= " AND EXISTS( SELECT 1 FROM acct_rt_transaction WHERE acct_rt_transaction.transaction_id = Transactions.id AND svcnum = $1 )";
+ $applied = "AND svcnum = $1";
+ }
+
+ $twhere .= "