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