1 package FS::msg_template;
2 use base qw( FS::Record );
5 use vars qw( $DEBUG $conf );
8 use FS::Record qw( qsearch qsearchs dbh );
11 use FS::template_content;
13 use Date::Format qw(time2str);
15 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
21 FS::msg_template - Object methods for msg_template records
27 $record = new FS::msg_template \%hash;
28 $record = new FS::msg_template { 'column' => 'value' };
30 $error = $record->insert;
32 $error = $new_record->replace($old_record);
34 $error = $record->delete;
36 $error = $record->check;
40 This uses a table-per-subclass ORM strategy, which is a somewhat cleaner
41 version of what we do elsewhere with _option tables. We could easily extract
42 that functionality into a base class, or even into FS::Record itself.
46 An FS::msg_template object represents a customer message template.
47 FS::msg_template inherits from FS::Record. The following fields are currently
52 =item msgnum - primary key
54 =item msgname - Name of the template. This will appear in the user interface;
55 if it needs to be localized for some users, add it to the message catalog.
57 =item msgclass - The L<FS::msg_template> subclass that this should belong to.
60 =item agentnum - Agent associated with this template. Can be NULL for a
63 =item mime_type - MIME type. Defaults to text/html.
65 =item from_addr - Source email address.
67 =item bcc_addr - Bcc all mail to this address.
69 =item disabled - disabled (NULL for not-disabled and selectable, 'D' for a
70 draft of a one-time message, 'C' for a completed one-time message, 'Y' for a
71 normal template disabled by user action).
81 Creates a new template. To add the template to the database, see L<"insert">.
83 Note that this stores the hash reference, not a distinct copy of the hash it
84 points to. You can ask the object for a copy with the I<hash> method.
88 # the new method can be inherited from FS::Record, if a table method is defined
90 sub table { 'msg_template'; }
92 sub extension_table { ''; } # subclasses don't HAVE to have extensions
96 my $class = 'FS::msg_template::' . $self->msgclass;
98 bless($self, $class) unless $@;
100 # merge in the extension fields (but let fields in $self override them)
101 # except don't ever override the extension's primary key, it's immutable
102 if ( $self->msgnum and $self->extension_table ) {
103 my $extension = $self->_extension;
105 my $ext_key = $extension->get($extension->primary_key);
106 $self->{Hash} = { $extension->hash,
108 $extension->primary_key => $ext_key
116 # Returns the subclass-specific extension record for this object. For internal
117 # use only; everyone else is supposed to think of this as a single record.
121 if ( $self->extension_table and $self->msgnum ) {
122 local $FS::Record::nowarn_classload = 1;
123 return qsearchs($self->extension_table, { msgnum => $self->msgnum });
128 =item insert [ CONTENT ]
130 Adds this record to the database. If there is an error, returns the error,
131 otherwise returns false.
139 my $oldAutoCommit = $FS::UID::AutoCommit;
140 local $FS::UID::AutoCommit = 0;
142 my $error = $self->SUPER::insert;
143 # calling _extension at this point makes it copy the msgnum, so links work
144 if ( $self->extension_table ) {
145 local $FS::Record::nowarn_classload = 1;
146 my $extension = FS::Record->new($self->extension_table, { $self->hash });
147 $error ||= $extension->insert;
151 dbh->rollback if $oldAutoCommit;
153 dbh->commit if $oldAutoCommit;
160 Delete this record from the database.
167 my $oldAutoCommit = $FS::UID::AutoCommit;
168 local $FS::UID::AutoCommit = 0;
171 my $extension = $self->_extension;
173 $error = $extension->delete;
176 $error ||= $self->SUPER::delete;
179 dbh->rollback if $oldAutoCommit;
181 dbh->commit if $oldAutoCommit;
186 =item replace [ OLD_RECORD ]
188 Replaces the OLD_RECORD with this one in the database. If there is an error,
189 returns the error, otherwise returns false.
195 my $old = shift || $new->replace_old;
197 my $oldAutoCommit = $FS::UID::AutoCommit;
198 local $FS::UID::AutoCommit = 0;
200 my $error = $new->SUPER::replace($old, @_);
202 my $extension = $new->_extension;
204 # merge changes into the extension record and replace it
205 $extension->{Hash} = { $extension->hash, $new->hash };
206 $error ||= $extension->replace;
210 dbh->rollback if $oldAutoCommit;
212 dbh->commit if $oldAutoCommit;
219 my $old = $self->replace_old;
220 # don't allow changing msgclass, except null to not-null (for upgrade)
221 if ( $old->msgclass ) {
222 if ( !$self->msgclass ) {
223 $self->set('msgclass', $old->msgclass);
224 } elsif ( $old->msgclass ne $self->msgclass ) {
225 return "Can't change message template class from ".$old->msgclass.
226 " to ".$self->msgclass.".";
234 Checks all fields to make sure this is a valid template. If there is
235 an error, returns the error, otherwise returns false. Called by the insert
240 # the check method should currently be supplied - FS::Record contains some
241 # data checking routines
247 $self->ut_numbern('msgnum')
248 || $self->ut_text('msgname')
249 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
250 || $self->ut_textn('mime_type')
251 || $self->ut_enum('disabled', [ '', 'Y', 'D', 'S' ] )
252 || $self->ut_textn('from_addr')
253 || $self->ut_textn('bcc_addr')
254 # fine for now, but change this to some kind of dynamic check if we
255 # ever have more than two msgclasses
256 || $self->ut_enum('msgclass', [ qw(email http) ]),
258 return $error if $error;
260 $self->mime_type('text/html') unless $self->mime_type;
265 =item prepare OPTION => VALUE
267 Fills in the template and returns an L<FS::cust_msg> object, containing the
268 message to be sent. This method must be provided by the subclass.
270 Options are passed as a list of name/value pairs:
276 Customer object (required).
280 Additional context object (currently, can be a cust_main, cust_pkg,
281 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
282 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
283 used for substitution.
285 As a special case, this may be an arrayref of two objects. Both
286 objects will be available for substitution, with their field names
287 prefixed with 'new_' and 'old_' respectively. This is used in the
288 rt_ticket export when exporting "replace" events.
292 Configuration option to use as the source address, based on the customer's
293 agentnum. If unspecified (or the named option is empty), 'invoice_from'
296 The I<from_addr> field in the template takes precedence over this.
300 Destination address. The default is to use the customer's
301 invoicing_list addresses. Multiple addresses may be comma-separated.
305 A hash reference of additional substitutions
315 =item prepare_substitutions OPTION => VALUE ...
317 Takes the same arguments as L</prepare>, and returns a hashref of the
318 substitution variables.
322 sub prepare_substitutions {
323 my( $self, %opt ) = @_;
325 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
326 my $object = $opt{'object'} or die 'object required';
328 warn "preparing substitutions for '".$self->msgname."'\n"
331 my $subs = $self->substitutions;
334 # create substitution table
338 push @objects, $cust_main if $cust_main;
342 if( ref($object) eq 'ARRAY' ) {
343 # [new, old], for provisioning tickets
344 push @objects, $object->[0], $object->[1];
345 push @prefixes, 'new_', 'old_';
346 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
349 push @objects, $object;
351 $svc = $object if $object->isa('FS::svc_Common');
355 push @objects, $svc->cust_svc->cust_pkg;
359 foreach my $obj (@objects) {
360 my $prefix = shift @prefixes;
361 foreach my $name (@{ $subs->{$obj->table} }) {
364 $hash{$prefix.$name} = $obj->$name();
366 elsif( ref($name) eq 'ARRAY' ) {
367 # [ foo => sub { ... } ]
368 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
371 warn "bad msg_template substitution: '$name'\n";
377 if ( $opt{substitutions} ) {
378 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
384 =item send OPTION => VALUE ...
386 Creates a message with L</prepare> (taking all the same options) and sends it.
392 my $cust_msg = $self->prepare(@_);
393 $self->send_prepared($cust_msg);
396 =item render OPTION => VALUE ...
398 Fills in the template and renders it to a PDF document. Returns the
399 name of the PDF file.
401 Options are as for 'prepare', but 'from' and 'to' are meaningless.
405 # XXX not sure where this ends up post-refactoring--a separate template
406 # class? it doesn't use the same rendering OR output machinery as ::email
408 # will also have options to set paper size, margins, etc.
412 eval "use PDF::WebKit";
415 my %hash = $self->prepare(%opt);
416 my $html = $hash{'html_body'};
418 # Graphics/stylesheets should probably go in /var/www on the Freeside
420 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
422 my $kit = PDF::WebKit->new(\$html); #%options
423 # hack to use our wrapper script
424 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
431 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
436 my( $self, %opt ) = @_;
437 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
440 # helper sub for package dates
441 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
443 # helper sub for money amounts
444 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
446 # helper sub for usage-related messages
447 my $usage_warning = sub {
449 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
450 my $amount = $svc->$col; next if $amount eq '';
451 my $method = $col.'_threshold';
452 my $threshold = $svc->$method; next if $threshold eq '';
453 return [$col, $amount, $threshold] if $amount <= $threshold;
454 # this only returns the first one that's below threshold, if there are
460 #return contexts and fill-in values
461 # If you add anything, be sure to add a description in
462 # httemplate/edit/msg_template.html.
464 { 'cust_main' => [qw(
465 display_custnum agentnum agent_name
468 name name_short contact contact_firstlast
469 address1 address2 city county state zip
471 daytime night mobile fax
474 ship_name ship_name_short ship_contact ship_contact_firstlast
475 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
478 paymask payname paytype payip
479 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
480 classname categoryname
483 invoicing_list_emailonly
484 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
489 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
490 #compatibility: obsolete ship_ fields - use the non-ship versions
493 [ "ship_$field" => sub { shift->$field } ]
495 qw( last first company daytime night fax )
497 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
499 [ expdate => sub { shift->paydate_epoch } ], #compatibility
500 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
501 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
502 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
503 [ otaker_first => sub { shift->access_user->first } ],
504 [ otaker_last => sub { shift->access_user->last } ],
505 [ payby => sub { FS::payby->shortname(shift->payby) } ],
506 [ company_name => sub {
507 $conf->config('company_name', shift->agentnum)
509 [ company_address => sub {
510 $conf->config('company_address', shift->agentnum)
512 [ company_phonenum => sub {
513 $conf->config('company_phonenum', shift->agentnum)
515 [ selfservice_server_base_url => sub {
516 $conf->config('selfservice_server-base_url') #, shift->agentnum)
521 pkgnum pkg_label pkg_label_long
525 start_date setup bill last_bill
529 [ pkg => sub { shift->part_pkg->pkg } ],
530 [ pkg_category => sub { shift->part_pkg->categoryname } ],
531 [ pkg_class => sub { shift->part_pkg->classname } ],
532 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
533 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
534 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
535 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
536 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
537 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
538 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
539 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
540 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
542 # not necessarily correct for non-flat packages
543 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
544 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
546 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
555 [ due_date2str => sub { shift->due_date2str('short') } ],
557 #XXX not really thinking about cust_bill substitutions quite yet
559 # for welcome and limit warning messages
565 [ password => sub { shift->getfield('_password') } ],
566 [ column => sub { &$usage_warning(shift)->[0] } ],
567 [ amount => sub { &$usage_warning(shift)->[1] } ],
568 [ threshold => sub { &$usage_warning(shift)->[2] } ],
575 my $registrar = qsearchs('registrar',
576 { registrarnum => shift->registrarnum} );
577 $registrar ? $registrar->registrarname : ''
581 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
582 $svc_acct ? $svc_acct->email : ''
593 'svc_broadband' => [qw(
601 # for payment receipts
606 [ paid => sub { sprintf("%.2f", shift->paid) } ],
607 # overrides the one in cust_main in cases where a cust_pay is passed
608 [ payby => sub { FS::payby->shortname(shift->payby) } ],
609 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
611 my $cust_pay = shift;
612 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
613 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
616 # for refund receipts
619 [ refund => sub { sprintf("%.2f", shift->refund) } ],
620 [ payby => sub { FS::payby->shortname(shift->payby) } ],
621 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
623 my $cust_refund = shift;
624 ($cust_refund->payby eq 'CARD' || $cust_refund->payby eq 'CHEK') ?
625 $cust_refund->paymask : $cust_refund->decrypt($cust_refund->payinfo)
628 # for payment decline messages
629 # try to support all cust_pay fields
630 # 'error' is a special case, it contains the raw error from the gateway
631 'cust_pay_pending' => [qw(
635 [ paid => sub { sprintf("%.2f", shift->paid) } ],
636 [ payby => sub { FS::payby->shortname(shift->payby) } ],
637 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
640 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
641 $pending->paymask : $pending->decrypt($pending->payinfo)
649 Stub, returns nothing.
657 Returns the L<FS::agent> object for this template.
662 my ($self, %opts) = @_;
665 # First move any historical templates in config to real message templates
669 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
670 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
671 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
672 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
673 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
674 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
675 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
678 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
679 foreach my $agentnum (@agentnums) {
681 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
682 if ($conf->exists($oldname, $agentnum)) {
683 my $new = new FS::msg_template({
684 'msgname' => $oldname,
685 'agentnum' => $agentnum,
686 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
687 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
688 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
689 'mime_type' => 'text/html',
690 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
692 my $error = $new->insert;
693 die $error if $error;
694 $conf->set($newname, $new->msgnum, $agentnum);
695 $conf->delete($oldname, $agentnum);
696 $conf->delete($from, $agentnum) if $from;
697 $conf->delete($subject, $agentnum) if $subject;
701 if ( $conf->exists('alert_expiration', $agentnum) ) {
702 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
703 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
705 warn "template for alerter_msgnum $msgnum not found\n";
708 # this is now a set of billing events
709 foreach my $days (30, 15, 5) {
710 my $event = FS::part_event->new({
711 'agentnum' => $agentnum,
712 'event' => "Card expiration warning - $days days",
713 'eventtable' => 'cust_main',
714 'check_freq' => '1d',
715 'action' => 'notice',
716 'disabled' => 'Y', #initialize first
718 my $error = $event->insert( 'msgnum' => $msgnum );
720 warn "error creating expiration alert event:\n$error\n\n";
723 # make it work like before:
724 # only send each warning once before the card expires,
725 # only warn active customers,
726 # only warn customers with CARD/DCRD,
727 # only warn customers who get email invoices
729 'once_every' => { 'run_delay' => '30d' },
730 'cust_paydate_within' => { 'within' => $days.'d' },
731 'cust_status' => { 'status' => { 'active' => 1 } },
732 'payby' => { 'payby' => { 'CARD' => 1,
735 'message_email' => {},
737 foreach (keys %conds) {
738 my $condition = FS::part_event_condition->new({
739 'conditionname' => $_,
740 'eventpart' => $event->eventpart,
742 $error = $condition->insert( %{ $conds{$_} });
744 warn "error creating expiration alert event:\n$error\n\n";
748 $error = $event->initialize;
750 warn "expiration alert event was created, but not initialized:\n$error\n\n";
753 $conf->delete('alerter_msgnum', $agentnum);
754 $conf->delete('alert_expiration', $agentnum);
756 } # if alerter_msgnum
761 # Move subject and body from msg_template to template_content
764 foreach my $msg_template ( qsearch('msg_template', {}) ) {
765 if ( $msg_template->subject || $msg_template->body ) {
766 # create new default content
768 $content{subject} = $msg_template->subject;
769 $msg_template->set('subject', '');
771 # work around obscure Pg/DBD bug
772 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
773 # (though the right fix is to upgrade DBD)
774 my $body = $msg_template->body;
775 if ( $body =~ /^x([0-9a-f]+)$/ ) {
776 # there should be no real message templates that look like that
777 warn "converting template body to TEXT\n";
778 $body = pack('H*', $1);
780 $content{body} = $body;
781 $msg_template->set('body', '');
782 my $error = $msg_template->replace(%content);
783 die $error if $error;
786 if ( !$msg_template->msgclass ) {
787 # set default message class
788 $msg_template->set('msgclass', 'email');
789 my $error = $msg_template->replace;
790 die $error if $error;
795 # Add new-style default templates if missing
797 $self->_populate_initial_data;
801 sub _populate_initial_data { #class method
802 #my($class, %opts) = @_;
805 eval "use FS::msg_template::InitialData;";
808 my $initial_data = FS::msg_template::InitialData->_initial_data;
810 foreach my $hash ( @$initial_data ) {
812 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
814 my $msg_template = new FS::msg_template($hash);
815 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
816 die $error if $error;
818 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
830 L<FS::Record>, schema.html from the base documentation.