autoload methods returning foreign records, RT#13971
[freeside.git] / FS / FS / msg_template.pm
1 package FS::msg_template;
2 use base qw( FS::Record );
3
4 use strict;
5 use vars qw( $DEBUG $conf );
6
7 use Date::Format qw( time2str );
8 use File::Temp;
9 use IPC::Run qw(run);
10 use Text::Template;
11
12 use HTML::Entities qw( decode_entities encode_entities ) ;
13 use HTML::FormatText;
14 use HTML::TreeBuilder;
15 use Encode;
16
17 use FS::Misc qw( generate_email send_email do_print );
18 use FS::Conf;
19 use FS::Record qw( qsearch qsearchs );
20 use FS::UID qw( dbh );
21
22 use FS::cust_main;
23 use FS::cust_msg;
24 use FS::template_content;
25
26 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
27
28 $DEBUG=0;
29
30 =head1 NAME
31
32 FS::msg_template - Object methods for msg_template records
33
34 =head1 SYNOPSIS
35
36   use FS::msg_template;
37
38   $record = new FS::msg_template \%hash;
39   $record = new FS::msg_template { 'column' => 'value' };
40
41   $error = $record->insert;
42
43   $error = $new_record->replace($old_record);
44
45   $error = $record->delete;
46
47   $error = $record->check;
48
49 =head1 DESCRIPTION
50
51 An FS::msg_template object represents a customer message template.
52 FS::msg_template inherits from FS::Record.  The following fields are currently
53 supported:
54
55 =over 4
56
57 =item msgnum - primary key
58
59 =item msgname - Name of the template.  This will appear in the user interface;
60 if it needs to be localized for some users, add it to the message catalog.
61
62 =item agentnum - Agent associated with this template.  Can be NULL for a 
63 global template.
64
65 =item mime_type - MIME type.  Defaults to text/html.
66
67 =item from_addr - Source email address.
68
69 =item disabled - disabled ('Y' or NULL).
70
71 =back
72
73 =head1 METHODS
74
75 =over 4
76
77 =item new HASHREF
78
79 Creates a new template.  To add the template to the database, see L<"insert">.
80
81 Note that this stores the hash reference, not a distinct copy of the hash it
82 points to.  You can ask the object for a copy with the I<hash> method.
83
84 =cut
85
86 # the new method can be inherited from FS::Record, if a table method is defined
87
88 sub table { 'msg_template'; }
89
90 =item insert [ CONTENT ]
91
92 Adds this record to the database.  If there is an error, returns the error,
93 otherwise returns false.
94
95 A default (no locale) L<FS::template_content> object will be created.  CONTENT 
96 is an optional hash containing 'subject' and 'body' for this object.
97
98 =cut
99
100 sub insert {
101   my $self = shift;
102   my %content = @_;
103
104   my $oldAutoCommit = $FS::UID::AutoCommit;
105   local $FS::UID::AutoCommit = 0;
106   my $dbh = dbh;
107
108   my $error = $self->SUPER::insert;
109   if ( !$error ) {
110     $content{'msgnum'} = $self->msgnum;
111     $content{'subject'} ||= '';
112     $content{'body'} ||= '';
113     my $template_content = new FS::template_content (\%content);
114     $error = $template_content->insert;
115   }
116
117   if ( $error ) {
118     $dbh->rollback if $oldAutoCommit;
119     return $error;
120   }
121
122   $dbh->commit if $oldAutoCommit;
123   return;
124 }
125
126 =item delete
127
128 Delete this record from the database.
129
130 =cut
131
132 # the delete method can be inherited from FS::Record
133
134 =item replace [ OLD_RECORD ] [ CONTENT ]
135
136 Replaces the OLD_RECORD with this one in the database.  If there is an error,
137 returns the error, otherwise returns false.
138
139 CONTENT is an optional hash containing 'subject', 'body', and 'locale'.  If 
140 supplied, an L<FS::template_content> object will be created (or modified, if 
141 one already exists for this locale).
142
143 =cut
144
145 sub replace {
146   my $self = shift;
147   my $old = ( ref($_[0]) and $_[0]->isa('FS::Record') ) 
148               ? shift
149               : $self->replace_old;
150   my %content = @_;
151   
152   my $oldAutoCommit = $FS::UID::AutoCommit;
153   local $FS::UID::AutoCommit = 0;
154   my $dbh = dbh;
155
156   my $error = $self->SUPER::replace($old);
157
158   if ( !$error and %content ) {
159     $content{'locale'} ||= '';
160     my $new_content = qsearchs('template_content', {
161                         'msgnum' => $self->msgnum,
162                         'locale' => $content{'locale'},
163                       } );
164     if ( $new_content ) {
165       $new_content->subject($content{'subject'});
166       $new_content->body($content{'body'});
167       $error = $new_content->replace;
168     }
169     else {
170       $content{'msgnum'} = $self->msgnum;
171       $new_content = new FS::template_content \%content;
172       $error = $new_content->insert;
173     }
174   }
175
176   if ( $error ) {
177     $dbh->rollback if $oldAutoCommit;
178     return $error;
179   }
180
181   warn "committing FS::msg_template->replace\n" if $DEBUG and $oldAutoCommit;
182   $dbh->commit if $oldAutoCommit;
183   return;
184 }
185     
186
187
188 =item check
189
190 Checks all fields to make sure this is a valid template.  If there is
191 an error, returns the error, otherwise returns false.  Called by the insert
192 and replace methods.
193
194 =cut
195
196 # the check method should currently be supplied - FS::Record contains some
197 # data checking routines
198
199 sub check {
200   my $self = shift;
201
202   my $error = 
203     $self->ut_numbern('msgnum')
204     || $self->ut_text('msgname')
205     || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
206     || $self->ut_textn('mime_type')
207     || $self->ut_enum('disabled', [ '', 'Y' ] )
208     || $self->ut_textn('from_addr')
209   ;
210   return $error if $error;
211
212   $self->mime_type('text/html') unless $self->mime_type;
213
214   $self->SUPER::check;
215 }
216
217 =item content_locales
218
219 Returns a hashref of the L<FS::template_content> objects attached to 
220 this template, with the locale as key.
221
222 =cut
223
224 sub content_locales {
225   my $self = shift;
226   return $self->{'_content_locales'} ||= +{
227     map { $_->locale , $_ } 
228     qsearch('template_content', { 'msgnum' => $self->msgnum })
229   };
230 }
231
232 =item prepare OPTION => VALUE
233
234 Fills in the template and returns a hash of the 'from' address, 'to' 
235 addresses, subject line, and body.
236
237 Options are passed as a list of name/value pairs:
238
239 =over 4
240
241 =item cust_main
242
243 Customer object (required).
244
245 =item object
246
247 Additional context object (currently, can be a cust_main, cust_pkg, 
248 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband, 
249 domain) ).  If the object is a svc_*, its cust_pkg will be fetched and 
250 used for substitution.
251
252 As a special case, this may be an arrayref of two objects.  Both 
253 objects will be available for substitution, with their field names 
254 prefixed with 'new_' and 'old_' respectively.  This is used in the 
255 rt_ticket export when exporting "replace" events.
256
257 =item from_config
258
259 Configuration option to use as the source address, based on the customer's 
260 agentnum.  If unspecified (or the named option is empty), 'invoice_from' 
261 will be used.
262
263 The I<from_addr> field in the template takes precedence over this.
264
265 =item to
266
267 Destination address.  The default is to use the customer's 
268 invoicing_list addresses.  Multiple addresses may be comma-separated.
269
270 =item substitutions
271
272 A hash reference of additional substitutions
273
274 =back
275
276 =cut
277
278 sub prepare {
279   my( $self, %opt ) = @_;
280
281   my $cust_main = $opt{'cust_main'} or die 'cust_main required';
282   my $object = $opt{'object'} or die 'object required';
283
284   # localization
285   my $locale = $cust_main->locale || '';
286   warn "no locale for cust#".$cust_main->custnum."; using default content\n"
287     if $DEBUG and !$locale;
288   my $content = $self->content($cust_main->locale);
289   warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
290     if($DEBUG);
291
292   my $subs = $self->substitutions;
293
294   ###
295   # create substitution table
296   ###  
297   my %hash;
298   my @objects = ($cust_main);
299   my @prefixes = ('');
300   my $svc;
301   if( ref $object ) {
302     if( ref($object) eq 'ARRAY' ) {
303       # [new, old], for provisioning tickets
304       push @objects, $object->[0], $object->[1];
305       push @prefixes, 'new_', 'old_';
306       $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
307     }
308     else {
309       push @objects, $object;
310       push @prefixes, '';
311       $svc = $object if $object->isa('FS::svc_Common');
312     }
313   }
314   if( $svc ) {
315     push @objects, $svc->cust_svc->cust_pkg;
316     push @prefixes, '';
317   }
318
319   foreach my $obj (@objects) {
320     my $prefix = shift @prefixes;
321     foreach my $name (@{ $subs->{$obj->table} }) {
322       if(!ref($name)) {
323         # simple case
324         $hash{$prefix.$name} = $obj->$name();
325       }
326       elsif( ref($name) eq 'ARRAY' ) {
327         # [ foo => sub { ... } ]
328         $hash{$prefix.($name->[0])} = $name->[1]->($obj);
329       }
330       else {
331         warn "bad msg_template substitution: '$name'\n";
332         #skip it?
333       } 
334     } 
335   } 
336
337   if ( $opt{substitutions} ) {
338     $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
339   }
340
341   $_ = encode_entities($_ || '') foreach values(%hash);
342
343   ###
344   # clean up template
345   ###
346   my $subject_tmpl = new Text::Template (
347     TYPE   => 'STRING',
348     SOURCE => $content->subject,
349   );
350   my $subject = $subject_tmpl->fill_in( HASH => \%hash );
351
352   my $body = $content->body;
353   my ($skin, $guts) = eviscerate($body);
354   @$guts = map { 
355     $_ = decode_entities($_); # turn all punctuation back into itself
356     s/\r//gs;           # remove \r's
357     s/<br[^>]*>/\n/gsi; # and <br /> tags
358     s/<p>/\n/gsi;       # and <p>
359     s/<\/p>//gsi;       # and </p>
360     s/\240/ /gs;        # and &nbsp;
361     $_
362   } @$guts;
363   
364   $body = '{ use Date::Format qw(time2str); "" }';
365   while(@$skin || @$guts) {
366     $body .= shift(@$skin) || '';
367     $body .= shift(@$guts) || '';
368   }
369
370   ###
371   # fill-in
372   ###
373
374   my $body_tmpl = new Text::Template (
375     TYPE          => 'STRING',
376     SOURCE        => $body,
377   );
378
379   $body = $body_tmpl->fill_in( HASH => \%hash );
380
381   ###
382   # and email
383   ###
384
385   my @to;
386   if ( exists($opt{'to'}) ) {
387     @to = split(/\s*,\s*/, $opt{'to'});
388   }
389   else {
390     @to = $cust_main->invoicing_list_emailonly;
391   }
392   # no warning when preparing with no destination
393
394   my $from_addr = $self->from_addr;
395
396   if ( !$from_addr ) {
397     if ( $opt{'from_config'} ) {
398       $from_addr = scalar( $conf->config($opt{'from_config'}, 
399                                          $cust_main->agentnum) );
400     }
401     $from_addr ||= scalar( $conf->config('invoice_from',
402                                          $cust_main->agentnum) );
403   }
404 #  my @cust_msg = ();
405 #  if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
406 #    my $cust_msg = FS::cust_msg->new({
407 #        'custnum' => $cust_main->custnum,
408 #        'msgnum'  => $self->msgnum,
409 #        'status'  => 'prepared',
410 #      });
411 #    $cust_msg->insert;
412 #    @cust_msg = ('cust_msg' => $cust_msg);
413 #  }
414
415   my $text_body = encode('UTF-8',
416                   HTML::FormatText->new(leftmargin => 0, rightmargin => 70)
417                       ->format( HTML::TreeBuilder->new_from_content($body) )
418                   );
419   (
420     'custnum' => $cust_main->custnum,
421     'msgnum'  => $self->msgnum,
422     'from' => $from_addr,
423     'to'   => \@to,
424     'bcc'  => $self->bcc_addr || undef,
425     'subject'   => $subject,
426     'html_body' => $body,
427     'text_body' => $text_body
428   );
429
430 }
431
432 =item send OPTION => VALUE
433
434 Fills in the template and sends it to the customer.  Options are as for 
435 'prepare'.
436
437 =cut
438
439 # broken out from prepare() in case we want to queue the sending,
440 # preview it, etc.
441 sub send {
442   my $self = shift;
443   send_email(generate_email($self->prepare(@_)));
444 }
445
446 =item render OPTION => VALUE ...
447
448 Fills in the template and renders it to a PDF document.  Returns the 
449 name of the PDF file.
450
451 Options are as for 'prepare', but 'from' and 'to' are meaningless.
452
453 =cut
454
455 # will also have options to set paper size, margins, etc.
456
457 sub render {
458   my $self = shift;
459   eval "use PDF::WebKit";
460   die $@ if $@;
461   my %opt = @_;
462   my %hash = $self->prepare(%opt);
463   my $html = $hash{'html_body'};
464
465   # Graphics/stylesheets should probably go in /var/www on the Freeside 
466   # machine.
467   my $kit = PDF::WebKit->new(\$html); #%options
468   # hack to use our wrapper script
469   $kit->configure(sub { shift->wkhtmltopdf('freeside-wkhtmltopdf') });
470
471   $kit->to_pdf;
472 }
473
474 =item print OPTIONS
475
476 Render a PDF and send it to the printer.  OPTIONS are as for 'render'.
477
478 =cut
479
480 sub print {
481   my( $self, %opt ) = @_;
482   do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
483 }
484
485 # helper sub for package dates
486 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
487
488 # helper sub for money amounts
489 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
490
491 # helper sub for usage-related messages
492 my $usage_warning = sub {
493   my $svc = shift;
494   foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
495     my $amount = $svc->$col; next if $amount eq '';
496     my $method = $col.'_threshold';
497     my $threshold = $svc->$method; next if $threshold eq '';
498     return [$col, $amount, $threshold] if $amount <= $threshold;
499     # this only returns the first one that's below threshold, if there are 
500     # several.
501   }
502   return ['', '', ''];
503 };
504
505 #my $conf = new FS::Conf;
506
507 #return contexts and fill-in values
508 # If you add anything, be sure to add a description in 
509 # httemplate/edit/msg_template.html.
510 sub substitutions {
511   { 'cust_main' => [qw(
512       display_custnum agentnum agent_name
513
514       last first company
515       name name_short contact contact_firstlast
516       address1 address2 city county state zip
517       country
518       daytime night mobile fax
519
520       has_ship_address
521       ship_name ship_name_short ship_contact ship_contact_firstlast
522       ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
523       ship_country
524
525       paymask payname paytype payip
526       num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
527       classname categoryname
528       balance
529       credit_limit
530       invoicing_list_emailonly
531       cust_status ucfirst_cust_status cust_statuscolor
532
533       signupdate dundate
534       packages recurdates
535       ),
536       [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
537       #compatibility: obsolete ship_ fields - use the non-ship versions
538       map (
539         { my $field = $_;
540           [ "ship_$field"   => sub { shift->$field } ]
541         }
542         qw( last first company daytime night fax )
543       ),
544       # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
545       # still work, though
546       [ expdate           => sub { shift->paydate_epoch } ], #compatibility
547       [ signupdate_ymd    => sub { $ymd->(shift->signupdate) } ],
548       [ dundate_ymd       => sub { $ymd->(shift->dundate) } ],
549       [ paydate_my        => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
550       [ otaker_first      => sub { shift->access_user->first } ],
551       [ otaker_last       => sub { shift->access_user->last } ],
552       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
553       [ company_name      => sub { 
554           $conf->config('company_name', shift->agentnum) 
555         } ],
556       [ company_address   => sub {
557           $conf->config('company_address', shift->agentnum)
558         } ],
559       [ company_phonenum  => sub {
560           $conf->config('company_phonenum', shift->agentnum)
561         } ],
562     ],
563     # next_bill_date
564     'cust_pkg'  => [qw( 
565       pkgnum pkg_label pkg_label_long
566       location_label
567       status statuscolor
568     
569       start_date setup bill last_bill 
570       adjourn susp expire 
571       labels_short
572       ),
573       [ pkg               => sub { shift->part_pkg->pkg } ],
574       [ pkg_category      => sub { shift->part_pkg->categoryname } ],
575       [ pkg_class         => sub { shift->part_pkg->classname } ],
576       [ cancel            => sub { shift->getfield('cancel') } ], # grrr...
577       [ start_ymd         => sub { $ymd->(shift->getfield('start_date')) } ],
578       [ setup_ymd         => sub { $ymd->(shift->getfield('setup')) } ],
579       [ next_bill_ymd     => sub { $ymd->(shift->getfield('bill')) } ],
580       [ last_bill_ymd     => sub { $ymd->(shift->getfield('last_bill')) } ],
581       [ adjourn_ymd       => sub { $ymd->(shift->getfield('adjourn')) } ],
582       [ susp_ymd          => sub { $ymd->(shift->getfield('susp')) } ],
583       [ expire_ymd        => sub { $ymd->(shift->getfield('expire')) } ],
584       [ cancel_ymd        => sub { $ymd->(shift->getfield('cancel')) } ],
585
586       # not necessarily correct for non-flat packages
587       [ setup_fee         => sub { shift->part_pkg->option('setup_fee') } ],
588       [ recur_fee         => sub { shift->part_pkg->option('recur_fee') } ],
589
590       [ freq_pretty       => sub { shift->part_pkg->freq_pretty } ],
591
592     ],
593     'cust_bill' => [qw(
594       invnum
595       _date
596     )],
597     #XXX not really thinking about cust_bill substitutions quite yet
598     
599     # for welcome and limit warning messages
600     'svc_acct' => [qw(
601       svcnum
602       username
603       domain
604       ),
605       [ password          => sub { shift->getfield('_password') } ],
606       [ column            => sub { &$usage_warning(shift)->[0] } ],
607       [ amount            => sub { &$usage_warning(shift)->[1] } ],
608       [ threshold         => sub { &$usage_warning(shift)->[2] } ],
609     ],
610     'svc_domain' => [qw(
611       svcnum
612       domain
613       ),
614       [ registrar         => sub {
615           my $registrar = qsearchs('registrar', 
616             { registrarnum => shift->registrarnum} );
617           $registrar ? $registrar->registrarname : ''
618         }
619       ],
620       [ catchall          => sub { 
621           my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
622           $svc_acct ? $svc_acct->email : ''
623         }
624       ],
625     ],
626     'svc_phone' => [qw(
627       svcnum
628       phonenum
629       countrycode
630       domain
631       )
632     ],
633     'svc_broadband' => [qw(
634       svcnum
635       speed_up
636       speed_down
637       ip_addr
638       mac_addr
639       )
640     ],
641     # for payment receipts
642     'cust_pay' => [qw(
643       paynum
644       _date
645       ),
646       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
647       # overrides the one in cust_main in cases where a cust_pay is passed
648       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
649       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
650       [ payinfo           => sub { 
651           my $cust_pay = shift;
652           ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
653             $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
654         } ],
655     ],
656     # for payment decline messages
657     # try to support all cust_pay fields
658     # 'error' is a special case, it contains the raw error from the gateway
659     'cust_pay_pending' => [qw(
660       _date
661       error
662       ),
663       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
664       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
665       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
666       [ payinfo           => sub {
667           my $pending = shift;
668           ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
669             $pending->paymask : $pending->decrypt($pending->payinfo)
670         } ],
671     ],
672   };
673 }
674
675 =item content LOCALE
676
677 Returns the L<FS::template_content> object appropriate to LOCALE, if there 
678 is one.  If not, returns the one with a NULL locale.
679
680 =cut
681
682 sub content {
683   my $self = shift;
684   my $locale = shift;
685   qsearchs('template_content', 
686             { 'msgnum' => $self->msgnum, 'locale' => $locale }) || 
687   qsearchs('template_content',
688             { 'msgnum' => $self->msgnum, 'locale' => '' });
689 }
690
691 =item agent
692
693 Returns the L<FS::agent> object for this template.
694
695 =cut
696
697 sub _upgrade_data {
698   my ($self, %opts) = @_;
699
700   my @fixes = (
701     [ 'alerter_msgnum',  'alerter_template',   '',               '', '' ],
702     [ 'cancel_msgnum',   'cancelmessage',      'cancelsubject',  '', '' ],
703     [ 'decline_msgnum',  'declinetemplate',    '',               '', '' ],
704     [ 'impending_recur_msgnum', 'impending_recur_template', '',  '', 'impending_recur_bcc' ],
705     [ 'payment_receipt_msgnum', 'payment_receipt_email', '',     '', '' ],
706     [ 'welcome_msgnum',  'welcome_email',      'welcome_email-subject', 'welcome_email-from', '' ],
707     [ 'warning_msgnum',  'warning_email',      'warning_email-subject', 'warning_email-from', '' ],
708   );
709  
710   my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
711   foreach my $agentnum (@agentnums) {
712     foreach (@fixes) {
713       my ($newname, $oldname, $subject, $from, $bcc) = @$_;
714       if ($conf->exists($oldname, $agentnum)) {
715         my $new = new FS::msg_template({
716           'msgname'   => $oldname,
717           'agentnum'  => $agentnum,
718           'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
719           'bcc_addr'  => ($bcc && $conf->config($from, $agentnum)) || '',
720           'subject'   => ($subject && $conf->config($subject, $agentnum)) || '',
721           'mime_type' => 'text/html',
722           'body'      => join('<BR>',$conf->config($oldname, $agentnum)),
723         });
724         my $error = $new->insert;
725         die $error if $error;
726         $conf->set($newname, $new->msgnum, $agentnum);
727         $conf->delete($oldname, $agentnum);
728         $conf->delete($from, $agentnum) if $from;
729         $conf->delete($subject, $agentnum) if $subject;
730       }
731     }
732
733     if ( $conf->exists('alert_expiration', $agentnum) ) {
734       my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
735       my $template = FS::msg_template->by_key($msgnum) if $msgnum;
736       if (!$template) {
737         warn "template for alerter_msgnum $msgnum not found\n";
738         next;
739       }
740       # this is now a set of billing events
741       foreach my $days (30, 15, 5) {
742         my $event = FS::part_event->new({
743             'agentnum'    => $agentnum,
744             'event'       => "Card expiration warning - $days days",
745             'eventtable'  => 'cust_main',
746             'check_freq'  => '1d',
747             'action'      => 'notice',
748             'disabled'    => 'Y', #initialize first
749         });
750         my $error = $event->insert( 'msgnum' => $msgnum );
751         if ($error) {
752           warn "error creating expiration alert event:\n$error\n\n";
753           next;
754         }
755         # make it work like before:
756         # only send each warning once before the card expires,
757         # only warn active customers,
758         # only warn customers with CARD/DCRD,
759         # only warn customers who get email invoices
760         my %conds = (
761           'once_every'          => { 'run_delay' => '30d' },
762           'cust_paydate_within' => { 'within' => $days.'d' },
763           'cust_status'         => { 'status' => { 'active' => 1 } },
764           'payby'               => { 'payby'  => { 'CARD' => 1,
765                                                    'DCRD' => 1, }
766                                    },
767           'message_email'       => {},
768         );
769         foreach (keys %conds) {
770           my $condition = FS::part_event_condition->new({
771               'conditionname' => $_,
772               'eventpart'     => $event->eventpart,
773           });
774           $error = $condition->insert( %{ $conds{$_} });
775           if ( $error ) {
776             warn "error creating expiration alert event:\n$error\n\n";
777             next;
778           }
779         }
780         $error = $event->initialize;
781         if ( $error ) {
782           warn "expiration alert event was created, but not initialized:\n$error\n\n";
783         }
784       } # foreach $days
785       $conf->delete('alerter_msgnum', $agentnum);
786       $conf->delete('alert_expiration', $agentnum);
787
788     } # if alerter_msgnum
789
790   }
791   foreach my $msg_template ( qsearch('msg_template', {}) ) {
792     if ( $msg_template->subject || $msg_template->body ) {
793       # create new default content
794       my %content;
795       $content{subject} = $msg_template->subject;
796       $msg_template->set('subject', '');
797
798       # work around obscure Pg/DBD bug
799       # https://rt.cpan.org/Public/Bug/Display.html?id=60200
800       # (though the right fix is to upgrade DBD)
801       my $body = $msg_template->body;
802       if ( $body =~ /^x([0-9a-f]+)$/ ) {
803         # there should be no real message templates that look like that
804         warn "converting template body to TEXT\n";
805         $body = pack('H*', $1);
806       }
807       $content{body} = $body;
808       $msg_template->set('body', '');
809
810       my $error = $msg_template->replace(%content);
811       die $error if $error;
812     }
813   }
814 }
815
816 sub eviscerate {
817   # Every bit as pleasant as it sounds.
818   #
819   # We do this because Text::Template::Preprocess doesn't
820   # actually work.  It runs the entire template through 
821   # the preprocessor, instead of the code segments.  Which 
822   # is a shame, because Text::Template already contains
823   # the code to do this operation.
824   my $body = shift;
825   my (@outside, @inside);
826   my $depth = 0;
827   my $chunk = '';
828   while($body || $chunk) {
829     my ($first, $delim, $rest);
830     # put all leading non-delimiters into $first
831     ($first, $rest) =
832         ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
833     $chunk .= $first;
834     # put a leading delimiter into $delim if there is one
835     ($delim, $rest) =
836       ($rest =~ /^([{}]?)(.*)$/s);
837
838     if( $delim eq '{' ) {
839       $chunk .= '{';
840       if( $depth == 0 ) {
841         push @outside, $chunk;
842         $chunk = '';
843       }
844       $depth++;
845     }
846     elsif( $delim eq '}' ) {
847       $depth--;
848       if( $depth == 0 ) {
849         push @inside, $chunk;
850         $chunk = '';
851       }
852       $chunk .= '}';
853     }
854     else {
855       # no more delimiters
856       if( $depth == 0 ) {
857         push @outside, $chunk . $rest;
858       } # else ? something wrong
859       last;
860     }
861     $body = $rest;
862   }
863   (\@outside, \@inside);
864 }
865
866 =back
867
868 =head1 BUGS
869
870 =head1 SEE ALSO
871
872 L<FS::Record>, schema.html from the base documentation.
873
874 =cut
875
876 1;
877