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 $@;
99 warn "Error loading msg_template msgclass: " . $@ if $@; #or die?
101 # merge in the extension fields (but let fields in $self override them)
102 # except don't ever override the extension's primary key, it's immutable
103 if ( $self->msgnum and $self->extension_table ) {
104 my $extension = $self->_extension;
106 my $ext_key = $extension->get($extension->primary_key);
107 $self->{Hash} = { $extension->hash,
109 $extension->primary_key => $ext_key
117 # Returns the subclass-specific extension record for this object. For internal
118 # use only; everyone else is supposed to think of this as a single record.
122 if ( $self->extension_table and $self->msgnum ) {
123 local $FS::Record::nowarn_classload = 1;
124 return qsearchs($self->extension_table, { msgnum => $self->msgnum });
129 =item insert [ CONTENT ]
131 Adds this record to the database. If there is an error, returns the error,
132 otherwise returns false.
140 my $oldAutoCommit = $FS::UID::AutoCommit;
141 local $FS::UID::AutoCommit = 0;
143 my $error = $self->SUPER::insert;
144 # calling _extension at this point makes it copy the msgnum, so links work
145 if ( $self->extension_table ) {
146 local $FS::Record::nowarn_classload = 1;
147 my $extension = FS::Record->new($self->extension_table, { $self->hash });
148 $error ||= $extension->insert;
152 dbh->rollback if $oldAutoCommit;
154 dbh->commit if $oldAutoCommit;
161 Delete this record from the database.
168 my $oldAutoCommit = $FS::UID::AutoCommit;
169 local $FS::UID::AutoCommit = 0;
172 my $extension = $self->_extension;
174 $error = $extension->delete;
177 $error ||= $self->SUPER::delete;
180 dbh->rollback if $oldAutoCommit;
182 dbh->commit if $oldAutoCommit;
187 =item replace [ OLD_RECORD ]
189 Replaces the OLD_RECORD with this one in the database. If there is an error,
190 returns the error, otherwise returns false.
196 my $old = shift || $new->replace_old;
198 my $oldAutoCommit = $FS::UID::AutoCommit;
199 local $FS::UID::AutoCommit = 0;
201 my $error = $new->SUPER::replace($old, @_);
203 my $extension = $new->_extension;
205 # merge changes into the extension record and replace it
206 $extension->{Hash} = { $extension->hash, $new->hash };
207 $error ||= $extension->replace;
211 dbh->rollback if $oldAutoCommit;
213 dbh->commit if $oldAutoCommit;
220 my $old = $self->replace_old;
221 # don't allow changing msgclass, except null to not-null (for upgrade)
222 if ( $old->msgclass ) {
223 if ( !$self->msgclass ) {
224 $self->set('msgclass', $old->msgclass);
225 } elsif ( $old->msgclass ne $self->msgclass ) {
226 return "Can't change message template class from ".$old->msgclass.
227 " to ".$self->msgclass.".";
235 Checks all fields to make sure this is a valid template. If there is
236 an error, returns the error, otherwise returns false. Called by the insert
241 # the check method should currently be supplied - FS::Record contains some
242 # data checking routines
248 $self->ut_numbern('msgnum')
249 || $self->ut_text('msgname')
250 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
251 || $self->ut_textn('mime_type')
252 || $self->ut_enum('disabled', [ '', 'Y', 'D', 'S' ] )
253 || $self->ut_textn('from_addr')
254 || $self->ut_textn('bcc_addr')
255 # fine for now, but change this to some kind of dynamic check if we
256 # ever have more than two msgclasses
257 || $self->ut_enum('msgclass', [ qw(email http) ]),
259 return $error if $error;
261 $self->mime_type('text/html') unless $self->mime_type;
266 =item prepare OPTION => VALUE
268 Fills in the template and returns an L<FS::cust_msg> object, containing the
269 message to be sent. This method must be provided by the subclass.
271 Options are passed as a list of name/value pairs:
281 Additional context object (currently, can be a cust_main, cust_pkg,
282 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
283 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
284 used for substitution.
286 As a special case, this may be an arrayref of two objects. Both
287 objects will be available for substitution, with their field names
288 prefixed with 'new_' and 'old_' respectively. This is used in the
289 rt_ticket export when exporting "replace" events.
293 Configuration option to use as the source address, based on the customer's
294 agentnum. If unspecified (or the named option is empty), 'invoice_from'
297 The I<from_addr> field in the template takes precedence over this.
301 Destination address. The default is to use the customer's
302 invoicing_list addresses. Multiple addresses may be comma-separated.
306 A hash reference of additional substitutions
316 =item prepare_substitutions OPTION => VALUE ...
318 Takes the same arguments as L</prepare>, and returns a hashref of the
319 substitution variables.
323 sub prepare_substitutions {
324 my( $self, %opt ) = @_;
326 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
327 my $object = $opt{'object'}; # or die 'object required';
329 warn "preparing substitutions for '".$self->msgname."'\n"
332 my $subs = $self->substitutions;
335 # create substitution table
339 push @objects, $cust_main if $cust_main;
343 if( ref($object) eq 'ARRAY' ) {
344 # [new, old], for provisioning tickets
345 push @objects, $object->[0], $object->[1];
346 push @prefixes, 'new_', 'old_';
347 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
350 push @objects, $object;
352 $svc = $object if $object->isa('FS::svc_Common');
356 push @objects, $svc->cust_svc->cust_pkg;
360 foreach my $obj (@objects) {
361 my $prefix = shift @prefixes;
362 foreach my $name (@{ $subs->{$obj->table} }) {
365 $hash{$prefix.$name} = $obj->$name();
367 elsif( ref($name) eq 'ARRAY' ) {
368 # [ foo => sub { ... } ]
369 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
372 warn "bad msg_template substitution: '$name'\n";
378 if ( $opt{substitutions} ) {
379 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
385 =item send OPTION => VALUE ...
387 Creates a message with L</prepare> (taking all the same options) and sends it.
393 my $cust_msg = $self->prepare(@_);
394 $self->send_prepared($cust_msg);
397 =item render OPTION => VALUE ...
399 Fills in the template and renders it to a PDF document. Returns the
400 name of the PDF file.
402 Options are as for 'prepare', but 'from' and 'to' are meaningless.
406 # XXX not sure where this ends up post-refactoring--a separate template
407 # class? it doesn't use the same rendering OR output machinery as ::email
409 # will also have options to set paper size, margins, etc.
413 eval "use PDF::WebKit";
416 my %hash = $self->prepare(%opt);
417 my $html = $hash{'html_body'};
419 # Graphics/stylesheets should probably go in /var/www on the Freeside
421 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
423 my $kit = PDF::WebKit->new(\$html); #%options
424 # hack to use our wrapper script
425 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
432 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
437 my( $self, %opt ) = @_;
438 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
441 # helper sub for package dates
442 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
444 # helper sub for money amounts
445 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
447 # helper sub for usage-related messages
448 my $usage_warning = sub {
450 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
451 my $amount = $svc->$col; next if $amount eq '';
452 my $method = $col.'_threshold';
453 my $threshold = $svc->$method; next if $threshold eq '';
454 return [$col, $amount, $threshold] if $amount <= $threshold;
455 # this only returns the first one that's below threshold, if there are
461 #return contexts and fill-in values
462 # If you add anything, be sure to add a description in
463 # httemplate/edit/msg_template.html.
465 my $payinfo_sub = sub {
467 ($obj->payby eq 'CARD' || $obj->payby eq 'CHEK')
469 : $obj->decrypt($obj->payinfo)
471 my $payinfo_end = sub {
473 my $payinfo = &$payinfo_sub($obj);
474 substr($payinfo, -4);
476 { 'cust_main' => [qw(
477 display_custnum agentnum agent_name
480 name name_short contact contact_firstlast
481 address1 address2 city county state zip
483 daytime night mobile fax
486 ship_name ship_name_short ship_contact ship_contact_firstlast
487 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
490 paymask payname paytype payip
491 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
492 classname categoryname
495 invoicing_list_emailonly
496 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
501 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
502 #compatibility: obsolete ship_ fields - use the non-ship versions
505 [ "ship_$field" => sub { shift->$field } ]
507 qw( last first company daytime night fax )
509 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
511 [ expdate => sub { shift->paydate_epoch } ], #compatibility
512 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
513 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
514 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
515 [ otaker_first => sub { shift->access_user->first } ],
516 [ otaker_last => sub { shift->access_user->last } ],
517 [ payby => sub { FS::payby->shortname(shift->payby) } ],
518 [ company_name => sub {
519 $conf->config('company_name', shift->agentnum)
521 [ company_address => sub {
522 $conf->config('company_address', shift->agentnum)
524 [ company_phonenum => sub {
525 $conf->config('company_phonenum', shift->agentnum)
527 [ selfservice_server_base_url => sub {
528 $conf->config('selfservice_server-base_url') #, shift->agentnum)
533 pkgnum pkg_label pkg_label_long
537 start_date setup bill last_bill
541 [ pkg => sub { shift->part_pkg->pkg } ],
542 [ pkg_category => sub { shift->part_pkg->categoryname } ],
543 [ pkg_class => sub { shift->part_pkg->classname } ],
544 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
545 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
546 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
547 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
548 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
549 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
550 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
551 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
552 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
554 # not necessarily correct for non-flat packages
555 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
556 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
558 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
567 [ due_date2str => sub { shift->due_date2str('short') } ],
569 #XXX not really thinking about cust_bill substitutions quite yet
571 # for welcome and limit warning messages
577 [ password => sub { shift->getfield('_password') } ],
578 [ column => sub { &$usage_warning(shift)->[0] } ],
579 [ amount => sub { &$usage_warning(shift)->[1] } ],
580 [ threshold => sub { &$usage_warning(shift)->[2] } ],
587 my $registrar = qsearchs('registrar',
588 { registrarnum => shift->registrarnum} );
589 $registrar ? $registrar->registrarname : ''
593 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
594 $svc_acct ? $svc_acct->email : ''
605 'svc_broadband' => [qw(
613 # for payment receipts
618 [ paid => sub { sprintf("%.2f", shift->paid) } ],
619 # overrides the one in cust_main in cases where a cust_pay is passed
620 [ payby => sub { FS::payby->shortname(shift->payby) } ],
621 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
622 [ 'payinfo' => $payinfo_sub ],
623 [ 'payinfo_end' => $payinfo_end ],
625 # for refund receipts
628 [ refund => sub { sprintf("%.2f", shift->refund) } ],
629 [ payby => sub { FS::payby->shortname(shift->payby) } ],
630 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
631 [ 'payinfo' => $payinfo_sub ],
632 [ 'payinfo_end' => $payinfo_end ],
634 # for payment decline messages
635 # try to support all cust_pay fields
636 # 'error' is a special case, it contains the raw error from the gateway
637 'cust_pay_pending' => [qw(
641 [ paid => sub { sprintf("%.2f", shift->paid) } ],
642 [ payby => sub { FS::payby->shortname(shift->payby) } ],
643 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
644 [ 'payinfo' => $payinfo_sub ],
645 [ 'payinfo_end' => $payinfo_end ],
652 Stub, returns nothing.
660 Returns the L<FS::agent> object for this template.
665 my ($self, %opts) = @_;
668 # First move any historical templates in config to real message templates
672 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
673 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
674 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
675 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
676 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
677 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '', 'welcome_email-mimetype' ],
678 [ 'threshold_warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', 'warning_email-cc', 'warning_email-mimetype' ],
681 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
682 foreach my $agentnum (@agentnums) {
684 my ($newname, $oldname, $subject, $from, $bcc, $mimetype) = @$_;
686 if ($conf->exists($oldname, $agentnum)) {
687 my $new = new FS::msg_template({
688 'msgclass' => 'email',
689 'msgname' => $oldname,
690 'agentnum' => $agentnum,
691 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
692 'bcc_addr' => ($bcc && $conf->config($bcc, $agentnum)) || '',
693 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
694 'mime_type' => 'text/html',
695 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
697 my $error = $new->insert;
698 die $error if $error;
699 $conf->set($newname, $new->msgnum, $agentnum);
700 $conf->delete($oldname, $agentnum);
701 $conf->delete($from, $agentnum) if $from;
702 $conf->delete($subject, $agentnum) if $subject;
703 $conf->delete($bcc, $agentnum) if $bcc;
704 $conf->delete($mimetype, $agentnum) if $mimetype;
708 if ( $conf->exists('alert_expiration', $agentnum) ) {
709 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
710 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
712 warn "template for alerter_msgnum $msgnum not found\n";
715 # this is now a set of billing events
716 foreach my $days (30, 15, 5) {
717 my $event = FS::part_event->new({
718 'agentnum' => $agentnum,
719 'event' => "Card expiration warning - $days days",
720 'eventtable' => 'cust_main',
721 'check_freq' => '1d',
722 'action' => 'notice',
723 'disabled' => 'Y', #initialize first
725 my $error = $event->insert( 'msgnum' => $msgnum );
727 warn "error creating expiration alert event:\n$error\n\n";
730 # make it work like before:
731 # only send each warning once before the card expires,
732 # only warn active customers,
733 # only warn customers with CARD/DCRD,
734 # only warn customers who get email invoices
736 'once_every' => { 'run_delay' => '30d' },
737 'cust_paydate_within' => { 'within' => $days.'d' },
738 'cust_status' => { 'status' => { 'active' => 1 } },
739 'payby' => { 'payby' => { 'CARD' => 1,
742 'message_email' => {},
744 foreach (keys %conds) {
745 my $condition = FS::part_event_condition->new({
746 'conditionname' => $_,
747 'eventpart' => $event->eventpart,
749 $error = $condition->insert( %{ $conds{$_} });
751 warn "error creating expiration alert event:\n$error\n\n";
755 $error = $event->initialize;
757 warn "expiration alert event was created, but not initialized:\n$error\n\n";
760 $conf->delete('alerter_msgnum', $agentnum);
761 $conf->delete('alert_expiration', $agentnum);
763 } # if alerter_msgnum
768 # Move subject and body from msg_template to template_content
771 foreach my $msg_template ( qsearch('msg_template', {}) ) {
772 if ( $msg_template->subject || $msg_template->body ) {
773 # create new default content
775 $content{subject} = $msg_template->subject;
776 $msg_template->set('subject', '');
778 # work around obscure Pg/DBD bug
779 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
780 # (though the right fix is to upgrade DBD)
781 my $body = $msg_template->body;
782 if ( $body =~ /^x([0-9a-f]+)$/ ) {
783 # there should be no real message templates that look like that
784 warn "converting template body to TEXT\n";
785 $body = pack('H*', $1);
787 $content{body} = $body;
788 $msg_template->set('body', '');
789 my $error = $msg_template->replace(%content);
790 die $error if $error;
793 if ( !$msg_template->msgclass ) {
794 # set default message class
795 $msg_template->set('msgclass', 'email');
796 my $error = $msg_template->replace;
797 die $error if $error;
802 # Add new-style default templates if missing
804 $self->_populate_initial_data;
806 ### Fix dump-email_to (needs to happen after _populate_initial_data)
807 if ($conf->config('dump-email_to')) {
808 # anyone who still uses dump-email_to should have just had this created
809 my ($msg_template) = qsearch('msg_template',{ msgname => 'System log' });
811 eval "use FS::log_email;";
813 my $log_email = new FS::log_email {
814 'context' => 'Cron::backup',
816 'msgnum' => $msg_template->msgnum,
817 'to_addr' => $conf->config('dump-email_to'),
819 my $error = $log_email->insert;
820 die $error if $error;
821 $conf->delete('dump-email_to');
827 sub _populate_initial_data { #class method
828 #my($class, %opts) = @_;
831 eval "use FS::msg_template::InitialData;";
833 eval "use FS::upgrade_journal;";
836 my $initial_data = FS::msg_template::InitialData->_initial_data;
838 foreach my $hash ( @$initial_data ) {
840 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
841 next if $hash->{_upgrade_journal} && FS::upgrade_journal->is_done( $hash->{_upgrade_journal} );
843 my $msg_template = new FS::msg_template($hash);
844 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
845 die $error if $error;
847 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
848 FS::upgrade_journal->set_done( $hash->{_upgrade_journal} ) if $hash->{_upgrade_journal};
860 L<FS::Record>, schema.html from the base documentation.