RT#38217: Send email when logging conditions are met
[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   { 'cust_main' => [qw(
466       display_custnum agentnum agent_name
467
468       last first company
469       name name_short contact contact_firstlast
470       address1 address2 city county state zip
471       country
472       daytime night mobile fax
473
474       has_ship_address
475       ship_name ship_name_short ship_contact ship_contact_firstlast
476       ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
477       ship_country
478
479       paymask payname paytype payip
480       num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
481       classname categoryname
482       balance
483       credit_limit
484       invoicing_list_emailonly
485       cust_status ucfirst_cust_status cust_statuscolor cust_status_label
486
487       signupdate dundate
488       packages recurdates
489       ),
490       [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
491       #compatibility: obsolete ship_ fields - use the non-ship versions
492       map (
493         { my $field = $_;
494           [ "ship_$field"   => sub { shift->$field } ]
495         }
496         qw( last first company daytime night fax )
497       ),
498       # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
499       # still work, though
500       [ expdate           => sub { shift->paydate_epoch } ], #compatibility
501       [ signupdate_ymd    => sub { $ymd->(shift->signupdate) } ],
502       [ dundate_ymd       => sub { $ymd->(shift->dundate) } ],
503       [ paydate_my        => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
504       [ otaker_first      => sub { shift->access_user->first } ],
505       [ otaker_last       => sub { shift->access_user->last } ],
506       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
507       [ company_name      => sub { 
508           $conf->config('company_name', shift->agentnum) 
509         } ],
510       [ company_address   => sub {
511           $conf->config('company_address', shift->agentnum)
512         } ],
513       [ company_phonenum  => sub {
514           $conf->config('company_phonenum', shift->agentnum)
515         } ],
516       [ selfservice_server_base_url => sub { 
517           $conf->config('selfservice_server-base_url') #, shift->agentnum) 
518         } ],
519     ],
520     # next_bill_date
521     'cust_pkg'  => [qw( 
522       pkgnum pkg_label pkg_label_long
523       location_label
524       status statuscolor
525     
526       start_date setup bill last_bill 
527       adjourn susp expire 
528       labels_short
529       ),
530       [ pkg               => sub { shift->part_pkg->pkg } ],
531       [ pkg_category      => sub { shift->part_pkg->categoryname } ],
532       [ pkg_class         => sub { shift->part_pkg->classname } ],
533       [ cancel            => sub { shift->getfield('cancel') } ], # grrr...
534       [ start_ymd         => sub { $ymd->(shift->getfield('start_date')) } ],
535       [ setup_ymd         => sub { $ymd->(shift->getfield('setup')) } ],
536       [ next_bill_ymd     => sub { $ymd->(shift->getfield('bill')) } ],
537       [ last_bill_ymd     => sub { $ymd->(shift->getfield('last_bill')) } ],
538       [ adjourn_ymd       => sub { $ymd->(shift->getfield('adjourn')) } ],
539       [ susp_ymd          => sub { $ymd->(shift->getfield('susp')) } ],
540       [ expire_ymd        => sub { $ymd->(shift->getfield('expire')) } ],
541       [ cancel_ymd        => sub { $ymd->(shift->getfield('cancel')) } ],
542
543       # not necessarily correct for non-flat packages
544       [ setup_fee         => sub { shift->part_pkg->option('setup_fee') } ],
545       [ recur_fee         => sub { shift->part_pkg->option('recur_fee') } ],
546
547       [ freq_pretty       => sub { shift->part_pkg->freq_pretty } ],
548
549     ],
550     'cust_bill' => [qw(
551       invnum
552       _date
553       _date_pretty
554       due_date
555     ),
556       [ due_date2str      => sub { shift->due_date2str('short') } ],
557     ],
558     #XXX not really thinking about cust_bill substitutions quite yet
559     
560     # for welcome and limit warning messages
561     'svc_acct' => [qw(
562       svcnum
563       username
564       domain
565       ),
566       [ password          => sub { shift->getfield('_password') } ],
567       [ column            => sub { &$usage_warning(shift)->[0] } ],
568       [ amount            => sub { &$usage_warning(shift)->[1] } ],
569       [ threshold         => sub { &$usage_warning(shift)->[2] } ],
570     ],
571     'svc_domain' => [qw(
572       svcnum
573       domain
574       ),
575       [ registrar         => sub {
576           my $registrar = qsearchs('registrar', 
577             { registrarnum => shift->registrarnum} );
578           $registrar ? $registrar->registrarname : ''
579         }
580       ],
581       [ catchall          => sub { 
582           my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
583           $svc_acct ? $svc_acct->email : ''
584         }
585       ],
586     ],
587     'svc_phone' => [qw(
588       svcnum
589       phonenum
590       countrycode
591       domain
592       )
593     ],
594     'svc_broadband' => [qw(
595       svcnum
596       speed_up
597       speed_down
598       ip_addr
599       mac_addr
600       )
601     ],
602     # for payment receipts
603     'cust_pay' => [qw(
604       paynum
605       _date
606       ),
607       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
608       # overrides the one in cust_main in cases where a cust_pay is passed
609       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
610       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
611       [ payinfo           => sub { 
612           my $cust_pay = shift;
613           ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
614             $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
615         } ],
616     ],
617     # for payment decline messages
618     # try to support all cust_pay fields
619     # 'error' is a special case, it contains the raw error from the gateway
620     'cust_pay_pending' => [qw(
621       _date
622       error
623       ),
624       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
625       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
626       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
627       [ payinfo           => sub {
628           my $pending = shift;
629           ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
630             $pending->paymask : $pending->decrypt($pending->payinfo)
631         } ],
632     ],
633   };
634 }
635
636 =item content LOCALE
637
638 Stub, returns nothing.
639
640 =cut
641
642 sub content {}
643
644 =item agent
645
646 Returns the L<FS::agent> object for this template.
647
648 =cut
649
650 sub _upgrade_data {
651   my ($self, %opts) = @_;
652
653   ###
654   # First move any historical templates in config to real message templates
655   ###
656
657   my @fixes = (
658     [ 'alerter_msgnum',  'alerter_template',   '',               '', '' ],
659     [ 'cancel_msgnum',   'cancelmessage',      'cancelsubject',  '', '' ],
660     [ 'decline_msgnum',  'declinetemplate',    '',               '', '' ],
661     [ 'impending_recur_msgnum', 'impending_recur_template', '',  '', 'impending_recur_bcc' ],
662     [ 'payment_receipt_msgnum', 'payment_receipt_email', '',     '', '' ],
663     [ 'welcome_msgnum',  'welcome_email',      'welcome_email-subject', 'welcome_email-from', '', 'welcome_email-mimetype' ],
664     [ 'threshold_warning_msgnum',  'warning_email',      'warning_email-subject', 'warning_email-from', 'warning_email-cc', 'warning_email-mimetype' ],
665   );
666  
667   my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
668   foreach my $agentnum (@agentnums) {
669     foreach (@fixes) {
670       my ($newname, $oldname, $subject, $from, $bcc, $mimetype) = @$_;
671       
672       if ($conf->exists($oldname, $agentnum)) {
673         my $new = new FS::msg_template({
674           'msgclass'  => 'email',
675           'msgname'   => $oldname,
676           'agentnum'  => $agentnum,
677           'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
678           'bcc_addr'  => ($bcc && $conf->config($bcc, $agentnum)) || '',
679           'subject'   => ($subject && $conf->config($subject, $agentnum)) || '',
680           'mime_type' => 'text/html',
681           'body'      => join('<BR>',$conf->config($oldname, $agentnum)),
682         });
683         my $error = $new->insert;
684         die $error if $error;
685         $conf->set($newname, $new->msgnum, $agentnum);
686         $conf->delete($oldname, $agentnum);
687         $conf->delete($from, $agentnum) if $from;
688         $conf->delete($subject, $agentnum) if $subject;
689         $conf->delete($bcc, $agentnum) if $bcc;
690         $conf->delete($mimetype, $agentnum) if $mimetype;
691       }
692     }
693
694     if ( $conf->exists('alert_expiration', $agentnum) ) {
695       my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
696       my $template = FS::msg_template->by_key($msgnum) if $msgnum;
697       if (!$template) {
698         warn "template for alerter_msgnum $msgnum not found\n";
699         next;
700       }
701       # this is now a set of billing events
702       foreach my $days (30, 15, 5) {
703         my $event = FS::part_event->new({
704             'agentnum'    => $agentnum,
705             'event'       => "Card expiration warning - $days days",
706             'eventtable'  => 'cust_main',
707             'check_freq'  => '1d',
708             'action'      => 'notice',
709             'disabled'    => 'Y', #initialize first
710         });
711         my $error = $event->insert( 'msgnum' => $msgnum );
712         if ($error) {
713           warn "error creating expiration alert event:\n$error\n\n";
714           next;
715         }
716         # make it work like before:
717         # only send each warning once before the card expires,
718         # only warn active customers,
719         # only warn customers with CARD/DCRD,
720         # only warn customers who get email invoices
721         my %conds = (
722           'once_every'          => { 'run_delay' => '30d' },
723           'cust_paydate_within' => { 'within' => $days.'d' },
724           'cust_status'         => { 'status' => { 'active' => 1 } },
725           'payby'               => { 'payby'  => { 'CARD' => 1,
726                                                    'DCRD' => 1, }
727                                    },
728           'message_email'       => {},
729         );
730         foreach (keys %conds) {
731           my $condition = FS::part_event_condition->new({
732               'conditionname' => $_,
733               'eventpart'     => $event->eventpart,
734           });
735           $error = $condition->insert( %{ $conds{$_} });
736           if ( $error ) {
737             warn "error creating expiration alert event:\n$error\n\n";
738             next;
739           }
740         }
741         $error = $event->initialize;
742         if ( $error ) {
743           warn "expiration alert event was created, but not initialized:\n$error\n\n";
744         }
745       } # foreach $days
746       $conf->delete('alerter_msgnum', $agentnum);
747       $conf->delete('alert_expiration', $agentnum);
748
749     } # if alerter_msgnum
750
751   }
752
753   ###
754   # Move subject and body from msg_template to template_content
755   ###
756
757   foreach my $msg_template ( qsearch('msg_template', {}) ) {
758     if ( $msg_template->subject || $msg_template->body ) {
759       # create new default content
760       my %content;
761       $content{subject} = $msg_template->subject;
762       $msg_template->set('subject', '');
763
764       # work around obscure Pg/DBD bug
765       # https://rt.cpan.org/Public/Bug/Display.html?id=60200
766       # (though the right fix is to upgrade DBD)
767       my $body = $msg_template->body;
768       if ( $body =~ /^x([0-9a-f]+)$/ ) {
769         # there should be no real message templates that look like that
770         warn "converting template body to TEXT\n";
771         $body = pack('H*', $1);
772       }
773       $content{body} = $body;
774       $msg_template->set('body', '');
775       my $error = $msg_template->replace(%content);
776       die $error if $error;
777     }
778
779     if ( !$msg_template->msgclass ) {
780       # set default message class
781       $msg_template->set('msgclass', 'email');
782       my $error = $msg_template->replace;
783       die $error if $error;
784     }
785   }
786
787   ###
788   # Add new-style default templates if missing
789   ###
790   $self->_populate_initial_data;
791
792 }
793
794 sub _populate_initial_data { #class method
795   #my($class, %opts) = @_;
796   #my $class = shift;
797
798   eval "use FS::msg_template::InitialData;";
799   die $@ if $@;
800
801   my $initial_data = FS::msg_template::InitialData->_initial_data;
802
803   foreach my $hash ( @$initial_data ) {
804
805     next if $hash->{_conf} && $conf->config( $hash->{_conf} );
806
807     my $msg_template = new FS::msg_template($hash);
808     my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
809     die $error if $error;
810
811     $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
812   
813   }
814
815 }
816
817 =back
818
819 =head1 BUGS
820
821 =head1 SEE ALSO
822
823 L<FS::Record>, schema.html from the base documentation.
824
825 =cut
826
827 1;
828