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 $@;
97 warn "Error loading msg_template msgclass: " . $@ if $@; #or die?
99 # merge in the extension fields (but let fields in $self override them)
100 # except don't ever override the extension's primary key, it's immutable
101 if ( $self->msgnum and $self->extension_table ) {
102 my $extension = $self->_extension;
104 my $ext_key = $extension->get($extension->primary_key);
105 $self->{Hash} = { $extension->hash,
107 $extension->primary_key => $ext_key
115 # Returns the subclass-specific extension record for this object. For internal
116 # use only; everyone else is supposed to think of this as a single record.
120 if ( $self->extension_table and $self->msgnum ) {
121 local $FS::Record::nowarn_classload = 1;
122 return qsearchs($self->extension_table, { msgnum => $self->msgnum });
127 =item insert [ CONTENT ]
129 Adds this record to the database. If there is an error, returns the error,
130 otherwise returns false.
138 my $oldAutoCommit = $FS::UID::AutoCommit;
139 local $FS::UID::AutoCommit = 0;
141 my $error = $self->SUPER::insert;
142 # calling _extension at this point makes it copy the msgnum, so links work
143 if ( $self->extension_table ) {
144 local $FS::Record::nowarn_classload = 1;
145 my $extension = FS::Record->new($self->extension_table, { $self->hash });
146 $error ||= $extension->insert;
150 dbh->rollback if $oldAutoCommit;
152 dbh->commit if $oldAutoCommit;
159 Delete this record from the database.
166 my $oldAutoCommit = $FS::UID::AutoCommit;
167 local $FS::UID::AutoCommit = 0;
170 my $extension = $self->_extension;
172 $error = $extension->delete;
175 $error ||= $self->SUPER::delete;
178 dbh->rollback if $oldAutoCommit;
180 dbh->commit if $oldAutoCommit;
185 =item replace [ OLD_RECORD ]
187 Replaces the OLD_RECORD with this one in the database. If there is an error,
188 returns the error, otherwise returns false.
194 my $old = shift || $new->replace_old;
196 my $oldAutoCommit = $FS::UID::AutoCommit;
197 local $FS::UID::AutoCommit = 0;
199 my $error = $new->SUPER::replace($old, @_);
201 my $extension = $new->_extension;
203 # merge changes into the extension record and replace it
204 $extension->{Hash} = { $extension->hash, $new->hash };
205 $error ||= $extension->replace;
209 dbh->rollback if $oldAutoCommit;
211 dbh->commit if $oldAutoCommit;
218 my $old = $self->replace_old;
219 # don't allow changing msgclass, except null to not-null (for upgrade)
220 if ( $old->msgclass ) {
221 if ( !$self->msgclass ) {
222 $self->set('msgclass', $old->msgclass);
223 } elsif ( $old->msgclass ne $self->msgclass ) {
224 return "Can't change message template class from ".$old->msgclass.
225 " to ".$self->msgclass.".";
233 Checks all fields to make sure this is a valid template. If there is
234 an error, returns the error, otherwise returns false. Called by the insert
239 # the check method should currently be supplied - FS::Record contains some
240 # data checking routines
246 $self->ut_numbern('msgnum')
247 || $self->ut_text('msgname')
248 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
249 || $self->ut_textn('mime_type')
250 || $self->ut_enum('disabled', [ '', 'Y' ] )
251 || $self->ut_textn('from_addr')
252 || $self->ut_textn('bcc_addr')
253 # fine for now, but change this to some kind of dynamic check if we
254 # ever have more than two msgclasses
255 || $self->ut_enum('msgclass', [ qw(email http) ]),
257 return $error if $error;
259 $self->mime_type('text/html') unless $self->mime_type;
264 =item prepare OPTION => VALUE
266 Fills in the template and returns an L<FS::cust_msg> object, containing the
267 message to be sent. This method must be provided by the subclass.
269 Options are passed as a list of name/value pairs:
275 Customer object (required).
279 Additional context object (currently, can be a cust_main, cust_pkg,
280 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
281 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
282 used for substitution.
284 As a special case, this may be an arrayref of two objects. Both
285 objects will be available for substitution, with their field names
286 prefixed with 'new_' and 'old_' respectively. This is used in the
287 rt_ticket export when exporting "replace" events.
291 Configuration option to use as the source address, based on the customer's
292 agentnum. If unspecified (or the named option is empty), 'invoice_from'
295 The I<from_addr> field in the template takes precedence over this.
299 Destination address. The default is to use the customer's
300 invoicing_list addresses. Multiple addresses may be comma-separated.
304 A hash reference of additional substitutions
314 =item prepare_substitutions OPTION => VALUE ...
316 Takes the same arguments as L</prepare>, and returns a hashref of the
317 substitution variables.
321 sub prepare_substitutions {
322 my( $self, %opt ) = @_;
324 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
325 my $object = $opt{'object'} or die 'object required';
327 warn "preparing substitutions for '".$self->msgname."'\n"
330 my $subs = $self->substitutions;
333 # create substitution table
337 push @objects, $cust_main if $cust_main;
341 if( ref($object) eq 'ARRAY' ) {
342 # [new, old], for provisioning tickets
343 push @objects, $object->[0], $object->[1];
344 push @prefixes, 'new_', 'old_';
345 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
348 push @objects, $object;
350 $svc = $object if $object->isa('FS::svc_Common');
354 push @objects, $svc->cust_svc->cust_pkg;
358 foreach my $obj (@objects) {
359 my $prefix = shift @prefixes;
360 foreach my $name (@{ $subs->{$obj->table} }) {
363 $hash{$prefix.$name} = $obj->$name();
365 elsif( ref($name) eq 'ARRAY' ) {
366 # [ foo => sub { ... } ]
367 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
370 warn "bad msg_template substitution: '$name'\n";
376 if ( $opt{substitutions} ) {
377 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
383 =item send OPTION => VALUE ...
385 Creates a message with L</prepare> (taking all the same options) and sends it.
391 my $cust_msg = $self->prepare(@_);
392 $self->send_prepared($cust_msg);
395 =item render OPTION => VALUE ...
397 Fills in the template and renders it to a PDF document. Returns the
398 name of the PDF file.
400 Options are as for 'prepare', but 'from' and 'to' are meaningless.
404 # XXX not sure where this ends up post-refactoring--a separate template
405 # class? it doesn't use the same rendering OR output machinery as ::email
407 # will also have options to set paper size, margins, etc.
411 eval "use PDF::WebKit";
414 my %hash = $self->prepare(%opt);
415 my $html = $hash{'html_body'};
417 # Graphics/stylesheets should probably go in /var/www on the Freeside
419 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
421 my $kit = PDF::WebKit->new(\$html); #%options
422 # hack to use our wrapper script
423 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
430 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
435 my( $self, %opt ) = @_;
436 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
439 # helper sub for package dates
440 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
442 # helper sub for money amounts
443 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
445 # helper sub for usage-related messages
446 my $usage_warning = sub {
448 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
449 my $amount = $svc->$col; next if $amount eq '';
450 my $method = $col.'_threshold';
451 my $threshold = $svc->$method; next if $threshold eq '';
452 return [$col, $amount, $threshold] if $amount <= $threshold;
453 # this only returns the first one that's below threshold, if there are
459 #return contexts and fill-in values
460 # If you add anything, be sure to add a description in
461 # httemplate/edit/msg_template.html.
463 { 'cust_main' => [qw(
464 display_custnum agentnum agent_name
467 name name_short contact contact_firstlast
468 address1 address2 city county state zip
470 daytime night mobile fax
473 ship_name ship_name_short ship_contact ship_contact_firstlast
474 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
477 paymask payname paytype payip
478 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
479 classname categoryname
482 invoicing_list_emailonly
483 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
488 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
489 #compatibility: obsolete ship_ fields - use the non-ship versions
492 [ "ship_$field" => sub { shift->$field } ]
494 qw( last first company daytime night fax )
496 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
498 [ expdate => sub { shift->paydate_epoch } ], #compatibility
499 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
500 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
501 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
502 [ otaker_first => sub { shift->access_user->first } ],
503 [ otaker_last => sub { shift->access_user->last } ],
504 [ payby => sub { FS::payby->shortname(shift->payby) } ],
505 [ company_name => sub {
506 $conf->config('company_name', shift->agentnum)
508 [ company_address => sub {
509 $conf->config('company_address', shift->agentnum)
511 [ company_phonenum => sub {
512 $conf->config('company_phonenum', shift->agentnum)
514 [ selfservice_server_base_url => sub {
515 $conf->config('selfservice_server-base_url') #, shift->agentnum)
520 pkgnum pkg_label pkg_label_long
524 start_date setup bill last_bill
528 [ pkg => sub { shift->part_pkg->pkg } ],
529 [ pkg_category => sub { shift->part_pkg->categoryname } ],
530 [ pkg_class => sub { shift->part_pkg->classname } ],
531 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
532 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
533 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
534 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
535 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
536 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
537 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
538 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
539 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
541 # not necessarily correct for non-flat packages
542 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
543 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
545 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
554 [ due_date2str => sub { shift->due_date2str('short') } ],
556 #XXX not really thinking about cust_bill substitutions quite yet
558 # for welcome and limit warning messages
564 [ password => sub { shift->getfield('_password') } ],
565 [ column => sub { &$usage_warning(shift)->[0] } ],
566 [ amount => sub { &$usage_warning(shift)->[1] } ],
567 [ threshold => sub { &$usage_warning(shift)->[2] } ],
574 my $registrar = qsearchs('registrar',
575 { registrarnum => shift->registrarnum} );
576 $registrar ? $registrar->registrarname : ''
580 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
581 $svc_acct ? $svc_acct->email : ''
592 'svc_broadband' => [qw(
600 # for payment receipts
605 [ paid => sub { sprintf("%.2f", shift->paid) } ],
606 # overrides the one in cust_main in cases where a cust_pay is passed
607 [ payby => sub { FS::payby->shortname(shift->payby) } ],
608 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
610 my $cust_pay = shift;
611 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
612 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
615 # for payment decline messages
616 # try to support all cust_pay fields
617 # 'error' is a special case, it contains the raw error from the gateway
618 'cust_pay_pending' => [qw(
622 [ paid => sub { sprintf("%.2f", shift->paid) } ],
623 [ payby => sub { FS::payby->shortname(shift->payby) } ],
624 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
627 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
628 $pending->paymask : $pending->decrypt($pending->payinfo)
636 Stub, returns nothing.
644 Returns the L<FS::agent> object for this template.
649 my ($self, %opts) = @_;
652 # First move any historical templates in config to real message templates
656 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
657 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
658 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
659 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
660 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
661 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '', 'welcome_email-mimetype' ],
662 [ 'threshold_warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', 'warning_email-cc', 'warning_email-mimetype' ],
665 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
666 foreach my $agentnum (@agentnums) {
668 my ($newname, $oldname, $subject, $from, $bcc, $mimetype) = @$_;
670 if ($conf->exists($oldname, $agentnum)) {
671 my $new = new FS::msg_template({
672 'msgclass' => 'email',
673 'msgname' => $oldname,
674 'agentnum' => $agentnum,
675 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
676 'bcc_addr' => ($bcc && $conf->config($bcc, $agentnum)) || '',
677 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
678 'mime_type' => 'text/html',
679 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
681 my $error = $new->insert;
682 die $error if $error;
683 $conf->set($newname, $new->msgnum, $agentnum);
684 $conf->delete($oldname, $agentnum);
685 $conf->delete($from, $agentnum) if $from;
686 $conf->delete($subject, $agentnum) if $subject;
687 $conf->delete($bcc, $agentnum) if $bcc;
688 $conf->delete($mimetype, $agentnum) if $mimetype;
692 if ( $conf->exists('alert_expiration', $agentnum) ) {
693 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
694 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
696 warn "template for alerter_msgnum $msgnum not found\n";
699 # this is now a set of billing events
700 foreach my $days (30, 15, 5) {
701 my $event = FS::part_event->new({
702 'agentnum' => $agentnum,
703 'event' => "Card expiration warning - $days days",
704 'eventtable' => 'cust_main',
705 'check_freq' => '1d',
706 'action' => 'notice',
707 'disabled' => 'Y', #initialize first
709 my $error = $event->insert( 'msgnum' => $msgnum );
711 warn "error creating expiration alert event:\n$error\n\n";
714 # make it work like before:
715 # only send each warning once before the card expires,
716 # only warn active customers,
717 # only warn customers with CARD/DCRD,
718 # only warn customers who get email invoices
720 'once_every' => { 'run_delay' => '30d' },
721 'cust_paydate_within' => { 'within' => $days.'d' },
722 'cust_status' => { 'status' => { 'active' => 1 } },
723 'payby' => { 'payby' => { 'CARD' => 1,
726 'message_email' => {},
728 foreach (keys %conds) {
729 my $condition = FS::part_event_condition->new({
730 'conditionname' => $_,
731 'eventpart' => $event->eventpart,
733 $error = $condition->insert( %{ $conds{$_} });
735 warn "error creating expiration alert event:\n$error\n\n";
739 $error = $event->initialize;
741 warn "expiration alert event was created, but not initialized:\n$error\n\n";
744 $conf->delete('alerter_msgnum', $agentnum);
745 $conf->delete('alert_expiration', $agentnum);
747 } # if alerter_msgnum
752 # Move subject and body from msg_template to template_content
755 foreach my $msg_template ( qsearch('msg_template', {}) ) {
756 if ( $msg_template->subject || $msg_template->body ) {
757 # create new default content
759 $content{subject} = $msg_template->subject;
760 $msg_template->set('subject', '');
762 # work around obscure Pg/DBD bug
763 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
764 # (though the right fix is to upgrade DBD)
765 my $body = $msg_template->body;
766 if ( $body =~ /^x([0-9a-f]+)$/ ) {
767 # there should be no real message templates that look like that
768 warn "converting template body to TEXT\n";
769 $body = pack('H*', $1);
771 $content{body} = $body;
772 $msg_template->set('body', '');
773 my $error = $msg_template->replace(%content);
774 die $error if $error;
777 if ( !$msg_template->msgclass ) {
778 # set default message class
779 $msg_template->set('msgclass', 'email');
780 my $error = $msg_template->replace;
781 die $error if $error;
786 # Add new-style default templates if missing
788 $self->_populate_initial_data;
792 sub _populate_initial_data { #class method
793 #my($class, %opts) = @_;
796 eval "use FS::msg_template::InitialData;";
799 my $initial_data = FS::msg_template::InitialData->_initial_data;
801 foreach my $hash ( @$initial_data ) {
803 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
805 my $msg_template = new FS::msg_template($hash);
806 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
807 die $error if $error;
809 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
821 L<FS::Record>, schema.html from the base documentation.