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