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