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