batch refactor continued
[freeside.git] / FS / FS / part_bill_event.pm
1 package FS::part_bill_event;
2
3 use strict;
4 use vars qw( @ISA $DEBUG @EXPORT_OK );
5 use FS::Record qw( dbh qsearch qsearchs );
6 use FS::Conf;
7
8 @ISA = qw( FS::Record );
9 @EXPORT_OK = qw( due_events );
10 $DEBUG = 0;
11
12 =head1 NAME
13
14 FS::part_bill_event - Object methods for part_bill_event records
15
16 =head1 SYNOPSIS
17
18   use FS::part_bill_event;
19
20   $record = new FS::part_bill_event \%hash;
21   $record = new FS::part_bill_event { 'column' => 'value' };
22
23   $error = $record->insert;
24
25   $error = $new_record->replace($old_record);
26
27   $error = $record->delete;
28
29   $error = $record->check;
30
31   $error = $record->do_event( $direct_object );
32   
33   @events = due_events ( { 'record' => $event_triggering_record,
34                            'payby'  => $payby,
35                            'event_time => $_date,
36                            'extra_sql  => $extra } );
37
38 =head1 DESCRIPTION
39
40 An FS::part_bill_event object represents an invoice event definition -
41 a callback which is triggered when an invoice is a certain amount of time
42 overdue.  FS::part_bill_event inherits from
43 FS::Record.  The following fields are currently supported:
44
45 =over 4
46
47 =item eventpart - primary key
48
49 =item payby - CARD, DCRD, CHEK, DCHK, LECB, BILL, or COMP
50
51 =item event - event name
52
53 =item eventcode - event action
54
55 =item seconds - how long after the invoice date events of this type are triggered
56
57 =item weight - ordering for events with identical seconds
58
59 =item plan - eventcode plan
60
61 =item plandata - additional plan data
62
63 =item disabled - Disabled flag, empty or `Y'
64
65 =back
66
67 =head1 METHODS
68
69 =over 4
70
71 =item new HASHREF
72
73 Creates a new invoice event definition.  To add the invoice event definition to
74 the database, see L<"insert">.
75
76 Note that this stores the hash reference, not a distinct copy of the hash it
77 points to.  You can ask the object for a copy with the I<hash> method.
78
79 =cut
80
81 # the new method can be inherited from FS::Record, if a table method is defined
82
83 sub table { 'part_bill_event'; }
84
85 =item insert
86
87 Adds this record to the database.  If there is an error, returns the error,
88 otherwise returns false.
89
90 =cut
91
92 # the insert method can be inherited from FS::Record
93
94 =item delete
95
96 Delete this record from the database.
97
98 =cut
99
100 # the delete method can be inherited from FS::Record
101
102 =item replace OLD_RECORD
103
104 Replaces the OLD_RECORD with this one in the database.  If there is an error,
105 returns the error, otherwise returns false.
106
107 =cut
108
109 # the replace method can be inherited from FS::Record
110
111 =item check
112
113 Checks all fields to make sure this is a valid invoice event definition.  If
114 there is an error, returns the error, otherwise returns false.  Called by the
115 insert and replace methods.
116
117 =cut
118
119 # the check method should currently be supplied - FS::Record contains some
120 # data checking routines
121
122 sub check {
123   my $self = shift;
124
125   $self->weight(0) unless $self->weight;
126
127   my $conf = new FS::Conf;
128   if ( $conf->exists('safe-part_bill_event') ) {
129     my $error = $self->ut_anything('eventcode');
130     return $error if $error;
131
132     my $c = $self->eventcode;
133
134     $c =~ /^\s*\$cust_main\->(suspend|cancel|invoicing_list_addpost|bill|collect)\(\);\s*("";)?\s*$/
135
136       or $c =~ /^\s*\$cust_bill\->(comp|realtime_(card|ach|lec)|batch_card|send)\((%options)*\);\s*$/
137
138       or $c =~ /^\s*\$cust_bill\->send(_if_newest)?\(\'[\w\-\s]+\'\s*(,\s*(\d+|\[\s*\d+(,\s*\d+)*\s*\])\s*,\s*'[\w\@\.\-\+]*'\s*)?\);\s*$/
139
140       or $c =~ /^\s*\$cust_main\->apply_payments; \$cust_main->apply_credits; "";\s*$/
141
142       or $c =~ /^\s*\$cust_main\->charge\( \s*\d*\.?\d*\s*,\s*\'[\w \!\@\#\$\%\&\(\)\-\+\;\:\"\,\.\?\/]*\'\s*\);\s*$/
143
144       or $c =~ /^\s*\$cust_main\->suspend_(if|unless)_pkgpart\([\d\,\s]*\);\s*$/
145
146       or $c =~ /^\s*\$cust_bill\->cust_suspend_if_balance_over\([\d\.\s]*\);\s*$/
147
148       or do {
149         #log
150         return "illegal eventcode: $c";
151       };
152
153   }
154
155   my $error = $self->ut_numbern('eventpart')
156     || $self->ut_enum('payby', [qw( CARD DCLN DCRD CHEK DCHK LECB BILL COMP )] )
157     || $self->ut_text('event')
158     || $self->ut_anything('eventcode')
159     || $self->ut_number('seconds')
160     || $self->ut_enum('disabled', [ '', 'Y' ] )
161     || $self->ut_number('weight')
162     || $self->ut_textn('plan')
163     || $self->ut_anything('plandata')
164   ;
165     #|| $self->ut_snumber('seconds')
166   return $error if $error;
167
168   #quelle kludge
169   if ( $self->plandata =~ /^(agent_)?templatename\s+(.*)$/m ) {
170     my $name= $2;
171
172     foreach my $file (qw( template
173                           latex latexnotes latexreturnaddress latexfooter
174                             latexsmallfooter
175                           html htmlnotes htmlreturnaddress htmlfooter
176                      ))
177     {
178       unless ( $conf->exists("invoice_${file}_$name") ) {
179         $conf->set(
180           "invoice_${file}_$name" =>
181             join("\n", $conf->config("invoice_$file") )
182         );
183       }
184     }
185   }
186
187   $self->SUPER::check;
188 }
189
190 =item templatename
191
192 Returns the alternate invoice template name, if any, or false if there is
193 no alternate template for this invoice event.
194
195 =cut
196
197 sub templatename {
198   my $self = shift;
199   if (    $self->plan     =~ /^send_(alternate|agent)$/
200        && $self->plandata =~ /^(agent_)?templatename (.*)$/m
201      )
202   {
203     $2;
204   } else {
205     '';
206   }
207 }
208
209 =item due_events
210
211 Returns the list of events due, if any, or false if there is none.
212 Requires record and payby, but event_time and extra_sql are optional.
213
214 =cut
215
216 sub due_events {
217   my ($record, $payby, $event_time, $extra_sql) = @_;
218   my $interval = 0;
219   if ($record->_date){ 
220     $event_time = time unless $event_time;
221     $interval = $event_time - $record->_date;
222   }
223   sort {    $a->seconds   <=> $b->seconds
224          || $a->weight    <=> $b->weight
225          || $a->eventpart <=> $b->eventpart }
226     grep { $_->seconds <= ( $interval )
227            && ! qsearch( 'cust_bill_event', {
228                            'invnum' => $record->get($record->dbdef_table->primary_key),
229                            'eventpart' => $_->eventpart,
230                            'status' => 'done',
231                                                                          } )
232          }
233       qsearch( {
234         'table'     => 'part_bill_event',
235         'hashref'   => { 'payby'    => $payby,
236                          'disabled' => '',             },
237         'extra_sql' => $extra_sql,
238       } );
239
240
241 }
242
243 =item do_event
244
245 Performs the event and returns any errors that occur.
246 Requires a record on which to perform the event.
247 Should only be performed inside a transaction.
248
249 =cut
250
251 sub do_event {
252   my ($self, $object, %options) = @_;
253   warn " calling event (". $self->eventcode. ") for " . $object->table . " " ,
254     $object->get($object->dbdef_table->primary_key) . "\n" if $DEBUG > 1;
255   my $oldAutoCommit = $FS::UID::AutoCommit;
256   local $FS::UID::AutoCommit = 0;
257
258   #  for "callback" -- heh
259   my $cust_main = $object->cust_main;
260   my $cust_bill;
261   if ($object->table eq 'cust_bill'){
262     $cust_bill = $object;
263   }
264   my $cust_pay_batch;
265   if ($object->table eq 'cust_pay_batch'){
266     $cust_pay_batch = $object;
267   }
268
269   my $error;
270   {
271     local $SIG{__DIE__}; # don't want Mason __DIE__ handler active
272     $error = eval $self->eventcode;
273   }
274
275   my $status = '';
276   my $statustext = '';
277   if ( $@ ) {
278     $status = 'failed';
279     $statustext = $@;
280   } elsif ( $error ) {
281     $status = 'done';
282     $statustext = $error;
283   } else {
284     $status = 'done';
285   }
286
287   #add cust_bill_event
288   my $cust_bill_event = new FS::cust_bill_event {
289 #    'invnum'     => $object->get($object->dbdef_table->primary_key),
290     'invnum'     => $object->invnum,
291     'eventpart'  => $self->eventpart,
292     '_date'      => time,
293     'status'     => $status,
294     'statustext' => $statustext,
295   };
296   $error = $cust_bill_event->insert;
297   if ( $error ) {
298     my $e = 'WARNING: Event run but database not updated - '.
299             'error inserting cust_bill_event, invnum #'.  $object->invnum .
300             ', eventpart '. $self->eventpart.": $error";
301     warn $e;
302     return $e;
303   }
304   '';
305 }
306
307 =back
308
309 =head1 BUGS
310
311 The whole "eventcode" idea is bunk.  This should be refactored with subclasses
312 like part_pkg/ and part_export/
313
314 =head1 SEE ALSO
315
316 L<FS::cust_bill>, L<FS::cust_bill_event>, L<FS::Record>, schema.html from the
317 base documentation.
318
319 =cut
320
321 1;
322