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