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