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