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