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