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 ('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 sub extension_table { ''; } # subclasses don't HAVE to have extensions
94 my $class = 'FS::msg_template::' . $self->msgclass;
96 bless($self, $class) unless $@;
98 # merge in the extension fields (but let fields in $self override them)
99 # except don't ever override the extension's primary key, it's immutable
100 if ( $self->msgnum and $self->extension_table ) {
101 my $extension = $self->_extension;
103 my $ext_key = $extension->get($extension->primary_key);
104 $self->{Hash} = { $extension->hash,
106 $extension->primary_key => $ext_key
114 # Returns the subclass-specific extension record for this object. For internal
115 # use only; everyone else is supposed to think of this as a single record.
119 if ( $self->extension_table and $self->msgnum ) {
120 local $FS::Record::nowarn_classload = 1;
121 return qsearchs($self->extension_table, { msgnum => $self->msgnum });
126 =item insert [ CONTENT ]
128 Adds this record to the database. If there is an error, returns the error,
129 otherwise returns false.
137 my $oldAutoCommit = $FS::UID::AutoCommit;
138 local $FS::UID::AutoCommit = 0;
140 my $error = $self->SUPER::insert;
141 # calling _extension at this point makes it copy the msgnum, so links work
142 if ( $self->extension_table ) {
143 local $FS::Record::nowarn_classload = 1;
144 my $extension = FS::Record->new($self->extension_table, { $self->hash });
145 $error ||= $extension->insert;
149 dbh->rollback if $oldAutoCommit;
151 dbh->commit if $oldAutoCommit;
158 Delete this record from the database.
165 my $oldAutoCommit = $FS::UID::AutoCommit;
166 local $FS::UID::AutoCommit = 0;
169 my $extension = $self->_extension;
171 $error = $extension->delete;
174 $error ||= $self->SUPER::delete;
177 dbh->rollback if $oldAutoCommit;
179 dbh->commit if $oldAutoCommit;
184 =item replace [ OLD_RECORD ]
186 Replaces the OLD_RECORD with this one in the database. If there is an error,
187 returns the error, otherwise returns false.
193 my $old = shift || $new->replace_old;
195 my $oldAutoCommit = $FS::UID::AutoCommit;
196 local $FS::UID::AutoCommit = 0;
198 my $error = $new->SUPER::replace($old, @_);
200 my $extension = $new->_extension;
202 # merge changes into the extension record and replace it
203 $extension->{Hash} = { $extension->hash, $new->hash };
204 $error ||= $extension->replace;
208 dbh->rollback if $oldAutoCommit;
210 dbh->commit if $oldAutoCommit;
217 my $old = $self->replace_old;
218 # don't allow changing msgclass, except null to not-null (for upgrade)
219 if ( $old->msgclass ) {
220 if ( !$self->msgclass ) {
221 $self->set('msgclass', $old->msgclass);
222 } elsif ( $old->msgclass ne $self->msgclass ) {
223 return "Can't change message template class from ".$old->msgclass.
224 " to ".$self->msgclass.".";
232 Checks all fields to make sure this is a valid template. If there is
233 an error, returns the error, otherwise returns false. Called by the insert
238 # the check method should currently be supplied - FS::Record contains some
239 # data checking routines
245 $self->ut_numbern('msgnum')
246 || $self->ut_text('msgname')
247 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
248 || $self->ut_textn('mime_type')
249 || $self->ut_enum('disabled', [ '', 'Y' ] )
250 || $self->ut_textn('from_addr')
251 || $self->ut_textn('bcc_addr')
252 # fine for now, but change this to some kind of dynamic check if we
253 # ever have more than two msgclasses
254 || $self->ut_enum('msgclass', [ qw(email http) ]),
256 return $error if $error;
258 $self->mime_type('text/html') unless $self->mime_type;
263 =item prepare OPTION => VALUE
265 Fills in the template and returns an L<FS::cust_msg> object, containing the
266 message to be sent. This method must be provided by the subclass.
268 Options are passed as a list of name/value pairs:
274 Customer object (required).
278 Additional context object (currently, can be a cust_main, cust_pkg,
279 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
280 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
281 used for substitution.
283 As a special case, this may be an arrayref of two objects. Both
284 objects will be available for substitution, with their field names
285 prefixed with 'new_' and 'old_' respectively. This is used in the
286 rt_ticket export when exporting "replace" events.
290 Configuration option to use as the source address, based on the customer's
291 agentnum. If unspecified (or the named option is empty), 'invoice_from'
294 The I<from_addr> field in the template takes precedence over this.
298 Destination address. The default is to use the customer's
299 invoicing_list addresses. Multiple addresses may be comma-separated.
303 A hash reference of additional substitutions
313 =item prepare_substitutions OPTION => VALUE ...
315 Takes the same arguments as L</prepare>, and returns a hashref of the
316 substitution variables.
320 sub prepare_substitutions {
321 my( $self, %opt ) = @_;
323 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
324 my $object = $opt{'object'} or die 'object required';
326 warn "preparing substitutions for '".$self->msgname."'\n"
329 my $subs = $self->substitutions;
332 # create substitution table
336 push @objects, $cust_main if $cust_main;
340 if( ref($object) eq 'ARRAY' ) {
341 # [new, old], for provisioning tickets
342 push @objects, $object->[0], $object->[1];
343 push @prefixes, 'new_', 'old_';
344 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
347 push @objects, $object;
349 $svc = $object if $object->isa('FS::svc_Common');
353 push @objects, $svc->cust_svc->cust_pkg;
357 foreach my $obj (@objects) {
358 my $prefix = shift @prefixes;
359 foreach my $name (@{ $subs->{$obj->table} }) {
362 $hash{$prefix.$name} = $obj->$name();
364 elsif( ref($name) eq 'ARRAY' ) {
365 # [ foo => sub { ... } ]
366 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
369 warn "bad msg_template substitution: '$name'\n";
375 if ( $opt{substitutions} ) {
376 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
382 =item send OPTION => VALUE ...
384 Creates a message with L</prepare> (taking all the same options) and sends it.
390 my $cust_msg = $self->prepare(@_);
391 $self->send_prepared($cust_msg);
394 =item render OPTION => VALUE ...
396 Fills in the template and renders it to a PDF document. Returns the
397 name of the PDF file.
399 Options are as for 'prepare', but 'from' and 'to' are meaningless.
403 # XXX not sure where this ends up post-refactoring--a separate template
404 # class? it doesn't use the same rendering OR output machinery as ::email
406 # will also have options to set paper size, margins, etc.
410 eval "use PDF::WebKit";
413 my %hash = $self->prepare(%opt);
414 my $html = $hash{'html_body'};
416 # Graphics/stylesheets should probably go in /var/www on the Freeside
418 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
420 my $kit = PDF::WebKit->new(\$html); #%options
421 # hack to use our wrapper script
422 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
429 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
434 my( $self, %opt ) = @_;
435 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
438 # helper sub for package dates
439 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
441 # helper sub for money amounts
442 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
444 # helper sub for usage-related messages
445 my $usage_warning = sub {
447 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
448 my $amount = $svc->$col; next if $amount eq '';
449 my $method = $col.'_threshold';
450 my $threshold = $svc->$method; next if $threshold eq '';
451 return [$col, $amount, $threshold] if $amount <= $threshold;
452 # this only returns the first one that's below threshold, if there are
458 #return contexts and fill-in values
459 # If you add anything, be sure to add a description in
460 # httemplate/edit/msg_template.html.
462 { 'cust_main' => [qw(
463 display_custnum agentnum agent_name
466 name name_short contact contact_firstlast
467 address1 address2 city county state zip
469 daytime night mobile fax
472 ship_name ship_name_short ship_contact ship_contact_firstlast
473 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
476 paymask payname paytype payip
477 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
478 classname categoryname
481 invoicing_list_emailonly
482 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
487 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
488 #compatibility: obsolete ship_ fields - use the non-ship versions
491 [ "ship_$field" => sub { shift->$field } ]
493 qw( last first company daytime night fax )
495 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
497 [ expdate => sub { shift->paydate_epoch } ], #compatibility
498 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
499 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
500 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
501 [ otaker_first => sub { shift->access_user->first } ],
502 [ otaker_last => sub { shift->access_user->last } ],
503 [ payby => sub { FS::payby->shortname(shift->payby) } ],
504 [ company_name => sub {
505 $conf->config('company_name', shift->agentnum)
507 [ company_address => sub {
508 $conf->config('company_address', shift->agentnum)
510 [ company_phonenum => sub {
511 $conf->config('company_phonenum', shift->agentnum)
513 [ selfservice_server_base_url => sub {
514 $conf->config('selfservice_server-base_url') #, shift->agentnum)
519 pkgnum pkg_label pkg_label_long
523 start_date setup bill last_bill
527 [ pkg => sub { shift->part_pkg->pkg } ],
528 [ pkg_category => sub { shift->part_pkg->categoryname } ],
529 [ pkg_class => sub { shift->part_pkg->classname } ],
530 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
531 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
532 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
533 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
534 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
535 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
536 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
537 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
538 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
540 # not necessarily correct for non-flat packages
541 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
542 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
544 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
553 [ due_date2str => sub { shift->due_date2str('short') } ],
555 #XXX not really thinking about cust_bill substitutions quite yet
557 # for welcome and limit warning messages
563 [ password => sub { shift->getfield('_password') } ],
564 [ column => sub { &$usage_warning(shift)->[0] } ],
565 [ amount => sub { &$usage_warning(shift)->[1] } ],
566 [ threshold => sub { &$usage_warning(shift)->[2] } ],
573 my $registrar = qsearchs('registrar',
574 { registrarnum => shift->registrarnum} );
575 $registrar ? $registrar->registrarname : ''
579 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
580 $svc_acct ? $svc_acct->email : ''
591 'svc_broadband' => [qw(
599 # for payment receipts
604 [ paid => sub { sprintf("%.2f", shift->paid) } ],
605 # overrides the one in cust_main in cases where a cust_pay is passed
606 [ payby => sub { FS::payby->shortname(shift->payby) } ],
607 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
609 my $cust_pay = shift;
610 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
611 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
614 # for payment decline messages
615 # try to support all cust_pay fields
616 # 'error' is a special case, it contains the raw error from the gateway
617 'cust_pay_pending' => [qw(
621 [ paid => sub { sprintf("%.2f", shift->paid) } ],
622 [ payby => sub { FS::payby->shortname(shift->payby) } ],
623 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
626 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
627 $pending->paymask : $pending->decrypt($pending->payinfo)
635 Stub, returns nothing.
643 Returns the L<FS::agent> object for this template.
648 my ($self, %opts) = @_;
651 # First move any historical templates in config to real message templates
655 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
656 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
657 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
658 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
659 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
660 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
661 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
664 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
665 foreach my $agentnum (@agentnums) {
667 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
668 if ($conf->exists($oldname, $agentnum)) {
669 my $new = new FS::msg_template({
670 'msgname' => $oldname,
671 'agentnum' => $agentnum,
672 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
673 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
674 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
675 'mime_type' => 'text/html',
676 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
678 my $error = $new->insert;
679 die $error if $error;
680 $conf->set($newname, $new->msgnum, $agentnum);
681 $conf->delete($oldname, $agentnum);
682 $conf->delete($from, $agentnum) if $from;
683 $conf->delete($subject, $agentnum) if $subject;
687 if ( $conf->exists('alert_expiration', $agentnum) ) {
688 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
689 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
691 warn "template for alerter_msgnum $msgnum not found\n";
694 # this is now a set of billing events
695 foreach my $days (30, 15, 5) {
696 my $event = FS::part_event->new({
697 'agentnum' => $agentnum,
698 'event' => "Card expiration warning - $days days",
699 'eventtable' => 'cust_main',
700 'check_freq' => '1d',
701 'action' => 'notice',
702 'disabled' => 'Y', #initialize first
704 my $error = $event->insert( 'msgnum' => $msgnum );
706 warn "error creating expiration alert event:\n$error\n\n";
709 # make it work like before:
710 # only send each warning once before the card expires,
711 # only warn active customers,
712 # only warn customers with CARD/DCRD,
713 # only warn customers who get email invoices
715 'once_every' => { 'run_delay' => '30d' },
716 'cust_paydate_within' => { 'within' => $days.'d' },
717 'cust_status' => { 'status' => { 'active' => 1 } },
718 'payby' => { 'payby' => { 'CARD' => 1,
721 'message_email' => {},
723 foreach (keys %conds) {
724 my $condition = FS::part_event_condition->new({
725 'conditionname' => $_,
726 'eventpart' => $event->eventpart,
728 $error = $condition->insert( %{ $conds{$_} });
730 warn "error creating expiration alert event:\n$error\n\n";
734 $error = $event->initialize;
736 warn "expiration alert event was created, but not initialized:\n$error\n\n";
739 $conf->delete('alerter_msgnum', $agentnum);
740 $conf->delete('alert_expiration', $agentnum);
742 } # if alerter_msgnum
747 # Move subject and body from msg_template to template_content
750 foreach my $msg_template ( qsearch('msg_template', {}) ) {
751 if ( $msg_template->subject || $msg_template->body ) {
752 # create new default content
754 $content{subject} = $msg_template->subject;
755 $msg_template->set('subject', '');
757 # work around obscure Pg/DBD bug
758 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
759 # (though the right fix is to upgrade DBD)
760 my $body = $msg_template->body;
761 if ( $body =~ /^x([0-9a-f]+)$/ ) {
762 # there should be no real message templates that look like that
763 warn "converting template body to TEXT\n";
764 $body = pack('H*', $1);
766 $content{body} = $body;
767 $msg_template->set('body', '');
768 my $error = $msg_template->replace(%content);
769 die $error if $error;
772 if ( !$msg_template->msgclass ) {
773 # set default message class
774 $msg_template->set('msgclass', 'email');
775 my $error = $msg_template->replace;
776 die $error if $error;
781 # Add new-style default templates if missing
783 $self->_populate_initial_data;
787 sub _populate_initial_data { #class method
788 #my($class, %opts) = @_;
791 eval "use FS::msg_template::InitialData;";
794 my $initial_data = FS::msg_template::InitialData->_initial_data;
796 foreach my $hash ( @$initial_data ) {
798 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
800 my $msg_template = new FS::msg_template($hash);
801 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
802 die $error if $error;
804 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
816 L<FS::Record>, schema.html from the base documentation.