1 package FS::msg_template;
4 use base qw( FS::Record );
6 use FS::Misc qw( generate_email send_email do_print );
8 use FS::Record qw( qsearch qsearchs );
13 use FS::template_content;
15 use Date::Format qw( time2str );
16 use HTML::Entities qw( decode_entities encode_entities ) ;
18 use HTML::TreeBuilder;
23 use vars qw( $DEBUG $conf );
25 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
31 FS::msg_template - Object methods for msg_template records
37 $record = new FS::msg_template \%hash;
38 $record = new FS::msg_template { 'column' => 'value' };
40 $error = $record->insert;
42 $error = $new_record->replace($old_record);
44 $error = $record->delete;
46 $error = $record->check;
50 An FS::msg_template object represents a customer message template.
51 FS::msg_template inherits from FS::Record. The following fields are currently
56 =item msgnum - primary key
58 =item msgname - Name of the template. This will appear in the user interface;
59 if it needs to be localized for some users, add it to the message catalog.
61 =item agentnum - Agent associated with this template. Can be NULL for a
64 =item mime_type - MIME type. Defaults to text/html.
66 =item from_addr - Source email address.
68 =item disabled - disabled ('Y' or NULL).
78 Creates a new template. To add the template to the database, see L<"insert">.
80 Note that this stores the hash reference, not a distinct copy of the hash it
81 points to. You can ask the object for a copy with the I<hash> method.
85 # the new method can be inherited from FS::Record, if a table method is defined
87 sub table { 'msg_template'; }
89 =item insert [ CONTENT ]
91 Adds this record to the database. If there is an error, returns the error,
92 otherwise returns false.
94 A default (no locale) L<FS::template_content> object will be created. CONTENT
95 is an optional hash containing 'subject' and 'body' for this object.
103 my $oldAutoCommit = $FS::UID::AutoCommit;
104 local $FS::UID::AutoCommit = 0;
107 my $error = $self->SUPER::insert;
109 $content{'msgnum'} = $self->msgnum;
110 $content{'subject'} ||= '';
111 $content{'body'} ||= '';
112 my $template_content = new FS::template_content (\%content);
113 $error = $template_content->insert;
117 $dbh->rollback if $oldAutoCommit;
121 $dbh->commit if $oldAutoCommit;
127 Delete this record from the database.
131 # the delete method can be inherited from FS::Record
133 =item replace [ OLD_RECORD ] [ CONTENT ]
135 Replaces the OLD_RECORD with this one in the database. If there is an error,
136 returns the error, otherwise returns false.
138 CONTENT is an optional hash containing 'subject', 'body', and 'locale'. If
139 supplied, an L<FS::template_content> object will be created (or modified, if
140 one already exists for this locale).
146 my $old = ( ref($_[0]) and $_[0]->isa('FS::Record') )
148 : $self->replace_old;
151 my $oldAutoCommit = $FS::UID::AutoCommit;
152 local $FS::UID::AutoCommit = 0;
155 my $error = $self->SUPER::replace($old);
157 if ( !$error and %content ) {
158 $content{'locale'} ||= '';
159 my $new_content = qsearchs('template_content', {
160 'msgnum' => $self->msgnum,
161 'locale' => $content{'locale'},
163 if ( $new_content ) {
164 $new_content->subject($content{'subject'});
165 $new_content->body($content{'body'});
166 $error = $new_content->replace;
169 $content{'msgnum'} = $self->msgnum;
170 $new_content = new FS::template_content \%content;
171 $error = $new_content->insert;
176 $dbh->rollback if $oldAutoCommit;
180 warn "committing FS::msg_template->replace\n" if $DEBUG and $oldAutoCommit;
181 $dbh->commit if $oldAutoCommit;
189 Checks all fields to make sure this is a valid template. If there is
190 an error, returns the error, otherwise returns false. Called by the insert
195 # the check method should currently be supplied - FS::Record contains some
196 # data checking routines
202 $self->ut_numbern('msgnum')
203 || $self->ut_text('msgname')
204 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
205 || $self->ut_textn('mime_type')
206 || $self->ut_enum('disabled', [ '', 'Y' ] )
207 || $self->ut_textn('from_addr')
209 return $error if $error;
211 $self->mime_type('text/html') unless $self->mime_type;
216 =item content_locales
218 Returns a hashref of the L<FS::template_content> objects attached to
219 this template, with the locale as key.
223 sub content_locales {
225 return $self->{'_content_locales'} ||= +{
226 map { $_->locale , $_ }
227 qsearch('template_content', { 'msgnum' => $self->msgnum })
231 =item prepare OPTION => VALUE
233 Fills in the template and returns a hash of the 'from' address, 'to'
234 addresses, subject line, and body.
236 Options are passed as a list of name/value pairs:
242 Customer object (required).
246 Additional context object (currently, can be a cust_main, cust_pkg,
247 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
248 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
249 used for substitution.
251 As a special case, this may be an arrayref of two objects. Both
252 objects will be available for substitution, with their field names
253 prefixed with 'new_' and 'old_' respectively. This is used in the
254 rt_ticket export when exporting "replace" events.
258 Configuration option to use as the source address, based on the customer's
259 agentnum. If unspecified (or the named option is empty), 'invoice_from'
262 The I<from_addr> field in the template takes precedence over this.
266 Destination address. The default is to use the customer's
267 invoicing_list addresses. Multiple addresses may be comma-separated.
271 A hash reference of additional substitutions
278 my( $self, %opt ) = @_;
280 my $cust_main = $opt{'cust_main'} or die 'cust_main required';
281 my $object = $opt{'object'} or die 'object required';
284 my $locale = $cust_main->locale || '';
285 warn "no locale for cust#".$cust_main->custnum."; using default content\n"
286 if $DEBUG and !$locale;
287 my $content = $self->content($cust_main->locale);
288 warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
291 my $subs = $self->substitutions;
294 # create substitution table
297 my @objects = ($cust_main);
301 if( ref($object) eq 'ARRAY' ) {
302 # [new, old], for provisioning tickets
303 push @objects, $object->[0], $object->[1];
304 push @prefixes, 'new_', 'old_';
305 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
308 push @objects, $object;
310 $svc = $object if $object->isa('FS::svc_Common');
314 push @objects, $svc->cust_svc->cust_pkg;
318 foreach my $obj (@objects) {
319 my $prefix = shift @prefixes;
320 foreach my $name (@{ $subs->{$obj->table} }) {
323 $hash{$prefix.$name} = $obj->$name();
325 elsif( ref($name) eq 'ARRAY' ) {
326 # [ foo => sub { ... } ]
327 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
330 warn "bad msg_template substitution: '$name'\n";
336 if ( $opt{substitutions} ) {
337 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
340 $_ = encode_entities($_ || '') foreach values(%hash);
345 my $subject_tmpl = new Text::Template (
347 SOURCE => $content->subject,
349 my $subject = $subject_tmpl->fill_in( HASH => \%hash );
351 my $body = $content->body;
352 my ($skin, $guts) = eviscerate($body);
354 $_ = decode_entities($_); # turn all punctuation back into itself
355 s/\r//gs; # remove \r's
356 s/<br[^>]*>/\n/gsi; # and <br /> tags
357 s/<p>/\n/gsi; # and <p>
358 s/<\/p>//gsi; # and </p>
359 s/\240/ /gs; # and
363 $body = '{ use Date::Format qw(time2str); "" }';
364 while(@$skin || @$guts) {
365 $body .= shift(@$skin) || '';
366 $body .= shift(@$guts) || '';
373 my $body_tmpl = new Text::Template (
378 $body = $body_tmpl->fill_in( HASH => \%hash );
385 if ( exists($opt{'to'}) ) {
386 @to = split(/\s*,\s*/, $opt{'to'});
389 @to = $cust_main->invoicing_list_emailonly;
391 # no warning when preparing with no destination
393 my $from_addr = $self->from_addr;
396 if ( $opt{'from_config'} ) {
397 $from_addr = scalar( $conf->config($opt{'from_config'},
398 $cust_main->agentnum) );
400 $from_addr ||= $conf->invoice_from_full($cust_main->agentnum);
403 # if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
404 # my $cust_msg = FS::cust_msg->new({
405 # 'custnum' => $cust_main->custnum,
406 # 'msgnum' => $self->msgnum,
407 # 'status' => 'prepared',
410 # @cust_msg = ('cust_msg' => $cust_msg);
413 my $text_body = encode('UTF-8',
414 HTML::FormatText->new(leftmargin => 0, rightmargin => 70)
415 ->format( HTML::TreeBuilder->new_from_content($body) )
418 'custnum' => $cust_main->custnum,
419 'msgnum' => $self->msgnum,
420 'from' => $from_addr,
422 'bcc' => $self->bcc_addr || undef,
423 'subject' => $subject,
424 'html_body' => $body,
425 'text_body' => $text_body,
430 =item send OPTION => VALUE
432 Fills in the template and sends it to the customer. Options are as for
433 'prepare', plus 'attach', a L<MIME::Entity> (or arrayref of them) to attach
438 # broken out from prepare() in case we want to queue the sending,
444 my %email = generate_email($self->prepare(%opt));
445 if ( $opt{'attach'} ) {
447 if (ref($opt{'attach'}) eq 'ARRAY') {
448 @attach = @{ $opt{'attach'} };
450 @attach = $opt{'attach'};
452 push @{ $email{mimeparts} }, @attach;
458 =item render OPTION => VALUE ...
460 Fills in the template and renders it to a PDF document. Returns the
461 name of the PDF file.
463 Options are as for 'prepare', but 'from' and 'to' are meaningless.
467 # will also have options to set paper size, margins, etc.
471 eval "use PDF::WebKit";
474 my %hash = $self->prepare(%opt);
475 my $html = $hash{'html_body'};
477 # Graphics/stylesheets should probably go in /var/www on the Freeside
479 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
481 my $kit = PDF::WebKit->new(\$html); #%options
482 # hack to use our wrapper script
483 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
490 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
495 my( $self, %opt ) = @_;
496 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
499 # helper sub for package dates
500 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
502 # helper sub for money amounts
503 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
505 # helper sub for usage-related messages
506 my $usage_warning = sub {
508 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
509 my $amount = $svc->$col; next if $amount eq '';
510 my $method = $col.'_threshold';
511 my $threshold = $svc->$method; next if $threshold eq '';
512 return [$col, $amount, $threshold] if $amount <= $threshold;
513 # this only returns the first one that's below threshold, if there are
519 #my $conf = new FS::Conf;
521 #return contexts and fill-in values
522 # If you add anything, be sure to add a description in
523 # httemplate/edit/msg_template.html.
525 my $payinfo_sub = sub {
527 ($obj->payby eq 'CARD' || $obj->payby eq 'CHEK')
529 : $obj->decrypt($obj->payinfo)
531 my $payinfo_end = sub {
533 my $payinfo = &$payinfo_sub($obj);
534 substr($payinfo, -4);
536 { 'cust_main' => [qw(
537 display_custnum agentnum agent_name
540 name name_short contact contact_firstlast
541 address1 address2 city county state zip
543 daytime night mobile fax
546 ship_name ship_name_short ship_contact ship_contact_firstlast
547 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
550 paymask payname paytype payip
551 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
552 classname categoryname
555 invoicing_list_emailonly
556 cust_status ucfirst_cust_status cust_statuscolor
561 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
562 #compatibility: obsolete ship_ fields - use the non-ship versions
565 [ "ship_$field" => sub { shift->$field } ]
567 qw( last first company daytime night fax )
569 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
571 [ expdate => sub { shift->paydate_epoch } ], #compatibility
572 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
573 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
574 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
575 [ otaker_first => sub { shift->access_user->first } ],
576 [ otaker_last => sub { shift->access_user->last } ],
577 [ payby => sub { FS::payby->shortname(shift->payby) } ],
578 [ company_name => sub {
579 $conf->config('company_name', shift->agentnum)
581 [ company_address => sub {
582 $conf->config('company_address', shift->agentnum)
584 [ company_phonenum => sub {
585 $conf->config('company_phonenum', shift->agentnum)
587 [ selfservice_server_base_url => sub {
588 $conf->config('selfservice_server-base_url') #, shift->agentnum)
593 pkgnum pkg_label pkg_label_long
597 start_date setup bill last_bill
601 [ pkg => sub { shift->part_pkg->pkg } ],
602 [ pkg_category => sub { shift->part_pkg->categoryname } ],
603 [ pkg_class => sub { shift->part_pkg->classname } ],
604 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
605 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
606 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
607 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
608 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
609 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
610 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
611 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
612 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
614 # not necessarily correct for non-flat packages
615 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
616 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
618 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
627 [ due_date2str => sub { shift->due_date2str('short') } ],
629 #XXX not really thinking about cust_bill substitutions quite yet
631 # for welcome and limit warning messages
637 [ password => sub { shift->getfield('_password') } ],
638 [ column => sub { &$usage_warning(shift)->[0] } ],
639 [ amount => sub { &$usage_warning(shift)->[1] } ],
640 [ threshold => sub { &$usage_warning(shift)->[2] } ],
647 my $registrar = qsearchs('registrar',
648 { registrarnum => shift->registrarnum} );
649 $registrar ? $registrar->registrarname : ''
653 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
654 $svc_acct ? $svc_acct->email : ''
665 'svc_broadband' => [qw(
673 # for payment receipts
678 [ paid => sub { sprintf("%.2f", shift->paid) } ],
679 # overrides the one in cust_main in cases where a cust_pay is passed
680 [ payby => sub { FS::payby->shortname(shift->payby) } ],
681 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
682 [ 'payinfo' => $payinfo_sub ],
683 [ 'payinfo_end' => $payinfo_end ],
685 # for refund receipts
688 [ refund => sub { sprintf("%.2f", shift->refund) } ],
689 [ payby => sub { FS::payby->shortname(shift->payby) } ],
690 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
691 [ 'payinfo' => $payinfo_sub ],
692 [ 'payinfo_end' => $payinfo_end ],
694 # for payment decline messages
695 # try to support all cust_pay fields
696 # 'error' is a special case, it contains the raw error from the gateway
697 'cust_pay_pending' => [qw(
701 [ paid => sub { sprintf("%.2f", shift->paid) } ],
702 [ payby => sub { FS::payby->shortname(shift->payby) } ],
703 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
704 [ 'payinfo' => $payinfo_sub ],
705 [ 'payinfo_end' => $payinfo_end ],
712 Returns the L<FS::template_content> object appropriate to LOCALE, if there
713 is one. If not, returns the one with a NULL locale.
720 qsearchs('template_content',
721 { 'msgnum' => $self->msgnum, 'locale' => $locale }) ||
722 qsearchs('template_content',
723 { 'msgnum' => $self->msgnum, 'locale' => '' });
728 Returns the L<FS::agent> object for this template.
733 qsearchs('agent', { 'agentnum' => $_[0]->agentnum });
737 my ($self, %opts) = @_;
740 # First move any historical templates in config to real message templates
744 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
745 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
746 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
747 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
748 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
749 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
750 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
753 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
754 foreach my $agentnum (@agentnums) {
756 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
757 if ($conf->exists($oldname, $agentnum)) {
758 my $new = new FS::msg_template({
759 'msgname' => $oldname,
760 'agentnum' => $agentnum,
761 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
762 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
763 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
764 'mime_type' => 'text/html',
765 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
767 my $error = $new->insert;
768 die $error if $error;
769 $conf->set($newname, $new->msgnum, $agentnum);
770 $conf->delete($oldname, $agentnum);
771 $conf->delete($from, $agentnum) if $from;
772 $conf->delete($subject, $agentnum) if $subject;
776 if ( $conf->exists('alert_expiration', $agentnum) ) {
777 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
778 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
780 warn "template for alerter_msgnum $msgnum not found\n";
783 # this is now a set of billing events
784 foreach my $days (30, 15, 5) {
785 my $event = FS::part_event->new({
786 'agentnum' => $agentnum,
787 'event' => "Card expiration warning - $days days",
788 'eventtable' => 'cust_main',
789 'check_freq' => '1d',
790 'action' => 'notice',
791 'disabled' => 'Y', #initialize first
793 my $error = $event->insert( 'msgnum' => $msgnum );
795 warn "error creating expiration alert event:\n$error\n\n";
798 # make it work like before:
799 # only send each warning once before the card expires,
800 # only warn active customers,
801 # only warn customers with CARD/DCRD,
802 # only warn customers who get email invoices
804 'once_every' => { 'run_delay' => '30d' },
805 'cust_paydate_within' => { 'within' => $days.'d' },
806 'cust_status' => { 'status' => { 'active' => 1 } },
807 'payby' => { 'payby' => { 'CARD' => 1,
810 'message_email' => {},
812 foreach (keys %conds) {
813 my $condition = FS::part_event_condition->new({
814 'conditionname' => $_,
815 'eventpart' => $event->eventpart,
817 $error = $condition->insert( %{ $conds{$_} });
819 warn "error creating expiration alert event:\n$error\n\n";
823 $error = $event->initialize;
825 warn "expiration alert event was created, but not initialized:\n$error\n\n";
828 $conf->delete('alerter_msgnum', $agentnum);
829 $conf->delete('alert_expiration', $agentnum);
831 } # if alerter_msgnum
836 # Move subject and body from msg_template to template_content
839 foreach my $msg_template ( qsearch('msg_template', {}) ) {
840 if ( $msg_template->subject || $msg_template->body ) {
841 # create new default content
843 $content{subject} = $msg_template->subject;
844 $msg_template->set('subject', '');
846 # work around obscure Pg/DBD bug
847 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
848 # (though the right fix is to upgrade DBD)
849 my $body = $msg_template->body;
850 if ( $body =~ /^x([0-9a-f]+)$/ ) {
851 # there should be no real message templates that look like that
852 warn "converting template body to TEXT\n";
853 $body = pack('H*', $1);
855 $content{body} = $body;
856 $msg_template->set('body', '');
858 my $error = $msg_template->replace(%content);
859 die $error if $error;
864 # Add new-style default templates if missing
866 $self->_populate_initial_data;
870 sub _populate_initial_data { #class method
871 #my($class, %opts) = @_;
874 eval "use FS::msg_template::InitialData;";
877 my $initial_data = FS::msg_template::InitialData->_initial_data;
879 foreach my $hash ( @$initial_data ) {
881 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
883 my $msg_template = new FS::msg_template($hash);
884 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
885 die $error if $error;
887 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
894 # Every bit as pleasant as it sounds.
896 # We do this because Text::Template::Preprocess doesn't
897 # actually work. It runs the entire template through
898 # the preprocessor, instead of the code segments. Which
899 # is a shame, because Text::Template already contains
900 # the code to do this operation.
902 my (@outside, @inside);
905 while($body || $chunk) {
906 my ($first, $delim, $rest);
907 # put all leading non-delimiters into $first
909 ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
911 # put a leading delimiter into $delim if there is one
913 ($rest =~ /^([{}]?)(.*)$/s);
915 if( $delim eq '{' ) {
918 push @outside, $chunk;
923 elsif( $delim eq '}' ) {
926 push @inside, $chunk;
934 push @outside, $chunk . $rest;
935 } # else ? something wrong
940 (\@outside, \@inside);
949 L<FS::Record>, schema.html from the base documentation.