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