This commit was generated by cvs2svn to compensate for changes in r10640,
[freeside.git] / FS / FS / msg_template.pm
1 package FS::msg_template;
2
3 use strict;
4 use base qw( FS::Record );
5 use Text::Template;
6 use FS::Misc qw( generate_email send_email );
7 use FS::Conf;
8 use FS::Record qw( qsearch qsearchs );
9
10 use Date::Format qw( time2str );
11 use HTML::Entities qw( decode_entities encode_entities ) ;
12 use HTML::FormatText;
13 use HTML::TreeBuilder;
14 use vars '$DEBUG';
15
16 $DEBUG=0;
17
18 =head1 NAME
19
20 FS::msg_template - Object methods for msg_template records
21
22 =head1 SYNOPSIS
23
24   use FS::msg_template;
25
26   $record = new FS::msg_template \%hash;
27   $record = new FS::msg_template { 'column' => 'value' };
28
29   $error = $record->insert;
30
31   $error = $new_record->replace($old_record);
32
33   $error = $record->delete;
34
35   $error = $record->check;
36
37 =head1 DESCRIPTION
38
39 An FS::msg_template object represents a customer message template.
40 FS::msg_template inherits from FS::Record.  The following fields are currently
41 supported:
42
43 =over 4
44
45 =item msgnum
46
47 primary key
48
49 =item msgname
50
51 Template name.
52
53 =item agentnum
54
55 Agent associated with this template.  Can be NULL for a global template.
56
57 =item mime_type
58
59 MIME type.  Defaults to text/html.
60
61 =item from_addr
62
63 Source email address.
64
65 =item subject
66
67 The message subject line, in L<Text::Template> format.
68
69 =item body
70
71 The message body, as plain text or HTML, in L<Text::Template> format.
72
73 =item disabled
74
75 disabled
76
77 =back
78
79 =head1 METHODS
80
81 =over 4
82
83 =item new HASHREF
84
85 Creates a new template.  To add the template to the database, see L<"insert">.
86
87 Note that this stores the hash reference, not a distinct copy of the hash it
88 points to.  You can ask the object for a copy with the I<hash> method.
89
90 =cut
91
92 # the new method can be inherited from FS::Record, if a table method is defined
93
94 sub table { 'msg_template'; }
95
96 =item insert
97
98 Adds this record to the database.  If there is an error, returns the error,
99 otherwise returns false.
100
101 =cut
102
103 # the insert method can be inherited from FS::Record
104
105 =item delete
106
107 Delete this record from the database.
108
109 =cut
110
111 # the delete method can be inherited from FS::Record
112
113 =item replace OLD_RECORD
114
115 Replaces the OLD_RECORD with this one in the database.  If there is an error,
116 returns the error, otherwise returns false.
117
118 =cut
119
120 # the replace method can be inherited from FS::Record
121
122 =item check
123
124 Checks all fields to make sure this is a valid template.  If there is
125 an error, returns the error, otherwise returns false.  Called by the insert
126 and replace methods.
127
128 =cut
129
130 # the check method should currently be supplied - FS::Record contains some
131 # data checking routines
132
133 sub check {
134   my $self = shift;
135
136   my $error = 
137     $self->ut_numbern('msgnum')
138     || $self->ut_text('msgname')
139     || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
140     || $self->ut_textn('mime_type')
141     || $self->ut_anything('subject')
142     || $self->ut_anything('body')
143     || $self->ut_enum('disabled', [ '', 'Y' ] )
144     || $self->ut_textn('from_addr')
145   ;
146   return $error if $error;
147
148   $self->mime_type('text/html') unless $self->mime_type;
149
150   $self->SUPER::check;
151 }
152
153 =item prepare OPTION => VALUE
154
155 Fills in the template and returns a hash of the 'from' address, 'to' 
156 addresses, subject line, and body.
157
158 Options are passed as a list of name/value pairs:
159
160 =over 4
161
162 =item cust_main
163
164 Customer object (required).
165
166 =item object
167
168 Additional context object (currently, can be a cust_main, cust_pkg, 
169 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband, 
170 domain) ).  If the object is a svc_*, its cust_pkg will be fetched and 
171 used for substitution.
172
173 As a special case, this may be an arrayref of two objects.  Both 
174 objects will be available for substitution, with their field names 
175 prefixed with 'new_' and 'old_' respectively.  This is used in the 
176 rt_ticket export when exporting "replace" events.
177
178 =item to
179
180 Destination address.  The default is to use the customer's 
181 invoicing_list addresses.  Multiple addresses may be comma-separated.
182
183 =back
184
185 =cut
186
187 sub prepare {
188   my( $self, %opt ) = @_;
189
190   my $cust_main = $opt{'cust_main'};
191   my $object = $opt{'object'};
192   warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
193     if($DEBUG);
194
195   my $subs = $self->substitutions;
196
197   ###
198   # create substitution table
199   ###  
200   my %hash;
201   my @objects = ($cust_main);
202   my @prefixes = ('');
203   my $svc;
204   if( ref $object ) {
205     if( ref($object) eq 'ARRAY' ) {
206       # [new, old], for provisioning tickets
207       push @objects, $object->[0], $object->[1];
208       push @prefixes, 'new_', 'old_';
209       $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
210     }
211     else {
212       push @objects, $object;
213       push @prefixes, '';
214       $svc = $object if $object->isa('FS::svc_Common');
215     }
216   }
217   if( $svc ) {
218     push @objects, $svc->cust_svc->cust_pkg;
219     push @prefixes, '';
220   }
221
222   foreach my $obj (@objects) {
223     my $prefix = shift @prefixes;
224     foreach my $name (@{ $subs->{$obj->table} }) {
225       if(!ref($name)) {
226         # simple case
227         $hash{$prefix.$name} = $obj->$name();
228       }
229       elsif( ref($name) eq 'ARRAY' ) {
230         # [ foo => sub { ... } ]
231         $hash{$prefix.($name->[0])} = $name->[1]->($obj);
232       }
233       else {
234         warn "bad msg_template substitution: '$name'\n";
235         #skip it?
236       } 
237     } 
238   } 
239   $_ = encode_entities($_) foreach values(%hash);
240
241
242   ###
243   # clean up template
244   ###
245   my $subject_tmpl = new Text::Template (
246     TYPE   => 'STRING',
247     SOURCE => $self->subject,
248   );
249   my $subject = $subject_tmpl->fill_in( HASH => \%hash );
250
251   my $body = $self->body;
252   my ($skin, $guts) = eviscerate($body);
253   @$guts = map { 
254     $_ = decode_entities($_); # turn all punctuation back into itself
255     s/\r//gs;           # remove \r's
256     s/<br[^>]*>/\n/gsi; # and <br /> tags
257     s/<p>/\n/gsi;       # and <p>
258     s/<\/p>//gsi;       # and </p>
259     s/\240/ /gs;        # and &nbsp;
260     $_
261   } @$guts;
262   
263   $body = '{ use Date::Format qw(time2str); "" }';
264   while(@$skin || @$guts) {
265     $body .= shift(@$skin) || '';
266     $body .= shift(@$guts) || '';
267   }
268
269   ###
270   # fill-in
271   ###
272
273   my $body_tmpl = new Text::Template (
274     TYPE          => 'STRING',
275     SOURCE        => $body,
276   );
277
278   $body = $body_tmpl->fill_in( HASH => \%hash );
279
280   ###
281   # and email
282   ###
283
284   my @to;
285   if ( exists($opt{'to'}) ) {
286     @to = split(/\s*,\s*/, $opt{'to'});
287   }
288   else {
289     @to = $cust_main->invoicing_list_emailonly;
290   }
291   # no warning when preparing with no destination
292
293   my $conf = new FS::Conf;
294
295   (
296     'from' => $self->from_addr || 
297               scalar( $conf->config('invoice_from', $cust_main->agentnum) ),
298     'to'   => \@to,
299     'bcc'  => $self->bcc_addr || undef,
300     'subject'   => $subject,
301     'html_body' => $body,
302     'text_body' => HTML::FormatText->new(leftmargin => 0, rightmargin => 70
303                     )->format( HTML::TreeBuilder->new_from_content($body) ),
304   );
305
306 }
307
308 =item send OPTION => VALUE
309
310 Fills in the template and sends it to the customer.  Options are as for 
311 'prepare'.
312
313 =cut
314
315 # broken out from prepare() in case we want to queue the sending,
316 # preview it, etc.
317 sub send {
318   my $self = shift;
319   send_email(generate_email($self->prepare(@_)));
320 }
321
322 # helper sub for package dates
323 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
324
325 # needed for some things
326 my $conf = new FS::Conf;
327
328 #return contexts and fill-in values
329 # If you add anything, be sure to add a description in 
330 # httemplate/edit/msg_template.html.
331 sub substitutions {
332   { 'cust_main' => [qw(
333       display_custnum agentnum agent_name
334
335       last first company
336       name name_short contact contact_firstlast
337       address1 address2 city county state zip
338       country
339       daytime night fax
340
341       has_ship_address
342       ship_last ship_first ship_company
343       ship_name ship_name_short ship_contact ship_contact_firstlast
344       ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
345       ship_country
346       ship_daytime ship_night ship_fax
347
348       paymask payname paytype payip
349       num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
350       classname categoryname
351       balance
352       credit_limit
353       invoicing_list_emailonly
354       cust_status ucfirst_cust_status cust_statuscolor
355
356       signupdate dundate
357       expdate
358       packages recurdates
359       ),
360       # expdate is a special case
361       [ signupdate_ymd    => sub { time2str('%Y-%m-%d', shift->signupdate) } ],
362       [ dundate_ymd       => sub { time2str('%Y-%m-%d', shift->dundate) } ],
363       [ paydate_my        => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
364       [ otaker_first      => sub { shift->access_user->first } ],
365       [ otaker_last       => sub { shift->access_user->last } ],
366       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
367       [ company_name      => sub { 
368           $conf->config('company_name', shift->agentnum) 
369         } ],
370       [ company_address   => sub {
371           $conf->config('company_address', shift->agentnum)
372         } ],
373     ],
374     # next_bill_date
375     'cust_pkg'  => [qw( 
376       pkgnum pkg_label pkg_label_long
377       location_label
378       status statuscolor
379     
380       start_date setup bill last_bill 
381       adjourn susp expire 
382       labels_short
383       ),
384       [ pkg               => sub { shift->part_pkg->pkg } ],
385       [ cancel            => sub { shift->getfield('cancel') } ], # grrr...
386       [ start_ymd         => sub { $ymd->(shift->getfield('start_date')) } ],
387       [ setup_ymd         => sub { $ymd->(shift->getfield('setup')) } ],
388       [ next_bill_ymd     => sub { $ymd->(shift->getfield('bill')) } ],
389       [ last_bill_ymd     => sub { $ymd->(shift->getfield('last_bill')) } ],
390       [ adjourn_ymd       => sub { $ymd->(shift->getfield('adjourn')) } ],
391       [ susp_ymd          => sub { $ymd->(shift->getfield('susp')) } ],
392       [ expire_ymd        => sub { $ymd->(shift->getfield('expire')) } ],
393       [ cancel_ymd        => sub { $ymd->(shift->getfield('cancel')) } ],
394     ],
395     'cust_bill' => [qw(
396       invnum
397       _date
398     )],
399     #XXX not really thinking about cust_bill substitutions quite yet
400     
401     # for welcome and limit warning messages
402     'svc_acct' => [qw(
403       svcnum
404       username
405       domain
406       ),
407       [ password          => sub { shift->getfield('_password') } ],
408     ],
409     'svc_domain' => [qw(
410       svcnum
411       domain
412       ),
413       [ registrar         => sub {
414           my $registrar = qsearchs('registrar', 
415             { registrarnum => shift->registrarnum} );
416           $registrar ? $registrar->registrarname : ''
417         }
418       ],
419       [ catchall          => sub { 
420           my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
421           $svc_acct ? $svc_acct->email : ''
422         }
423       ],
424     ],
425     'svc_phone' => [qw(
426       svcnum
427       phonenum
428       countrycode
429       domain
430       )
431     ],
432     'svc_broadband' => [qw(
433       svcnum
434       speed_up
435       speed_down
436       ip_addr
437       mac_addr
438       )
439     ],
440     # for payment receipts
441     'cust_pay' => [qw(
442       paynum
443       _date
444       ),
445       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
446       # overrides the one in cust_main in cases where a cust_pay is passed
447       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
448       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
449       [ payinfo           => sub { 
450           my $cust_pay = shift;
451           ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
452             $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
453         } ],
454     ],
455     # for payment decline messages
456     # try to support all cust_pay fields
457     # 'error' is a special case, it contains the raw error from the gateway
458     'cust_pay_pending' => [qw(
459       _date
460       error
461       ),
462       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
463       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
464       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
465       [ payinfo           => sub {
466           my $pending = shift;
467           ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
468             $pending->paymask : $pending->decrypt($pending->payinfo)
469         } ],
470     ],
471   };
472 }
473
474 sub _upgrade_data {
475   my ($self, %opts) = @_;
476
477   my @fixes = (
478     [ 'alerter_msgnum',  'alerter_template',   '',               '', '' ],
479     [ 'cancel_msgnum',   'cancelmessage',      'cancelsubject',  '', '' ],
480     [ 'decline_msgnum',  'declinetemplate',    '',               '', '' ],
481     [ 'impending_recur_msgnum', 'impending_recur_template', '',  '', 'impending_recur_bcc' ],
482     [ 'payment_receipt_msgnum', 'payment_receipt_email', '',     '', '' ],
483     [ 'welcome_msgnum',  'welcome_email',      'welcome_email-subject', 'welcome_email-from', '' ],
484     [ 'warning_msgnum',  'warning_email',      'warning_email-subject', 'warning_email-from', '' ],
485   );
486  
487   my $conf = new FS::Conf;
488   my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
489   foreach my $agentnum (@agentnums) {
490     foreach (@fixes) {
491       my ($newname, $oldname, $subject, $from, $bcc) = @$_;
492       if ($conf->exists($oldname, $agentnum)) {
493         my $new = new FS::msg_template({
494            'msgname'   => $oldname,
495            'agentnum'  => $agentnum,
496            'from_addr' => ($from && $conf->config($from, $agentnum)) || 
497                           $conf->config('invoice_from', $agentnum),
498            'bcc_addr'  => ($bcc && $conf->config($from, $agentnum)) || '',
499            'subject'   => ($subject && $conf->config($subject, $agentnum)) || '',
500            'mime_type' => 'text/html',
501            'body'      => join('<BR>',$conf->config($oldname, $agentnum)),
502         });
503         my $error = $new->insert;
504         die $error if $error;
505         $conf->set($newname, $new->msgnum, $agentnum);
506         $conf->delete($oldname, $agentnum);
507         $conf->delete($from, $agentnum) if $from;
508         $conf->delete($subject, $agentnum) if $subject;
509       }
510     }
511   }
512 }
513
514 sub eviscerate {
515   # Every bit as pleasant as it sounds.
516   #
517   # We do this because Text::Template::Preprocess doesn't
518   # actually work.  It runs the entire template through 
519   # the preprocessor, instead of the code segments.  Which 
520   # is a shame, because Text::Template already contains
521   # the code to do this operation.
522   my $body = shift;
523   my (@outside, @inside);
524   my $depth = 0;
525   my $chunk = '';
526   while($body || $chunk) {
527     my ($first, $delim, $rest);
528     # put all leading non-delimiters into $first
529     ($first, $rest) =
530         ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
531     $chunk .= $first;
532     # put a leading delimiter into $delim if there is one
533     ($delim, $rest) =
534       ($rest =~ /^([{}]?)(.*)$/s);
535
536     if( $delim eq '{' ) {
537       $chunk .= '{';
538       if( $depth == 0 ) {
539         push @outside, $chunk;
540         $chunk = '';
541       }
542       $depth++;
543     }
544     elsif( $delim eq '}' ) {
545       $depth--;
546       if( $depth == 0 ) {
547         push @inside, $chunk;
548         $chunk = '';
549       }
550       $chunk .= '}';
551     }
552     else {
553       # no more delimiters
554       if( $depth == 0 ) {
555         push @outside, $chunk . $rest;
556       } # else ? something wrong
557       last;
558     }
559     $body = $rest;
560   }
561   (\@outside, \@inside);
562 }
563
564 =back
565
566 =head1 BUGS
567
568 =head1 SEE ALSO
569
570 L<FS::Record>, schema.html from the base documentation.
571
572 =cut
573
574 1;
575