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 return '' unless $self->msgclass;
97 my $class = 'FS::msg_template::' . $self->msgclass;
99 bless($self, $class) unless $@;
100 warn "Error loading msg_template msgclass: " . $@ if $@; #or die?
102 # merge in the extension fields (but let fields in $self override them)
103 # except don't ever override the extension's primary key, it's immutable
104 if ( $self->msgnum and $self->extension_table ) {
105 my $extension = $self->_extension;
107 my $ext_key = $extension->get($extension->primary_key);
108 $self->{Hash} = { $extension->hash,
110 $extension->primary_key => $ext_key
118 # Returns the subclass-specific extension record for this object. For internal
119 # use only; everyone else is supposed to think of this as a single record.
123 if ( $self->extension_table and $self->msgnum ) {
124 local $FS::Record::nowarn_classload = 1;
125 return qsearchs($self->extension_table, { msgnum => $self->msgnum });
130 =item insert [ CONTENT ]
132 Adds this record to the database. If there is an error, returns the error,
133 otherwise returns false.
141 my $oldAutoCommit = $FS::UID::AutoCommit;
142 local $FS::UID::AutoCommit = 0;
144 my $error = $self->SUPER::insert;
145 # calling _extension at this point makes it copy the msgnum, so links work
146 if ( $self->extension_table ) {
147 local $FS::Record::nowarn_classload = 1;
148 my $extension = FS::Record->new($self->extension_table, { $self->hash });
149 $error ||= $extension->insert;
153 dbh->rollback if $oldAutoCommit;
155 dbh->commit if $oldAutoCommit;
162 Delete this record from the database.
169 my $oldAutoCommit = $FS::UID::AutoCommit;
170 local $FS::UID::AutoCommit = 0;
173 my $extension = $self->_extension;
175 $error = $extension->delete;
178 $error ||= $self->SUPER::delete;
181 dbh->rollback if $oldAutoCommit;
183 dbh->commit if $oldAutoCommit;
188 =item replace [ OLD_RECORD ]
190 Replaces the OLD_RECORD with this one in the database. If there is an error,
191 returns the error, otherwise returns false.
197 my $old = shift || $new->replace_old;
199 my $oldAutoCommit = $FS::UID::AutoCommit;
200 local $FS::UID::AutoCommit = 0;
202 my $error = $new->SUPER::replace($old, @_);
204 my $extension = $new->_extension;
206 # merge changes into the extension record and replace it
207 $extension->{Hash} = { $extension->hash, $new->hash };
208 $error ||= $extension->replace;
212 dbh->rollback if $oldAutoCommit;
214 dbh->commit if $oldAutoCommit;
221 my $old = $self->replace_old;
222 # don't allow changing msgclass, except null to not-null (for upgrade)
223 if ( $old->msgclass ) {
224 if ( !$self->msgclass ) {
225 $self->set('msgclass', $old->msgclass);
226 } elsif ( $old->msgclass ne $self->msgclass ) {
227 return "Can't change message template class from ".$old->msgclass.
228 " to ".$self->msgclass.".";
236 Checks all fields to make sure this is a valid template. If there is
237 an error, returns the error, otherwise returns false. Called by the insert
242 # the check method should currently be supplied - FS::Record contains some
243 # data checking routines
249 $self->ut_numbern('msgnum')
250 || $self->ut_text('msgname')
251 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
252 || $self->ut_textn('mime_type')
253 || $self->ut_enum('disabled', [ '', 'Y', 'D', 'S' ] )
254 || $self->ut_textn('from_addr')
255 || $self->ut_textn('bcc_addr')
256 # fine for now, but change this to some kind of dynamic check if we
257 # ever have more than two msgclasses
258 || $self->ut_enum('msgclass', [ qw(email http) ]),
260 return $error if $error;
262 $self->mime_type('text/html') unless $self->mime_type;
267 =item prepare OPTION => VALUE
269 Fills in the template and returns an L<FS::cust_msg> object, containing the
270 message to be sent. This method must be provided by the subclass.
272 Options are passed as a list of name/value pairs:
282 Additional context object (currently, can be a cust_main, cust_pkg,
283 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
284 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
285 used for substitution.
287 As a special case, this may be an arrayref of two objects. Both
288 objects will be available for substitution, with their field names
289 prefixed with 'new_' and 'old_' respectively. This is used in the
290 rt_ticket export when exporting "replace" events.
294 Configuration option to use as the source address, based on the customer's
295 agentnum. If unspecified (or the named option is empty), 'invoice_from'
298 The I<from_addr> field in the template takes precedence over this.
302 Destination address. The default is to use the customer's
303 invoicing_list addresses. Multiple addresses may be comma-separated.
307 A hash reference of additional substitutions
317 =item prepare_substitutions OPTION => VALUE ...
319 Takes the same arguments as L</prepare>, and returns a hashref of the
320 substitution variables.
324 sub prepare_substitutions {
325 my( $self, %opt ) = @_;
327 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
328 my $object = $opt{'object'}; # or die 'object required';
330 warn "preparing substitutions for '".$self->msgname."'\n"
333 my $subs = $self->substitutions;
336 # create substitution table
340 push @objects, $cust_main if $cust_main;
344 if( ref($object) eq 'ARRAY' ) {
345 # [new, old], for provisioning tickets
346 push @objects, $object->[0], $object->[1];
347 push @prefixes, 'new_', 'old_';
348 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
351 push @objects, $object;
353 $svc = $object if $object->isa('FS::svc_Common');
357 push @objects, $svc->cust_svc->cust_pkg;
361 foreach my $obj (@objects) {
362 my $prefix = shift @prefixes;
363 foreach my $name (@{ $subs->{$obj->table} }) {
366 $hash{$prefix.$name} = $obj->$name();
368 elsif( ref($name) eq 'ARRAY' ) {
369 # [ foo => sub { ... } ]
370 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
373 warn "bad msg_template substitution: '$name'\n";
379 if ( $opt{substitutions} ) {
380 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
386 =item send OPTION => VALUE ...
388 Creates a message with L</prepare> (taking all the same options) and sends it.
394 my $cust_msg = $self->prepare(@_);
395 $self->send_prepared($cust_msg);
398 =item render OPTION => VALUE ...
400 Fills in the template and renders it to a PDF document. Returns the
401 name of the PDF file.
403 Options are as for 'prepare', but 'from' and 'to' are meaningless.
407 # XXX not sure where this ends up post-refactoring--a separate template
408 # class? it doesn't use the same rendering OR output machinery as ::email
410 # will also have options to set paper size, margins, etc.
414 eval "use PDF::WebKit";
417 my %hash = $self->prepare(%opt);
418 my $html = $hash{'html_body'};
420 # Graphics/stylesheets should probably go in /var/www on the Freeside
422 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
424 my $kit = PDF::WebKit->new(\$html); #%options
425 # hack to use our wrapper script
426 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
433 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
438 my( $self, %opt ) = @_;
439 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
442 # helper sub for package dates
443 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
445 # helper sub for money amounts
446 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
448 # helper sub for usage-related messages
449 my $usage_warning = sub {
451 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
452 my $amount = $svc->$col; next if $amount eq '';
453 my $method = $col.'_threshold';
454 my $threshold = $svc->$method; next if $threshold eq '';
455 return [$col, $amount, $threshold] if $amount <= $threshold;
456 # this only returns the first one that's below threshold, if there are
462 #return contexts and fill-in values
463 # If you add anything, be sure to add a description in
464 # httemplate/edit/msg_template.html.
466 my $payinfo_sub = sub {
468 ($obj->payby eq 'CARD' || $obj->payby eq 'CHEK')
470 : $obj->decrypt($obj->payinfo)
472 my $payinfo_end = sub {
474 my $payinfo = &$payinfo_sub($obj);
475 substr($payinfo, -4);
477 { 'cust_main' => [qw(
478 display_custnum agentnum agent_name
481 name name_short contact contact_firstlast
482 address1 address2 city county state zip
484 daytime night mobile fax
487 ship_name ship_name_short ship_contact ship_contact_firstlast
488 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
491 paymask payname paytype payip
492 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
493 classname categoryname
496 invoicing_list_emailonly
497 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
502 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
503 #compatibility: obsolete ship_ fields - use the non-ship versions
506 [ "ship_$field" => sub { shift->$field } ]
508 qw( last first company daytime night fax )
510 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
512 [ expdate => sub { shift->paydate_epoch } ], #compatibility
513 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
514 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
515 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
516 [ otaker_first => sub { shift->access_user->first } ],
517 [ otaker_last => sub { shift->access_user->last } ],
518 [ payby => sub { FS::payby->shortname(shift->payby) } ],
519 [ company_name => sub {
520 $conf->config('company_name', shift->agentnum)
522 [ company_address => sub {
523 $conf->config('company_address', shift->agentnum)
525 [ company_phonenum => sub {
526 $conf->config('company_phonenum', shift->agentnum)
528 [ selfservice_server_base_url => sub {
529 $conf->config('selfservice_server-base_url') #, shift->agentnum)
534 pkgnum pkg_label pkg_label_long
538 start_date setup bill last_bill
542 [ pkg => sub { shift->part_pkg->pkg } ],
543 [ pkg_category => sub { shift->part_pkg->categoryname } ],
544 [ pkg_class => sub { shift->part_pkg->classname } ],
545 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
546 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
547 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
548 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
549 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
550 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
551 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
552 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
553 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
555 # not necessarily correct for non-flat packages
556 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
557 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
559 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
568 [ due_date2str => sub { shift->due_date2str('short') } ],
570 #XXX not really thinking about cust_bill substitutions quite yet
572 # for welcome and limit warning messages
578 [ password => sub { shift->getfield('_password') } ],
579 [ column => sub { &$usage_warning(shift)->[0] } ],
580 [ amount => sub { &$usage_warning(shift)->[1] } ],
581 [ threshold => sub { &$usage_warning(shift)->[2] } ],
588 my $registrar = qsearchs('registrar',
589 { registrarnum => shift->registrarnum} );
590 $registrar ? $registrar->registrarname : ''
594 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
595 $svc_acct ? $svc_acct->email : ''
606 'svc_broadband' => [qw(
614 # for payment receipts
619 [ paid => sub { sprintf("%.2f", shift->paid) } ],
620 # overrides the one in cust_main in cases where a cust_pay is passed
621 [ payby => sub { FS::payby->shortname(shift->payby) } ],
622 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
623 [ 'payinfo' => $payinfo_sub ],
624 [ 'payinfo_end' => $payinfo_end ],
626 # for refund receipts
629 [ refund => sub { sprintf("%.2f", shift->refund) } ],
630 [ payby => sub { FS::payby->shortname(shift->payby) } ],
631 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
632 [ 'payinfo' => $payinfo_sub ],
633 [ 'payinfo_end' => $payinfo_end ],
635 # for payment decline messages
636 # try to support all cust_pay fields
637 # 'error' is a special case, it contains the raw error from the gateway
638 'cust_pay_pending' => [qw(
642 [ paid => sub { sprintf("%.2f", shift->paid) } ],
643 [ payby => sub { FS::payby->shortname(shift->payby) } ],
644 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
645 [ 'payinfo' => $payinfo_sub ],
646 [ 'payinfo_end' => $payinfo_end ],
653 Stub, returns nothing.
661 Returns the L<FS::agent> object for this template.
666 my ($self, %opts) = @_;
669 # First move any historical templates in config to real message templates
673 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
674 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
675 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
676 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
677 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
678 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '', 'welcome_email-mimetype' ],
679 [ 'threshold_warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', 'warning_email-cc', 'warning_email-mimetype' ],
682 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
683 foreach my $agentnum (@agentnums) {
685 my ($newname, $oldname, $subject, $from, $bcc, $mimetype) = @$_;
687 if ($conf->exists($oldname, $agentnum)) {
688 my $new = new FS::msg_template({
689 'msgclass' => 'email',
690 'msgname' => $oldname,
691 'agentnum' => $agentnum,
692 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
693 'bcc_addr' => ($bcc && $conf->config($bcc, $agentnum)) || '',
694 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
695 'mime_type' => 'text/html',
696 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
698 my $error = $new->insert;
699 die $error if $error;
700 $conf->set($newname, $new->msgnum, $agentnum);
701 $conf->delete($oldname, $agentnum);
702 $conf->delete($from, $agentnum) if $from;
703 $conf->delete($subject, $agentnum) if $subject;
704 $conf->delete($bcc, $agentnum) if $bcc;
705 $conf->delete($mimetype, $agentnum) if $mimetype;
709 if ( $conf->exists('alert_expiration', $agentnum) ) {
710 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
711 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
713 warn "template for alerter_msgnum $msgnum not found\n";
716 # this is now a set of billing events
717 foreach my $days (30, 15, 5) {
718 my $event = FS::part_event->new({
719 'agentnum' => $agentnum,
720 'event' => "Card expiration warning - $days days",
721 'eventtable' => 'cust_main',
722 'check_freq' => '1d',
723 'action' => 'notice',
724 'disabled' => 'Y', #initialize first
726 my $error = $event->insert( 'msgnum' => $msgnum );
728 warn "error creating expiration alert event:\n$error\n\n";
731 # make it work like before:
732 # only send each warning once before the card expires,
733 # only warn active customers,
734 # only warn customers with CARD/DCRD,
735 # only warn customers who get email invoices
737 'once_every' => { 'run_delay' => '30d' },
738 'cust_paydate_within' => { 'within' => $days.'d' },
739 'cust_status' => { 'status' => { 'active' => 1 } },
740 'payby' => { 'payby' => { 'CARD' => 1,
743 'message_email' => {},
745 foreach (keys %conds) {
746 my $condition = FS::part_event_condition->new({
747 'conditionname' => $_,
748 'eventpart' => $event->eventpart,
750 $error = $condition->insert( %{ $conds{$_} });
752 warn "error creating expiration alert event:\n$error\n\n";
756 $error = $event->initialize;
758 warn "expiration alert event was created, but not initialized:\n$error\n\n";
761 $conf->delete('alerter_msgnum', $agentnum);
762 $conf->delete('alert_expiration', $agentnum);
764 } # if alerter_msgnum
769 # Move subject and body from msg_template to template_content
772 foreach my $msg_template ( qsearch('msg_template', {}) ) {
773 if ( $msg_template->subject || $msg_template->body ) {
774 # create new default content
776 $content{subject} = $msg_template->subject;
777 $msg_template->set('subject', '');
779 # work around obscure Pg/DBD bug
780 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
781 # (though the right fix is to upgrade DBD)
782 my $body = $msg_template->body;
783 if ( $body =~ /^x([0-9a-f]+)$/ ) {
784 # there should be no real message templates that look like that
785 warn "converting template body to TEXT\n";
786 $body = pack('H*', $1);
788 $content{body} = $body;
789 $msg_template->set('body', '');
790 my $error = $msg_template->replace(%content);
791 die $error if $error;
794 if ( !$msg_template->msgclass ) {
795 # set default message class
796 $msg_template->set('msgclass', 'email');
797 my $error = $msg_template->replace;
798 die $error if $error;
803 # Add new-style default templates if missing
805 $self->_populate_initial_data;
808 # Move welcome_msgnum to an export
811 #upgrade_journal loaded by _populate_initial_data
812 unless (FS::upgrade_journal->is_done('msg_template__welcome_export')) {
813 if (my $msgnum = $conf->config('welcome_msgnum')) {
814 eval "use FS::part_export;";
816 eval "use FS::part_svc;";
818 eval "use FS::export_svc;";
821 my $part_export = new FS::part_export {
822 'exportname' => 'Welcome Email',
823 'exporttype' => 'send_email'
825 my $error = $part_export->insert({
827 'insert_template' => $msgnum,
828 # replicate blank options that would be generated by UI,
829 # to avoid unexpected results from not having them exist
831 'replace_template' => 0,
832 'suspend_template' => 0,
833 'unsuspend_template' => 0,
834 'delete_template' => 0,
836 die $error if $error;
837 #attach it to part_svcs
838 my @welcome_exclude_svcparts = $conf->config('svc_acct_welcome_exclude');
839 foreach my $part_svc (
840 qsearch('part_svc',{ 'svcdb' => 'svc_acct', 'disabled' => '' })
842 next if grep { $_ eq $part_svc->svcpart } @welcome_exclude_svcparts;
843 my $export_svc = new FS::export_svc {
844 'exportnum' => $part_export->exportnum,
845 'svcpart' => $part_svc->svcpart,
847 $error = $export_svc->insert;
848 die $error if $error;
850 #remove the old confs
851 $error = $conf->delete('welcome_msgnum');
852 die $error if $error;
853 $error = $conf->delete('svc_acct_welcome_exclude');
854 die $error if $error;
856 FS::upgrade_journal->set_done('msg_template__welcome_export');
860 ### Fix dump-email_to (needs to happen after _populate_initial_data)
861 if ($conf->config('dump-email_to')) {
862 # anyone who still uses dump-email_to should have just had this created
863 my ($msg_template) = qsearch('msg_template',{ msgname => 'System log' });
865 eval "use FS::log_email;";
867 my $log_email = new FS::log_email {
868 'context' => 'Cron::backup',
870 'msgnum' => $msg_template->msgnum,
871 'to_addr' => $conf->config('dump-email_to'),
873 my $error = $log_email->insert;
874 die $error if $error;
875 $conf->delete('dump-email_to');
881 sub _populate_initial_data { #class method
882 #my($class, %opts) = @_;
885 eval "use FS::msg_template::InitialData;";
887 eval "use FS::upgrade_journal;";
890 my $initial_data = FS::msg_template::InitialData->_initial_data;
892 foreach my $hash ( @$initial_data ) {
894 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
895 next if $hash->{_upgrade_journal} && FS::upgrade_journal->is_done( $hash->{_upgrade_journal} );
897 my $msg_template = new FS::msg_template($hash);
898 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
899 die $error if $error;
901 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
902 FS::upgrade_journal->set_done( $hash->{_upgrade_journal} ) if $hash->{_upgrade_journal};
914 L<FS::Record>, schema.html from the base documentation.