1 package FS::msg_template;
2 use base qw( FS::Record );
5 use vars qw( $DEBUG $conf );
7 use Date::Format qw( time2str );
12 use HTML::Entities qw( decode_entities encode_entities ) ;
14 use HTML::TreeBuilder;
17 use FS::Misc qw( generate_email send_email do_print );
19 use FS::Record qw( qsearch qsearchs );
20 use FS::UID qw( dbh );
24 use FS::template_content;
26 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
32 FS::msg_template - Object methods for msg_template records
38 $record = new FS::msg_template \%hash;
39 $record = new FS::msg_template { 'column' => 'value' };
41 $error = $record->insert;
43 $error = $new_record->replace($old_record);
45 $error = $record->delete;
47 $error = $record->check;
51 An FS::msg_template object represents a customer message template.
52 FS::msg_template inherits from FS::Record. The following fields are currently
57 =item msgnum - primary key
59 =item msgname - Name of the template. This will appear in the user interface;
60 if it needs to be localized for some users, add it to the message catalog.
62 =item agentnum - Agent associated with this template. Can be NULL for a
65 =item mime_type - MIME type. Defaults to text/html.
67 =item from_addr - Source email address.
69 =item disabled - disabled ('Y' or NULL).
79 Creates a new template. To add the template to the database, see L<"insert">.
81 Note that this stores the hash reference, not a distinct copy of the hash it
82 points to. You can ask the object for a copy with the I<hash> method.
86 # the new method can be inherited from FS::Record, if a table method is defined
88 sub table { 'msg_template'; }
90 =item insert [ CONTENT ]
92 Adds this record to the database. If there is an error, returns the error,
93 otherwise returns false.
95 A default (no locale) L<FS::template_content> object will be created. CONTENT
96 is an optional hash containing 'subject' and 'body' for this object.
104 my $oldAutoCommit = $FS::UID::AutoCommit;
105 local $FS::UID::AutoCommit = 0;
108 my $error = $self->SUPER::insert;
110 $content{'msgnum'} = $self->msgnum;
111 $content{'subject'} ||= '';
112 $content{'body'} ||= '';
113 my $template_content = new FS::template_content (\%content);
114 $error = $template_content->insert;
118 $dbh->rollback if $oldAutoCommit;
122 $dbh->commit if $oldAutoCommit;
128 Delete this record from the database.
132 # the delete method can be inherited from FS::Record
134 =item replace [ OLD_RECORD ] [ CONTENT ]
136 Replaces the OLD_RECORD with this one in the database. If there is an error,
137 returns the error, otherwise returns false.
139 CONTENT is an optional hash containing 'subject', 'body', and 'locale'. If
140 supplied, an L<FS::template_content> object will be created (or modified, if
141 one already exists for this locale).
147 my $old = ( ref($_[0]) and $_[0]->isa('FS::Record') )
149 : $self->replace_old;
152 my $oldAutoCommit = $FS::UID::AutoCommit;
153 local $FS::UID::AutoCommit = 0;
156 my $error = $self->SUPER::replace($old);
158 if ( !$error and %content ) {
159 $content{'locale'} ||= '';
160 my $new_content = qsearchs('template_content', {
161 'msgnum' => $self->msgnum,
162 'locale' => $content{'locale'},
164 if ( $new_content ) {
165 $new_content->subject($content{'subject'});
166 $new_content->body($content{'body'});
167 $error = $new_content->replace;
170 $content{'msgnum'} = $self->msgnum;
171 $new_content = new FS::template_content \%content;
172 $error = $new_content->insert;
177 $dbh->rollback if $oldAutoCommit;
181 warn "committing FS::msg_template->replace\n" if $DEBUG and $oldAutoCommit;
182 $dbh->commit if $oldAutoCommit;
190 Checks all fields to make sure this is a valid template. If there is
191 an error, returns the error, otherwise returns false. Called by the insert
196 # the check method should currently be supplied - FS::Record contains some
197 # data checking routines
203 $self->ut_numbern('msgnum')
204 || $self->ut_text('msgname')
205 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
206 || $self->ut_textn('mime_type')
207 || $self->ut_enum('disabled', [ '', 'Y' ] )
208 || $self->ut_textn('from_addr')
210 return $error if $error;
212 $self->mime_type('text/html') unless $self->mime_type;
217 =item content_locales
219 Returns a hashref of the L<FS::template_content> objects attached to
220 this template, with the locale as key.
224 sub content_locales {
226 return $self->{'_content_locales'} ||= +{
227 map { $_->locale , $_ }
228 qsearch('template_content', { 'msgnum' => $self->msgnum })
232 =item prepare OPTION => VALUE
234 Fills in the template and returns a hash of the 'from' address, 'to'
235 addresses, subject line, and body.
237 Options are passed as a list of name/value pairs:
243 Customer object (required).
247 Additional context object (currently, can be a cust_main, cust_pkg,
248 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
249 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
250 used for substitution.
252 As a special case, this may be an arrayref of two objects. Both
253 objects will be available for substitution, with their field names
254 prefixed with 'new_' and 'old_' respectively. This is used in the
255 rt_ticket export when exporting "replace" events.
259 Configuration option to use as the source address, based on the customer's
260 agentnum. If unspecified (or the named option is empty), 'invoice_from'
263 The I<from_addr> field in the template takes precedence over this.
267 Destination address. The default is to use the customer's
268 invoicing_list addresses. Multiple addresses may be comma-separated.
272 A hash reference of additional substitutions
279 my( $self, %opt ) = @_;
281 my $cust_main = $opt{'cust_main'} or die 'cust_main required';
282 my $object = $opt{'object'} or die 'object required';
285 my $locale = $cust_main->locale || '';
286 warn "no locale for cust#".$cust_main->custnum."; using default content\n"
287 if $DEBUG and !$locale;
288 my $content = $self->content($cust_main->locale);
289 warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
292 my $subs = $self->substitutions;
295 # create substitution table
298 my @objects = ($cust_main);
302 if( ref($object) eq 'ARRAY' ) {
303 # [new, old], for provisioning tickets
304 push @objects, $object->[0], $object->[1];
305 push @prefixes, 'new_', 'old_';
306 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
309 push @objects, $object;
311 $svc = $object if $object->isa('FS::svc_Common');
315 push @objects, $svc->cust_svc->cust_pkg;
319 foreach my $obj (@objects) {
320 my $prefix = shift @prefixes;
321 foreach my $name (@{ $subs->{$obj->table} }) {
324 $hash{$prefix.$name} = $obj->$name();
326 elsif( ref($name) eq 'ARRAY' ) {
327 # [ foo => sub { ... } ]
328 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
331 warn "bad msg_template substitution: '$name'\n";
337 if ( $opt{substitutions} ) {
338 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
341 $_ = encode_entities($_ || '') foreach values(%hash);
346 my $subject_tmpl = new Text::Template (
348 SOURCE => $content->subject,
350 my $subject = $subject_tmpl->fill_in( HASH => \%hash );
352 my $body = $content->body;
353 my ($skin, $guts) = eviscerate($body);
355 $_ = decode_entities($_); # turn all punctuation back into itself
356 s/\r//gs; # remove \r's
357 s/<br[^>]*>/\n/gsi; # and <br /> tags
358 s/<p>/\n/gsi; # and <p>
359 s/<\/p>//gsi; # and </p>
360 s/\240/ /gs; # and
364 $body = '{ use Date::Format qw(time2str); "" }';
365 while(@$skin || @$guts) {
366 $body .= shift(@$skin) || '';
367 $body .= shift(@$guts) || '';
374 my $body_tmpl = new Text::Template (
379 $body = $body_tmpl->fill_in( HASH => \%hash );
386 if ( exists($opt{'to'}) ) {
387 @to = split(/\s*,\s*/, $opt{'to'});
390 @to = $cust_main->invoicing_list_emailonly;
392 # no warning when preparing with no destination
394 my $from_addr = $self->from_addr;
397 if ( $opt{'from_config'} ) {
398 $from_addr = scalar( $conf->config($opt{'from_config'},
399 $cust_main->agentnum) );
401 $from_addr ||= scalar( $conf->config('invoice_from',
402 $cust_main->agentnum) );
405 # if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
406 # my $cust_msg = FS::cust_msg->new({
407 # 'custnum' => $cust_main->custnum,
408 # 'msgnum' => $self->msgnum,
409 # 'status' => 'prepared',
412 # @cust_msg = ('cust_msg' => $cust_msg);
415 my $text_body = encode('UTF-8',
416 HTML::FormatText->new(leftmargin => 0, rightmargin => 70)
417 ->format( HTML::TreeBuilder->new_from_content($body) )
420 'custnum' => $cust_main->custnum,
421 'msgnum' => $self->msgnum,
422 'from' => $from_addr,
424 'bcc' => $self->bcc_addr || undef,
425 'subject' => $subject,
426 'html_body' => $body,
427 'text_body' => $text_body
432 =item send OPTION => VALUE
434 Fills in the template and sends it to the customer. Options are as for
439 # broken out from prepare() in case we want to queue the sending,
443 send_email(generate_email($self->prepare(@_)));
446 =item render OPTION => VALUE ...
448 Fills in the template and renders it to a PDF document. Returns the
449 name of the PDF file.
451 Options are as for 'prepare', but 'from' and 'to' are meaningless.
455 # will also have options to set paper size, margins, etc.
459 eval "use PDF::WebKit";
462 my %hash = $self->prepare(%opt);
463 my $html = $hash{'html_body'};
465 # Graphics/stylesheets should probably go in /var/www on the Freeside
467 my $kit = PDF::WebKit->new(\$html); #%options
468 # hack to use our wrapper script
469 $kit->configure(sub { shift->wkhtmltopdf('freeside-wkhtmltopdf') });
476 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
481 my( $self, %opt ) = @_;
482 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
485 # helper sub for package dates
486 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
488 # helper sub for money amounts
489 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
491 # helper sub for usage-related messages
492 my $usage_warning = sub {
494 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
495 my $amount = $svc->$col; next if $amount eq '';
496 my $method = $col.'_threshold';
497 my $threshold = $svc->$method; next if $threshold eq '';
498 return [$col, $amount, $threshold] if $amount <= $threshold;
499 # this only returns the first one that's below threshold, if there are
505 #my $conf = new FS::Conf;
507 #return contexts and fill-in values
508 # If you add anything, be sure to add a description in
509 # httemplate/edit/msg_template.html.
511 { 'cust_main' => [qw(
512 display_custnum agentnum agent_name
515 name name_short contact contact_firstlast
516 address1 address2 city county state zip
518 daytime night mobile fax
521 ship_name ship_name_short ship_contact ship_contact_firstlast
522 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
525 paymask payname paytype payip
526 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
527 classname categoryname
530 invoicing_list_emailonly
531 cust_status ucfirst_cust_status cust_statuscolor
536 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
537 #compatibility: obsolete ship_ fields - use the non-ship versions
540 [ "ship_$field" => sub { shift->$field } ]
542 qw( last first company daytime night fax )
544 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
546 [ expdate => sub { shift->paydate_epoch } ], #compatibility
547 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
548 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
549 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
550 [ otaker_first => sub { shift->access_user->first } ],
551 [ otaker_last => sub { shift->access_user->last } ],
552 [ payby => sub { FS::payby->shortname(shift->payby) } ],
553 [ company_name => sub {
554 $conf->config('company_name', shift->agentnum)
556 [ company_address => sub {
557 $conf->config('company_address', shift->agentnum)
559 [ company_phonenum => sub {
560 $conf->config('company_phonenum', shift->agentnum)
562 [ selfservice_server_base_url => sub {
563 $conf->config('selfservice_server-base_url') #, shift->agentnum)
568 pkgnum pkg_label pkg_label_long
572 start_date setup bill last_bill
576 [ pkg => sub { shift->part_pkg->pkg } ],
577 [ pkg_category => sub { shift->part_pkg->categoryname } ],
578 [ pkg_class => sub { shift->part_pkg->classname } ],
579 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
580 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
581 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
582 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
583 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
584 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
585 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
586 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
587 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
589 # not necessarily correct for non-flat packages
590 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
591 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
593 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
600 #XXX not really thinking about cust_bill substitutions quite yet
602 # for welcome and limit warning messages
608 [ password => sub { shift->getfield('_password') } ],
609 [ column => sub { &$usage_warning(shift)->[0] } ],
610 [ amount => sub { &$usage_warning(shift)->[1] } ],
611 [ threshold => sub { &$usage_warning(shift)->[2] } ],
618 my $registrar = qsearchs('registrar',
619 { registrarnum => shift->registrarnum} );
620 $registrar ? $registrar->registrarname : ''
624 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
625 $svc_acct ? $svc_acct->email : ''
636 'svc_broadband' => [qw(
644 # for payment receipts
649 [ paid => sub { sprintf("%.2f", shift->paid) } ],
650 # overrides the one in cust_main in cases where a cust_pay is passed
651 [ payby => sub { FS::payby->shortname(shift->payby) } ],
652 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
654 my $cust_pay = shift;
655 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
656 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
659 # for payment decline messages
660 # try to support all cust_pay fields
661 # 'error' is a special case, it contains the raw error from the gateway
662 'cust_pay_pending' => [qw(
666 [ paid => sub { sprintf("%.2f", shift->paid) } ],
667 [ payby => sub { FS::payby->shortname(shift->payby) } ],
668 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
671 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
672 $pending->paymask : $pending->decrypt($pending->payinfo)
680 Returns the L<FS::template_content> object appropriate to LOCALE, if there
681 is one. If not, returns the one with a NULL locale.
688 qsearchs('template_content',
689 { 'msgnum' => $self->msgnum, 'locale' => $locale }) ||
690 qsearchs('template_content',
691 { 'msgnum' => $self->msgnum, 'locale' => '' });
696 Returns the L<FS::agent> object for this template.
701 my ($self, %opts) = @_;
704 # First move any historical templates in config to real message templates
708 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
709 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
710 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
711 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
712 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
713 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
714 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
717 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
718 foreach my $agentnum (@agentnums) {
720 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
721 if ($conf->exists($oldname, $agentnum)) {
722 my $new = new FS::msg_template({
723 'msgname' => $oldname,
724 'agentnum' => $agentnum,
725 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
726 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
727 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
728 'mime_type' => 'text/html',
729 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
731 my $error = $new->insert;
732 die $error if $error;
733 $conf->set($newname, $new->msgnum, $agentnum);
734 $conf->delete($oldname, $agentnum);
735 $conf->delete($from, $agentnum) if $from;
736 $conf->delete($subject, $agentnum) if $subject;
740 if ( $conf->exists('alert_expiration', $agentnum) ) {
741 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
742 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
744 warn "template for alerter_msgnum $msgnum not found\n";
747 # this is now a set of billing events
748 foreach my $days (30, 15, 5) {
749 my $event = FS::part_event->new({
750 'agentnum' => $agentnum,
751 'event' => "Card expiration warning - $days days",
752 'eventtable' => 'cust_main',
753 'check_freq' => '1d',
754 'action' => 'notice',
755 'disabled' => 'Y', #initialize first
757 my $error = $event->insert( 'msgnum' => $msgnum );
759 warn "error creating expiration alert event:\n$error\n\n";
762 # make it work like before:
763 # only send each warning once before the card expires,
764 # only warn active customers,
765 # only warn customers with CARD/DCRD,
766 # only warn customers who get email invoices
768 'once_every' => { 'run_delay' => '30d' },
769 'cust_paydate_within' => { 'within' => $days.'d' },
770 'cust_status' => { 'status' => { 'active' => 1 } },
771 'payby' => { 'payby' => { 'CARD' => 1,
774 'message_email' => {},
776 foreach (keys %conds) {
777 my $condition = FS::part_event_condition->new({
778 'conditionname' => $_,
779 'eventpart' => $event->eventpart,
781 $error = $condition->insert( %{ $conds{$_} });
783 warn "error creating expiration alert event:\n$error\n\n";
787 $error = $event->initialize;
789 warn "expiration alert event was created, but not initialized:\n$error\n\n";
792 $conf->delete('alerter_msgnum', $agentnum);
793 $conf->delete('alert_expiration', $agentnum);
795 } # if alerter_msgnum
800 # Move subject and body from msg_template to template_content
803 foreach my $msg_template ( qsearch('msg_template', {}) ) {
804 if ( $msg_template->subject || $msg_template->body ) {
805 # create new default content
807 $content{subject} = $msg_template->subject;
808 $msg_template->set('subject', '');
810 # work around obscure Pg/DBD bug
811 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
812 # (though the right fix is to upgrade DBD)
813 my $body = $msg_template->body;
814 if ( $body =~ /^x([0-9a-f]+)$/ ) {
815 # there should be no real message templates that look like that
816 warn "converting template body to TEXT\n";
817 $body = pack('H*', $1);
819 $content{body} = $body;
820 $msg_template->set('body', '');
822 my $error = $msg_template->replace(%content);
823 die $error if $error;
828 # Add new-style default templates if missing
830 $self->_populate_initial_data;
834 sub _populate_initial_data { #class method
835 #my($class, %opts) = @_;
838 eval "use FS::msg_template::InitialData;";
841 my $initial_data = FS::msg_template::InitialData->_initial_data;
843 foreach my $hash ( @$initial_data ) {
845 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
847 my $msg_template = new FS::msg_template($hash);
848 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
849 die $error if $error;
851 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
858 # Every bit as pleasant as it sounds.
860 # We do this because Text::Template::Preprocess doesn't
861 # actually work. It runs the entire template through
862 # the preprocessor, instead of the code segments. Which
863 # is a shame, because Text::Template already contains
864 # the code to do this operation.
866 my (@outside, @inside);
869 while($body || $chunk) {
870 my ($first, $delim, $rest);
871 # put all leading non-delimiters into $first
873 ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
875 # put a leading delimiter into $delim if there is one
877 ($rest =~ /^([{}]?)(.*)$/s);
879 if( $delim eq '{' ) {
882 push @outside, $chunk;
887 elsif( $delim eq '}' ) {
890 push @inside, $chunk;
898 push @outside, $chunk . $rest;
899 } # else ? something wrong
904 (\@outside, \@inside);
913 L<FS::Record>, schema.html from the base documentation.