03ac8e4aea0d74300642de9ff33a2354cce5c3e6
[freeside.git] / rt / lib / RT / Action / Accumulate.pm
1 package RT::Action::Accumulate;
2 use base 'RT::Action';
3
4 use strict;
5
6 =head1 NAME 
7
8 RT::Action::Accumulate - Accumulate a running total in a ticket custom field.
9
10 This action requires a transaction and ticket custom field with the same name.
11 When a transaction is submitted with a numeric value in that field, the field 
12 value for the ticket will be incremented by that amount.  Use this to create 
13 custom fields that behave like the "TimeWorked" field.
14
15 Best used with an "On Update" condition that triggers on any transaction.  The 
16 ticket custom field update itself does not a create a transaction.
17
18 The argument to this action is the name of the custom field.  They must have 
19 the same name, and should be single-valued fields.
20
21 =cut
22
23 sub Prepare {
24     my $self = shift;
25     my $cfname = $self->Argument or return 0;
26     RT::Logger->info('Accumulate::Prepare called on transaction '.
27                        $self->TransactionObj->Id." field $cfname");
28     my $TransObj = $self->TransactionObj;
29     my $TicketObj = $self->TicketObj;
30     if ( $TransObj->Type eq 'Create' and
31          !defined($TransObj->FirstCustomFieldValue($cfname)) ) {
32         # special case: we're creating a new ticket, and the initial value
33         # may have been set on the ticket instead of the transaction, so
34         # update the transaction to match
35         $self->{'obj'} = $TransObj;
36         $self->{'inc_by'} = $TicketObj->FirstCustomFieldValue($cfname);
37     } else {
38         # the usual case when updating an existing ticket
39         $self->{'obj'} = $TicketObj;
40         $self->{'inc_by'} = $TransObj->FirstCustomFieldValue($cfname) 
41                             || '';
42     }
43     return ( $self->{'inc_by'} =~ /^(\d+)$/ ); # else it's empty
44 }
45
46 sub Commit {
47     my $self = shift;
48     my $cfname = $self->Argument;
49     my $obj = $self->{'obj'};
50     my $newval = $self->{'inc_by'} + 
51       ($obj->FirstCustomFieldValue($cfname) || 0);
52     RT::Logger->info('Accumulate::Commit called on '.ref($obj).' '.
53                        $obj->Id." field $cfname");
54     my ($val) = $obj->AddCustomFieldValue(
55         Field => $cfname,
56         Value => $newval,
57         RecordTransaction => 0,
58     );
59     return $val;
60 }
61
62 1;
63