cust_pkg fields in ticket export templates, RT#9936
[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, svc_acct, cust_pay, or cust_pay_pending).  If the object 
170 is a svc_acct, its cust_pkg will be fetched and used for substitution.
171
172 As a special case, this may be an arrayref of two objects.  Both 
173 objects will be available for substitution, with their field names 
174 prefixed with 'new_' and 'old_' respectively.  This is used in the 
175 rt_ticket export when exporting "replace" events.
176
177 =item to
178
179 Destination address.  The default is to use the customer's 
180 invoicing_list addresses.
181
182 =back
183
184 =cut
185
186 sub prepare {
187   my( $self, %opt ) = @_;
188
189   my $cust_main = $opt{'cust_main'};
190   my $object = $opt{'object'};
191   warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
192     if($DEBUG);
193
194   my $subs = $self->substitutions;
195
196   ###
197   # create substitution table
198   ###  
199   my %hash;
200   my @objects = ($cust_main);
201   my @prefixes = ('');
202   my $svc;
203   if( ref $object ) {
204     if( ref($object) eq 'ARRAY' ) {
205       # [new, old], for provisioning tickets
206       push @objects, $object->[0], $object->[1];
207       push @prefixes, 'new_', 'old_';
208       $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
209     }
210     else {
211       push @objects, $object;
212       push @prefixes, '';
213       $svc = $object if $object->isa('FS::svc_Common');
214     }
215   }
216   if( $svc ) {
217     push @objects, $svc->cust_svc->cust_pkg;
218     push @prefixes, '';
219   }
220
221   foreach my $obj (@objects) {
222     my $prefix = shift @prefixes;
223     foreach my $name (@{ $subs->{$obj->table} }) {
224       if(!ref($name)) {
225         # simple case
226         $hash{$prefix.$name} = $obj->$name();
227       }
228       elsif( ref($name) eq 'ARRAY' ) {
229         # [ foo => sub { ... } ]
230         $hash{$prefix.($name->[0])} = $name->[1]->($obj);
231       }
232       else {
233         warn "bad msg_template substitution: '$name'\n";
234         #skip it?
235       } 
236     } 
237   } 
238   $_ = encode_entities($_) foreach values(%hash);
239
240
241   ###
242   # clean up template
243   ###
244   my $subject_tmpl = new Text::Template (
245     TYPE   => 'STRING',
246     SOURCE => $self->subject,
247   );
248   my $subject = $subject_tmpl->fill_in( HASH => \%hash );
249
250   my $body = $self->body;
251   my ($skin, $guts) = eviscerate($body);
252   @$guts = map { 
253     $_ = decode_entities($_); # turn all punctuation back into itself
254     s/\r//gs;           # remove \r's
255     s/<br[^>]*>/\n/gsi; # and <br /> tags
256     s/<p>/\n/gsi;       # and <p>
257     s/<\/p>//gsi;       # and </p>
258     s/\240/ /gs;        # and &nbsp;
259     $_
260   } @$guts;
261   
262   $body = '{ use Date::Format qw(time2str); "" }';
263   while(@$skin || @$guts) {
264     $body .= shift(@$skin) || '';
265     $body .= shift(@$guts) || '';
266   }
267
268   ###
269   # fill-in
270   ###
271
272   my $body_tmpl = new Text::Template (
273     TYPE          => 'STRING',
274     SOURCE        => $body,
275   );
276
277   $body = $body_tmpl->fill_in( HASH => \%hash );
278
279   ###
280   # and email
281   ###
282
283   my @to = ($opt{'to'}) || $cust_main->invoicing_list_emailonly;
284   warn "prepared msg_template with no email destination (custnum ".
285     $cust_main->custnum.")\n"
286     if !@to;
287
288   my $conf = new FS::Conf;
289
290   (
291     'from' => $self->from_addr || 
292               scalar( $conf->config('invoice_from', $cust_main->agentnum) ),
293     'to'   => \@to,
294     'bcc'  => $self->bcc_addr || undef,
295     'subject'   => $subject,
296     'html_body' => $body,
297     'text_body' => HTML::FormatText->new(leftmargin => 0, rightmargin => 70
298                     )->format( HTML::TreeBuilder->new_from_content($body) ),
299   );
300
301 }
302
303 =item send OPTION => VALUE
304
305 Fills in the template and sends it to the customer.  Options are as for 
306 'prepare'.
307
308 =cut
309
310 # broken out from prepare() in case we want to queue the sending,
311 # preview it, etc.
312 sub send {
313   my $self = shift;
314   send_email(generate_email($self->prepare(@_)));
315 }
316
317 # helper sub for package dates
318 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
319
320 # needed for some things
321 my $conf = new FS::Conf;
322
323 #return contexts and fill-in values
324 # If you add anything, be sure to add a description in 
325 # httemplate/edit/msg_template.html.
326 sub substitutions {
327   { 'cust_main' => [qw(
328       display_custnum agentnum agent_name
329
330       last first company
331       name name_short contact contact_firstlast
332       address1 address2 city county state zip
333       country
334       daytime night fax
335
336       has_ship_address
337       ship_last ship_first ship_company
338       ship_name ship_name_short ship_contact ship_contact_firstlast
339       ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
340       ship_country
341       ship_daytime ship_night ship_fax
342
343       paymask payname paytype payip
344       num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
345       classname categoryname
346       balance
347       credit_limit
348       invoicing_list_emailonly
349       cust_status ucfirst_cust_status cust_statuscolor
350
351       signupdate dundate
352       expdate
353       packages recurdates
354       ),
355       # expdate is a special case
356       [ signupdate_ymd    => sub { time2str('%Y-%m-%d', shift->signupdate) } ],
357       [ dundate_ymd       => sub { time2str('%Y-%m-%d', shift->dundate) } ],
358       [ paydate_my        => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
359       [ otaker_first      => sub { shift->access_user->first } ],
360       [ otaker_last       => sub { shift->access_user->last } ],
361       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
362       [ company_name      => sub { 
363           $conf->config('company_name', shift->agentnum) 
364         } ],
365       [ company_address   => sub {
366           $conf->config('company_address', shift->agentnum)
367         } ],
368     ],
369     # next_bill_date
370     'cust_pkg'  => [qw( 
371       pkgnum pkg pkg_label pkg_label_long
372       location_label
373       status statuscolor
374     
375       start_date setup bill last_bill 
376       adjourn susp expire 
377       labels_short
378       ),
379       [ cancel            => sub { shift->getfield('cancel') } ], # grrr...
380       [ start_ymd         => sub { $ymd->(shift->getfield('start_date')) } ],
381       [ setup_ymd         => sub { $ymd->(shift->getfield('setup')) } ],
382       [ next_bill_ymd     => sub { $ymd->(shift->getfield('bill')) } ],
383       [ last_bill_ymd     => sub { $ymd->(shift->getfield('last_bill')) } ],
384       [ adjourn_ymd       => sub { $ymd->(shift->getfield('adjourn')) } ],
385       [ susp_ymd          => sub { $ymd->(shift->getfield('susp')) } ],
386       [ expire_ymd        => sub { $ymd->(shift->getfield('expire')) } ],
387       [ cancel_ymd        => sub { $ymd->(shift->getfield('cancel')) } ],
388     ],
389     'cust_bill' => [qw(
390       invnum
391       _date
392     )],
393     #XXX not really thinking about cust_bill substitutions quite yet
394     
395     # for welcome and limit warning messages
396     'svc_acct' => [qw(
397       svcnum
398       username
399       domain
400       ),
401       [ password          => sub { shift->getfield('_password') } ],
402     ],
403     # for payment receipts
404     'cust_pay' => [qw(
405       paynum
406       _date
407       ),
408       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
409       # overrides the one in cust_main in cases where a cust_pay is passed
410       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
411       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
412       [ payinfo           => sub { 
413           my $cust_pay = shift;
414           ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
415             $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
416         } ],
417     ],
418     # for payment decline messages
419     # try to support all cust_pay fields
420     # 'error' is a special case, it contains the raw error from the gateway
421     'cust_pay_pending' => [qw(
422       _date
423       error
424       ),
425       [ paid              => sub { sprintf("%.2f", shift->paid) } ],
426       [ payby             => sub { FS::payby->shortname(shift->payby) } ],
427       [ date              => sub { time2str("%a %B %o, %Y", shift->_date) } ],
428       [ payinfo           => sub {
429           my $pending = shift;
430           ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
431             $pending->paymask : $pending->decrypt($pending->payinfo)
432         } ],
433     ],
434   };
435 }
436
437 sub _upgrade_data {
438   my ($self, %opts) = @_;
439
440   my @fixes = (
441     [ 'alerter_msgnum',  'alerter_template',   '',               '', '' ],
442     [ 'cancel_msgnum',   'cancelmessage',      'cancelsubject',  '', '' ],
443     [ 'decline_msgnum',  'declinetemplate',    '',               '', '' ],
444     [ 'impending_recur_msgnum', 'impending_recur_template', '',  '', 'impending_recur_bcc' ],
445     [ 'payment_receipt_msgnum', 'payment_receipt_email', '',     '', '' ],
446     [ 'welcome_msgnum',  'welcome_email',      'welcome_email-subject', 'welcome_email-from', '' ],
447     [ 'warning_msgnum',  'warning_email',      'warning_email-subject', 'warning_email-from', '' ],
448   );
449  
450   my $conf = new FS::Conf;
451   my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
452   foreach my $agentnum (@agentnums) {
453     foreach (@fixes) {
454       my ($newname, $oldname, $subject, $from, $bcc) = @$_;
455       if ($conf->exists($oldname, $agentnum)) {
456         my $new = new FS::msg_template({
457            'msgname'   => $oldname,
458            'agentnum'  => $agentnum,
459            'from_addr' => ($from && $conf->config($from, $agentnum)) || 
460                           $conf->config('invoice_from', $agentnum),
461            'bcc_addr'  => ($bcc && $conf->config($from, $agentnum)) || '',
462            'subject'   => ($subject && $conf->config($subject, $agentnum)) || '',
463            'mime_type' => 'text/html',
464            'body'      => join('<BR>',$conf->config($oldname, $agentnum)),
465         });
466         my $error = $new->insert;
467         die $error if $error;
468         $conf->set($newname, $new->msgnum, $agentnum);
469         $conf->delete($oldname, $agentnum);
470         $conf->delete($from, $agentnum) if $from;
471         $conf->delete($subject, $agentnum) if $subject;
472       }
473     }
474   }
475 }
476
477 sub eviscerate {
478   # Every bit as pleasant as it sounds.
479   #
480   # We do this because Text::Template::Preprocess doesn't
481   # actually work.  It runs the entire template through 
482   # the preprocessor, instead of the code segments.  Which 
483   # is a shame, because Text::Template already contains
484   # the code to do this operation.
485   my $body = shift;
486   my (@outside, @inside);
487   my $depth = 0;
488   my $chunk = '';
489   while($body || $chunk) {
490     my ($first, $delim, $rest);
491     # put all leading non-delimiters into $first
492     ($first, $rest) =
493         ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
494     $chunk .= $first;
495     # put a leading delimiter into $delim if there is one
496     ($delim, $rest) =
497       ($rest =~ /^([{}]?)(.*)$/s);
498
499     if( $delim eq '{' ) {
500       $chunk .= '{';
501       if( $depth == 0 ) {
502         push @outside, $chunk;
503         $chunk = '';
504       }
505       $depth++;
506     }
507     elsif( $delim eq '}' ) {
508       $depth--;
509       if( $depth == 0 ) {
510         push @inside, $chunk;
511         $chunk = '';
512       }
513       $chunk .= '}';
514     }
515     else {
516       # no more delimiters
517       if( $depth == 0 ) {
518         push @outside, $chunk . $rest;
519       } # else ? something wrong
520       last;
521     }
522     $body = $rest;
523   }
524   (\@outside, \@inside);
525 }
526
527 =back
528
529 =head1 BUGS
530
531 =head1 SEE ALSO
532
533 L<FS::Record>, schema.html from the base documentation.
534
535 =cut
536
537 1;
538