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