1 package FS::msg_template;
4 use base qw( FS::Record );
6 use FS::Misc qw( generate_email send_email );
8 use FS::Record qw( qsearch qsearchs );
13 use Date::Format qw( time2str );
14 use HTML::Entities qw( decode_entities encode_entities ) ;
16 use HTML::TreeBuilder;
17 use vars qw( $DEBUG $conf );
19 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
25 FS::msg_template - Object methods for msg_template records
31 $record = new FS::msg_template \%hash;
32 $record = new FS::msg_template { 'column' => 'value' };
34 $error = $record->insert;
36 $error = $new_record->replace($old_record);
38 $error = $record->delete;
40 $error = $record->check;
44 An FS::msg_template object represents a customer message template.
45 FS::msg_template inherits from FS::Record. The following fields are currently
60 Agent associated with this template. Can be NULL for a global template.
64 MIME type. Defaults to text/html.
72 The message subject line, in L<Text::Template> format.
76 The message body, as plain text or HTML, in L<Text::Template> format.
90 Creates a new template. To add the template to the database, see L<"insert">.
92 Note that this stores the hash reference, not a distinct copy of the hash it
93 points to. You can ask the object for a copy with the I<hash> method.
97 # the new method can be inherited from FS::Record, if a table method is defined
99 sub table { 'msg_template'; }
103 Adds this record to the database. If there is an error, returns the error,
104 otherwise returns false.
108 # the insert method can be inherited from FS::Record
112 Delete this record from the database.
116 # the delete method can be inherited from FS::Record
118 =item replace OLD_RECORD
120 Replaces the OLD_RECORD with this one in the database. If there is an error,
121 returns the error, otherwise returns false.
125 # the replace method can be inherited from FS::Record
129 Checks all fields to make sure this is a valid template. If there is
130 an error, returns the error, otherwise returns false. Called by the insert
135 # the check method should currently be supplied - FS::Record contains some
136 # data checking routines
142 $self->ut_numbern('msgnum')
143 || $self->ut_text('msgname')
144 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
145 || $self->ut_textn('mime_type')
146 || $self->ut_anything('subject')
147 || $self->ut_anything('body')
148 || $self->ut_enum('disabled', [ '', 'Y' ] )
149 || $self->ut_textn('from_addr')
151 return $error if $error;
153 $self->mime_type('text/html') unless $self->mime_type;
158 =item prepare OPTION => VALUE
160 Fills in the template and returns a hash of the 'from' address, 'to'
161 addresses, subject line, and body.
163 Options are passed as a list of name/value pairs:
169 Customer object (required).
173 Additional context object (currently, can be a cust_main, cust_pkg,
174 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
175 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
176 used for substitution.
178 As a special case, this may be an arrayref of two objects. Both
179 objects will be available for substitution, with their field names
180 prefixed with 'new_' and 'old_' respectively. This is used in the
181 rt_ticket export when exporting "replace" events.
185 Configuration option to use as the source address, based on the customer's
186 agentnum. If unspecified (or the named option is empty), 'invoice_from'
189 The I<from_addr> field in the template takes precedence over this.
193 Destination address. The default is to use the customer's
194 invoicing_list addresses. Multiple addresses may be comma-separated.
201 my( $self, %opt ) = @_;
203 my $cust_main = $opt{'cust_main'};
204 my $object = $opt{'object'};
205 warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
208 my $subs = $self->substitutions;
211 # create substitution table
214 my @objects = ($cust_main);
218 if( ref($object) eq 'ARRAY' ) {
219 # [new, old], for provisioning tickets
220 push @objects, $object->[0], $object->[1];
221 push @prefixes, 'new_', 'old_';
222 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
225 push @objects, $object;
227 $svc = $object if $object->isa('FS::svc_Common');
231 push @objects, $svc->cust_svc->cust_pkg;
235 foreach my $obj (@objects) {
236 my $prefix = shift @prefixes;
237 foreach my $name (@{ $subs->{$obj->table} }) {
240 $hash{$prefix.$name} = $obj->$name();
242 elsif( ref($name) eq 'ARRAY' ) {
243 # [ foo => sub { ... } ]
244 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
247 warn "bad msg_template substitution: '$name'\n";
252 $_ = encode_entities($_ || '') foreach values(%hash);
258 my $subject_tmpl = new Text::Template (
260 SOURCE => $self->subject,
262 my $subject = $subject_tmpl->fill_in( HASH => \%hash );
264 my $body = $self->body;
265 my ($skin, $guts) = eviscerate($body);
267 $_ = decode_entities($_); # turn all punctuation back into itself
268 s/\r//gs; # remove \r's
269 s/<br[^>]*>/\n/gsi; # and <br /> tags
270 s/<p>/\n/gsi; # and <p>
271 s/<\/p>//gsi; # and </p>
272 s/\240/ /gs; # and
276 $body = '{ use Date::Format qw(time2str); "" }';
277 while(@$skin || @$guts) {
278 $body .= shift(@$skin) || '';
279 $body .= shift(@$guts) || '';
286 my $body_tmpl = new Text::Template (
291 $body = $body_tmpl->fill_in( HASH => \%hash );
298 if ( exists($opt{'to'}) ) {
299 @to = split(/\s*,\s*/, $opt{'to'});
302 @to = $cust_main->invoicing_list_emailonly;
304 # no warning when preparing with no destination
306 my $from_addr = $self->from_addr;
309 if ( $opt{'from_config'} ) {
310 $from_addr = scalar( $conf->config($opt{'from_config'},
311 $cust_main->agentnum) );
313 $from_addr ||= scalar( $conf->config('invoice_from',
314 $cust_main->agentnum) );
317 # if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
318 # my $cust_msg = FS::cust_msg->new({
319 # 'custnum' => $cust_main->custnum,
320 # 'msgnum' => $self->msgnum,
321 # 'status' => 'prepared',
324 # @cust_msg = ('cust_msg' => $cust_msg);
328 'custnum' => $cust_main->custnum,
329 'msgnum' => $self->msgnum,
330 'from' => $from_addr,
332 'bcc' => $self->bcc_addr || undef,
333 'subject' => $subject,
334 'html_body' => $body,
335 'text_body' => HTML::FormatText->new(leftmargin => 0, rightmargin => 70
336 )->format( HTML::TreeBuilder->new_from_content($body) ),
341 =item send OPTION => VALUE
343 Fills in the template and sends it to the customer. Options are as for
348 # broken out from prepare() in case we want to queue the sending,
352 send_email(generate_email($self->prepare(@_)));
355 # helper sub for package dates
356 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
358 #my $conf = new FS::Conf;
360 #return contexts and fill-in values
361 # If you add anything, be sure to add a description in
362 # httemplate/edit/msg_template.html.
364 { 'cust_main' => [qw(
365 display_custnum agentnum agent_name
368 name name_short contact contact_firstlast
369 address1 address2 city county state zip
374 ship_last ship_first ship_company
375 ship_name ship_name_short ship_contact ship_contact_firstlast
376 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
378 ship_daytime ship_night ship_fax
380 paymask payname paytype payip
381 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
382 classname categoryname
385 invoicing_list_emailonly
386 cust_status ucfirst_cust_status cust_statuscolor
391 [ expdate => sub { shift->paydate_epoch } ], #compatibility
392 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
393 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
394 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
395 [ otaker_first => sub { shift->access_user->first } ],
396 [ otaker_last => sub { shift->access_user->last } ],
397 [ payby => sub { FS::payby->shortname(shift->payby) } ],
398 [ company_name => sub {
399 $conf->config('company_name', shift->agentnum)
401 [ company_address => sub {
402 $conf->config('company_address', shift->agentnum)
404 [ company_phonenum => sub {
405 $conf->config('company_phonenum', shift->agentnum)
410 pkgnum pkg_label pkg_label_long
414 start_date setup bill last_bill
418 [ pkg => sub { shift->part_pkg->pkg } ],
419 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
420 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
421 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
422 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
423 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
424 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
425 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
426 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
427 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
433 #XXX not really thinking about cust_bill substitutions quite yet
435 # for welcome and limit warning messages
441 [ password => sub { shift->getfield('_password') } ],
448 my $registrar = qsearchs('registrar',
449 { registrarnum => shift->registrarnum} );
450 $registrar ? $registrar->registrarname : ''
454 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
455 $svc_acct ? $svc_acct->email : ''
466 'svc_broadband' => [qw(
474 # for payment receipts
479 [ paid => sub { sprintf("%.2f", shift->paid) } ],
480 # overrides the one in cust_main in cases where a cust_pay is passed
481 [ payby => sub { FS::payby->shortname(shift->payby) } ],
482 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
484 my $cust_pay = shift;
485 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
486 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
489 # for payment decline messages
490 # try to support all cust_pay fields
491 # 'error' is a special case, it contains the raw error from the gateway
492 'cust_pay_pending' => [qw(
496 [ paid => sub { sprintf("%.2f", shift->paid) } ],
497 [ payby => sub { FS::payby->shortname(shift->payby) } ],
498 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
501 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
502 $pending->paymask : $pending->decrypt($pending->payinfo)
509 my ($self, %opts) = @_;
512 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
513 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
514 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
515 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
516 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
517 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
518 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
521 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
522 foreach my $agentnum (@agentnums) {
524 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
525 if ($conf->exists($oldname, $agentnum)) {
526 my $new = new FS::msg_template({
527 'msgname' => $oldname,
528 'agentnum' => $agentnum,
529 'from_addr' => ($from && $conf->config($from, $agentnum)) ||
530 $conf->config('invoice_from', $agentnum),
531 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
532 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
533 'mime_type' => 'text/html',
534 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
536 my $error = $new->insert;
537 die $error if $error;
538 $conf->set($newname, $new->msgnum, $agentnum);
539 $conf->delete($oldname, $agentnum);
540 $conf->delete($from, $agentnum) if $from;
541 $conf->delete($subject, $agentnum) if $subject;
548 # Every bit as pleasant as it sounds.
550 # We do this because Text::Template::Preprocess doesn't
551 # actually work. It runs the entire template through
552 # the preprocessor, instead of the code segments. Which
553 # is a shame, because Text::Template already contains
554 # the code to do this operation.
556 my (@outside, @inside);
559 while($body || $chunk) {
560 my ($first, $delim, $rest);
561 # put all leading non-delimiters into $first
563 ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
565 # put a leading delimiter into $delim if there is one
567 ($rest =~ /^([{}]?)(.*)$/s);
569 if( $delim eq '{' ) {
572 push @outside, $chunk;
577 elsif( $delim eq '}' ) {
580 push @inside, $chunk;
588 push @outside, $chunk . $rest;
589 } # else ? something wrong
594 (\@outside, \@inside);
603 L<FS::Record>, schema.html from the base documentation.