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 && $cust_main->locale || '';
286 warn "no locale for cust#".$cust_main->custnum."; using default content\n"
287 if $DEBUG and $cust_main && !$locale;
288 my $content = $self->content($locale);
290 warn "preparing template '".$self->msgname."\n"
293 my $subs = $self->substitutions;
296 # create substitution table
300 push @objects, $cust_main if $cust_main;
304 if( ref($object) eq 'ARRAY' ) {
305 # [new, old], for provisioning tickets
306 push @objects, $object->[0], $object->[1];
307 push @prefixes, 'new_', 'old_';
308 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
311 push @objects, $object;
313 $svc = $object if $object->isa('FS::svc_Common');
317 push @objects, $svc->cust_svc->cust_pkg;
321 foreach my $obj (@objects) {
322 my $prefix = shift @prefixes;
323 foreach my $name (@{ $subs->{$obj->table} }) {
326 $hash{$prefix.$name} = $obj->$name();
328 elsif( ref($name) eq 'ARRAY' ) {
329 # [ foo => sub { ... } ]
330 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
333 warn "bad msg_template substitution: '$name'\n";
339 if ( $opt{substitutions} ) {
340 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
343 $_ = encode_entities($_ || '') foreach values(%hash);
348 my $subject_tmpl = new Text::Template (
350 SOURCE => $content->subject,
352 my $subject = $subject_tmpl->fill_in( HASH => \%hash );
354 my $body = $content->body;
355 my ($skin, $guts) = eviscerate($body);
357 $_ = decode_entities($_); # turn all punctuation back into itself
358 s/\r//gs; # remove \r's
359 s/<br[^>]*>/\n/gsi; # and <br /> tags
360 s/<p>/\n/gsi; # and <p>
361 s/<\/p>//gsi; # and </p>
362 s/\240/ /gs; # and
366 $body = '{ use Date::Format qw(time2str); "" }';
367 while(@$skin || @$guts) {
368 $body .= shift(@$skin) || '';
369 $body .= shift(@$guts) || '';
376 my $body_tmpl = new Text::Template (
381 $body = $body_tmpl->fill_in( HASH => \%hash );
388 if ( exists($opt{'to'}) ) {
389 @to = split(/\s*,\s*/, $opt{'to'});
390 } elsif ( $cust_main ) {
391 @to = $cust_main->invoicing_list_emailonly;
393 die 'no To: address or cust_main object specified';
396 my $from_addr = $self->from_addr;
400 my $agentnum = $cust_main ? $cust_main->agentnum : '';
402 if ( $opt{'from_config'} ) {
403 $from_addr = $conf->config($opt{'from_config'}, $agentnum);
405 $from_addr ||= $conf->invoice_from_full($agentnum);
408 # if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
409 # my $cust_msg = FS::cust_msg->new({
410 # 'custnum' => $cust_main->custnum,
411 # 'msgnum' => $self->msgnum,
412 # 'status' => 'prepared',
415 # @cust_msg = ('cust_msg' => $cust_msg);
418 my $text_body = encode('UTF-8',
419 HTML::FormatText->new(leftmargin => 0, rightmargin => 70)
420 ->format( HTML::TreeBuilder->new_from_content($body) )
423 'custnum' => ( $cust_main ? $cust_main->custnum : ''),
424 'msgnum' => $self->msgnum,
425 'from' => $from_addr,
427 'bcc' => $self->bcc_addr || undef,
428 'subject' => $subject,
429 'html_body' => $body,
430 'text_body' => $text_body
435 =item send OPTION => VALUE
437 Fills in the template and sends it to the customer. Options are as for
442 # broken out from prepare() in case we want to queue the sending,
446 send_email(generate_email($self->prepare(@_)));
449 =item render OPTION => VALUE ...
451 Fills in the template and renders it to a PDF document. Returns the
452 name of the PDF file.
454 Options are as for 'prepare', but 'from' and 'to' are meaningless.
458 # will also have options to set paper size, margins, etc.
462 eval "use PDF::WebKit";
465 my %hash = $self->prepare(%opt);
466 my $html = $hash{'html_body'};
468 # Graphics/stylesheets should probably go in /var/www on the Freeside
470 my $kit = PDF::WebKit->new(\$html); #%options
471 # hack to use our wrapper script
472 $kit->configure(sub { shift->wkhtmltopdf('freeside-wkhtmltopdf') });
479 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
484 my( $self, %opt ) = @_;
485 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
488 # helper sub for package dates
489 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
491 # helper sub for money amounts
492 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
494 # helper sub for usage-related messages
495 my $usage_warning = sub {
497 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
498 my $amount = $svc->$col; next if $amount eq '';
499 my $method = $col.'_threshold';
500 my $threshold = $svc->$method; next if $threshold eq '';
501 return [$col, $amount, $threshold] if $amount <= $threshold;
502 # this only returns the first one that's below threshold, if there are
508 #my $conf = new FS::Conf;
510 #return contexts and fill-in values
511 # If you add anything, be sure to add a description in
512 # httemplate/edit/msg_template.html.
514 { 'cust_main' => [qw(
515 display_custnum agentnum agent_name
518 name name_short contact contact_firstlast
519 address1 address2 city county state zip
521 daytime night mobile fax
524 ship_name ship_name_short ship_contact ship_contact_firstlast
525 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
528 paymask payname paytype payip
529 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
530 classname categoryname
533 invoicing_list_emailonly
534 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
539 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
540 #compatibility: obsolete ship_ fields - use the non-ship versions
543 [ "ship_$field" => sub { shift->$field } ]
545 qw( last first company daytime night fax )
547 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
549 [ expdate => sub { shift->paydate_epoch } ], #compatibility
550 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
551 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
552 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
553 [ otaker_first => sub { shift->access_user->first } ],
554 [ otaker_last => sub { shift->access_user->last } ],
555 [ payby => sub { FS::payby->shortname(shift->payby) } ],
556 [ company_name => sub {
557 $conf->config('company_name', shift->agentnum)
559 [ company_address => sub {
560 $conf->config('company_address', shift->agentnum)
562 [ company_phonenum => sub {
563 $conf->config('company_phonenum', shift->agentnum)
565 [ selfservice_server_base_url => sub {
566 $conf->config('selfservice_server-base_url') #, shift->agentnum)
571 pkgnum pkg_label pkg_label_long
575 start_date setup bill last_bill
579 [ pkg => sub { shift->part_pkg->pkg } ],
580 [ pkg_category => sub { shift->part_pkg->categoryname } ],
581 [ pkg_class => sub { shift->part_pkg->classname } ],
582 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
583 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
584 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
585 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
586 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
587 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
588 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
589 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
590 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
592 # not necessarily correct for non-flat packages
593 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
594 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
596 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
605 [ due_date2str => sub { shift->due_date2str('short') } ],
607 #XXX not really thinking about cust_bill substitutions quite yet
609 # for welcome and limit warning messages
615 [ password => sub { shift->getfield('_password') } ],
616 [ column => sub { &$usage_warning(shift)->[0] } ],
617 [ amount => sub { &$usage_warning(shift)->[1] } ],
618 [ threshold => sub { &$usage_warning(shift)->[2] } ],
625 my $registrar = qsearchs('registrar',
626 { registrarnum => shift->registrarnum} );
627 $registrar ? $registrar->registrarname : ''
631 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
632 $svc_acct ? $svc_acct->email : ''
643 'svc_broadband' => [qw(
651 # for payment receipts
656 [ paid => sub { sprintf("%.2f", shift->paid) } ],
657 # overrides the one in cust_main in cases where a cust_pay is passed
658 [ payby => sub { FS::payby->shortname(shift->payby) } ],
659 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
661 my $cust_pay = shift;
662 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
663 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
666 # for payment decline messages
667 # try to support all cust_pay fields
668 # 'error' is a special case, it contains the raw error from the gateway
669 'cust_pay_pending' => [qw(
673 [ paid => sub { sprintf("%.2f", shift->paid) } ],
674 [ payby => sub { FS::payby->shortname(shift->payby) } ],
675 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
678 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
679 $pending->paymask : $pending->decrypt($pending->payinfo)
687 Returns the L<FS::template_content> object appropriate to LOCALE, if there
688 is one. If not, returns the one with a NULL locale.
695 qsearchs('template_content',
696 { 'msgnum' => $self->msgnum, 'locale' => $locale }) ||
697 qsearchs('template_content',
698 { 'msgnum' => $self->msgnum, 'locale' => '' });
703 Returns the L<FS::agent> object for this template.
708 my ($self, %opts) = @_;
711 # First move any historical templates in config to real message templates
715 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
716 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
717 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
718 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
719 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
720 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
721 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
724 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
725 foreach my $agentnum (@agentnums) {
727 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
728 if ($conf->exists($oldname, $agentnum)) {
729 my $new = new FS::msg_template({
730 'msgname' => $oldname,
731 'agentnum' => $agentnum,
732 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
733 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
734 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
735 'mime_type' => 'text/html',
736 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
738 my $error = $new->insert;
739 die $error if $error;
740 $conf->set($newname, $new->msgnum, $agentnum);
741 $conf->delete($oldname, $agentnum);
742 $conf->delete($from, $agentnum) if $from;
743 $conf->delete($subject, $agentnum) if $subject;
747 if ( $conf->exists('alert_expiration', $agentnum) ) {
748 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
749 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
751 warn "template for alerter_msgnum $msgnum not found\n";
754 # this is now a set of billing events
755 foreach my $days (30, 15, 5) {
756 my $event = FS::part_event->new({
757 'agentnum' => $agentnum,
758 'event' => "Card expiration warning - $days days",
759 'eventtable' => 'cust_main',
760 'check_freq' => '1d',
761 'action' => 'notice',
762 'disabled' => 'Y', #initialize first
764 my $error = $event->insert( 'msgnum' => $msgnum );
766 warn "error creating expiration alert event:\n$error\n\n";
769 # make it work like before:
770 # only send each warning once before the card expires,
771 # only warn active customers,
772 # only warn customers with CARD/DCRD,
773 # only warn customers who get email invoices
775 'once_every' => { 'run_delay' => '30d' },
776 'cust_paydate_within' => { 'within' => $days.'d' },
777 'cust_status' => { 'status' => { 'active' => 1 } },
778 'payby' => { 'payby' => { 'CARD' => 1,
781 'message_email' => {},
783 foreach (keys %conds) {
784 my $condition = FS::part_event_condition->new({
785 'conditionname' => $_,
786 'eventpart' => $event->eventpart,
788 $error = $condition->insert( %{ $conds{$_} });
790 warn "error creating expiration alert event:\n$error\n\n";
794 $error = $event->initialize;
796 warn "expiration alert event was created, but not initialized:\n$error\n\n";
799 $conf->delete('alerter_msgnum', $agentnum);
800 $conf->delete('alert_expiration', $agentnum);
802 } # if alerter_msgnum
807 # Move subject and body from msg_template to template_content
810 foreach my $msg_template ( qsearch('msg_template', {}) ) {
811 if ( $msg_template->subject || $msg_template->body ) {
812 # create new default content
814 $content{subject} = $msg_template->subject;
815 $msg_template->set('subject', '');
817 # work around obscure Pg/DBD bug
818 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
819 # (though the right fix is to upgrade DBD)
820 my $body = $msg_template->body;
821 if ( $body =~ /^x([0-9a-f]+)$/ ) {
822 # there should be no real message templates that look like that
823 warn "converting template body to TEXT\n";
824 $body = pack('H*', $1);
826 $content{body} = $body;
827 $msg_template->set('body', '');
829 my $error = $msg_template->replace(%content);
830 die $error if $error;
835 # Add new-style default templates if missing
837 $self->_populate_initial_data;
841 sub _populate_initial_data { #class method
842 #my($class, %opts) = @_;
845 eval "use FS::msg_template::InitialData;";
848 my $initial_data = FS::msg_template::InitialData->_initial_data;
850 foreach my $hash ( @$initial_data ) {
852 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
854 my $msg_template = new FS::msg_template($hash);
855 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
856 die $error if $error;
858 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
865 # Every bit as pleasant as it sounds.
867 # We do this because Text::Template::Preprocess doesn't
868 # actually work. It runs the entire template through
869 # the preprocessor, instead of the code segments. Which
870 # is a shame, because Text::Template already contains
871 # the code to do this operation.
873 my (@outside, @inside);
876 while($body || $chunk) {
877 my ($first, $delim, $rest);
878 # put all leading non-delimiters into $first
880 ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
882 # put a leading delimiter into $delim if there is one
884 ($rest =~ /^([{}]?)(.*)$/s);
886 if( $delim eq '{' ) {
889 push @outside, $chunk;
894 elsif( $delim eq '}' ) {
897 push @inside, $chunk;
905 push @outside, $chunk . $rest;
906 } # else ? something wrong
911 (\@outside, \@inside);
920 L<FS::Record>, schema.html from the base documentation.