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