1 package FS::msg_template;
2 use base qw( FS::Record );
5 use vars qw( $DEBUG $conf );
8 use FS::Record qw( qsearch qsearchs );
11 use FS::template_content;
13 FS::UID->install_callback( sub { $conf = new FS::Conf; } );
19 FS::msg_template - Object methods for msg_template records
25 $record = new FS::msg_template \%hash;
26 $record = new FS::msg_template { 'column' => 'value' };
28 $error = $record->insert;
30 $error = $new_record->replace($old_record);
32 $error = $record->delete;
34 $error = $record->check;
38 An FS::msg_template object represents a customer message template.
39 FS::msg_template inherits from FS::Record. The following fields are currently
44 =item msgnum - primary key
46 =item msgname - Name of the template. This will appear in the user interface;
47 if it needs to be localized for some users, add it to the message catalog.
49 =item msgclass - The L<FS::msg_template> subclass that this should belong to.
52 =item agentnum - Agent associated with this template. Can be NULL for a
55 =item mime_type - MIME type. Defaults to text/html.
57 =item from_addr - Source email address.
59 =item bcc_addr - Bcc all mail to this address.
61 =item disabled - disabled ('Y' or NULL).
71 Creates a new template. To add the template to the database, see L<"insert">.
73 Note that this stores the hash reference, not a distinct copy of the hash it
74 points to. You can ask the object for a copy with the I<hash> method.
78 # the new method can be inherited from FS::Record, if a table method is defined
80 sub table { 'msg_template'; }
84 my $class = 'FS::msg_template::' . $self->msgclass;
86 bless($self, $class) unless $@;
90 =item insert [ CONTENT ]
92 Adds this record to the database. If there is an error, returns the error,
93 otherwise returns false.
99 Delete this record from the database.
105 =item replace [ OLD_RECORD ] [ CONTENT ]
107 Replaces the OLD_RECORD with this one in the database. If there is an error,
108 returns the error, otherwise returns false.
116 my $old = $self->replace_old;
117 # don't allow changing msgclass, except null to not-null (for upgrade)
118 if ( $old->msgclass ) {
119 if ( !$self->msgclass ) {
120 $self->set('msgclass', $old->msgclass);
122 return "Can't change message template class from ".$old->msgclass.
123 " to ".$self->msgclass.".";
131 Checks all fields to make sure this is a valid template. If there is
132 an error, returns the error, otherwise returns false. Called by the insert
137 # the check method should currently be supplied - FS::Record contains some
138 # data checking routines
144 $self->ut_numbern('msgnum')
145 || $self->ut_text('msgname')
146 || $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum')
147 || $self->ut_textn('mime_type')
148 || $self->ut_enum('disabled', [ '', 'Y' ] )
149 || $self->ut_textn('from_addr')
150 || $self->ut_textn('bcc_addr')
151 # fine for now, but change this to some kind of dynamic check if we
152 # ever have more than two msgclasses
153 || $self->ut_enum('msgclass', [ qw(email http) ]),
155 return $error if $error;
157 $self->mime_type('text/html') unless $self->mime_type;
162 =item prepare OPTION => VALUE
164 Fills in the template and returns an L<FS::cust_msg> object, containing the
165 message to be sent. This method must be provided by the subclass.
167 Options are passed as a list of name/value pairs:
173 Customer object (required).
177 Additional context object (currently, can be a cust_main, cust_pkg,
178 cust_bill, cust_pay, cust_pay_pending, or svc_(acct, phone, broadband,
179 domain) ). If the object is a svc_*, its cust_pkg will be fetched and
180 used for substitution.
182 As a special case, this may be an arrayref of two objects. Both
183 objects will be available for substitution, with their field names
184 prefixed with 'new_' and 'old_' respectively. This is used in the
185 rt_ticket export when exporting "replace" events.
189 Configuration option to use as the source address, based on the customer's
190 agentnum. If unspecified (or the named option is empty), 'invoice_from'
193 The I<from_addr> field in the template takes precedence over this.
197 Destination address. The default is to use the customer's
198 invoicing_list addresses. Multiple addresses may be comma-separated.
202 A hash reference of additional substitutions
212 =item prepare_substitutions OPTION => VALUE ...
214 Takes the same arguments as L</prepare>, and returns a hashref of the
215 substitution variables.
219 sub prepare_substitutions {
220 my( $self, %opt ) = @_;
222 my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
223 my $object = $opt{'object'} or die 'object required';
225 warn "preparing substitutions for '".$self->msgname."'\n"
228 my $subs = $self->substitutions;
231 # create substitution table
235 push @objects, $cust_main if $cust_main;
239 if( ref($object) eq 'ARRAY' ) {
240 # [new, old], for provisioning tickets
241 push @objects, $object->[0], $object->[1];
242 push @prefixes, 'new_', 'old_';
243 $svc = $object->[0] if $object->[0]->isa('FS::svc_Common');
246 push @objects, $object;
248 $svc = $object if $object->isa('FS::svc_Common');
252 push @objects, $svc->cust_svc->cust_pkg;
256 foreach my $obj (@objects) {
257 my $prefix = shift @prefixes;
258 foreach my $name (@{ $subs->{$obj->table} }) {
261 $hash{$prefix.$name} = $obj->$name();
263 elsif( ref($name) eq 'ARRAY' ) {
264 # [ foo => sub { ... } ]
265 $hash{$prefix.($name->[0])} = $name->[1]->($obj);
268 warn "bad msg_template substitution: '$name'\n";
274 if ( $opt{substitutions} ) {
275 $hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
281 =item send OPTION => VALUE ...
283 Creates a message with L</prepare> (taking all the same options) and sends it.
289 my $cust_msg = $self->prepare(@_);
290 $self->send_prepared($cust_msg);
293 =item render OPTION => VALUE ...
295 Fills in the template and renders it to a PDF document. Returns the
296 name of the PDF file.
298 Options are as for 'prepare', but 'from' and 'to' are meaningless.
302 # XXX not sure where this ends up post-refactoring--a separate template
303 # class? it doesn't use the same rendering OR output machinery as ::email
305 # will also have options to set paper size, margins, etc.
309 eval "use PDF::WebKit";
312 my %hash = $self->prepare(%opt);
313 my $html = $hash{'html_body'};
315 # Graphics/stylesheets should probably go in /var/www on the Freeside
317 my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
319 my $kit = PDF::WebKit->new(\$html); #%options
320 # hack to use our wrapper script
321 $kit->configure(sub { shift->wkhtmltopdf($script_path) });
328 Render a PDF and send it to the printer. OPTIONS are as for 'render'.
333 my( $self, %opt ) = @_;
334 do_print( [ $self->render(%opt) ], agentnum=>$opt{cust_main}->agentnum );
337 # helper sub for package dates
338 my $ymd = sub { $_[0] ? time2str('%Y-%m-%d', $_[0]) : '' };
340 # helper sub for money amounts
341 my $money = sub { ($conf->money_char || '$') . sprintf('%.2f', $_[0] || 0) };
343 # helper sub for usage-related messages
344 my $usage_warning = sub {
346 foreach my $col (qw(seconds upbytes downbytes totalbytes)) {
347 my $amount = $svc->$col; next if $amount eq '';
348 my $method = $col.'_threshold';
349 my $threshold = $svc->$method; next if $threshold eq '';
350 return [$col, $amount, $threshold] if $amount <= $threshold;
351 # this only returns the first one that's below threshold, if there are
357 #return contexts and fill-in values
358 # If you add anything, be sure to add a description in
359 # httemplate/edit/msg_template.html.
361 { 'cust_main' => [qw(
362 display_custnum agentnum agent_name
365 name name_short contact contact_firstlast
366 address1 address2 city county state zip
368 daytime night mobile fax
371 ship_name ship_name_short ship_contact ship_contact_firstlast
372 ship_address1 ship_address2 ship_city ship_county ship_state ship_zip
375 paymask payname paytype payip
376 num_cancelled_pkgs num_ncancelled_pkgs num_pkgs
377 classname categoryname
380 invoicing_list_emailonly
381 cust_status ucfirst_cust_status cust_statuscolor cust_status_label
386 [ invoicing_email => sub { shift->invoicing_list_emailonly_scalar } ],
387 #compatibility: obsolete ship_ fields - use the non-ship versions
390 [ "ship_$field" => sub { shift->$field } ]
392 qw( last first company daytime night fax )
394 # ship_name, ship_name_short, ship_contact, ship_contact_firstlast
396 [ expdate => sub { shift->paydate_epoch } ], #compatibility
397 [ signupdate_ymd => sub { $ymd->(shift->signupdate) } ],
398 [ dundate_ymd => sub { $ymd->(shift->dundate) } ],
399 [ paydate_my => sub { sprintf('%02d/%04d', shift->paydate_monthyear) } ],
400 [ otaker_first => sub { shift->access_user->first } ],
401 [ otaker_last => sub { shift->access_user->last } ],
402 [ payby => sub { FS::payby->shortname(shift->payby) } ],
403 [ company_name => sub {
404 $conf->config('company_name', shift->agentnum)
406 [ company_address => sub {
407 $conf->config('company_address', shift->agentnum)
409 [ company_phonenum => sub {
410 $conf->config('company_phonenum', shift->agentnum)
412 [ selfservice_server_base_url => sub {
413 $conf->config('selfservice_server-base_url') #, shift->agentnum)
418 pkgnum pkg_label pkg_label_long
422 start_date setup bill last_bill
426 [ pkg => sub { shift->part_pkg->pkg } ],
427 [ pkg_category => sub { shift->part_pkg->categoryname } ],
428 [ pkg_class => sub { shift->part_pkg->classname } ],
429 [ cancel => sub { shift->getfield('cancel') } ], # grrr...
430 [ start_ymd => sub { $ymd->(shift->getfield('start_date')) } ],
431 [ setup_ymd => sub { $ymd->(shift->getfield('setup')) } ],
432 [ next_bill_ymd => sub { $ymd->(shift->getfield('bill')) } ],
433 [ last_bill_ymd => sub { $ymd->(shift->getfield('last_bill')) } ],
434 [ adjourn_ymd => sub { $ymd->(shift->getfield('adjourn')) } ],
435 [ susp_ymd => sub { $ymd->(shift->getfield('susp')) } ],
436 [ expire_ymd => sub { $ymd->(shift->getfield('expire')) } ],
437 [ cancel_ymd => sub { $ymd->(shift->getfield('cancel')) } ],
439 # not necessarily correct for non-flat packages
440 [ setup_fee => sub { shift->part_pkg->option('setup_fee') } ],
441 [ recur_fee => sub { shift->part_pkg->option('recur_fee') } ],
443 [ freq_pretty => sub { shift->part_pkg->freq_pretty } ],
452 [ due_date2str => sub { shift->due_date2str('short') } ],
454 #XXX not really thinking about cust_bill substitutions quite yet
456 # for welcome and limit warning messages
462 [ password => sub { shift->getfield('_password') } ],
463 [ column => sub { &$usage_warning(shift)->[0] } ],
464 [ amount => sub { &$usage_warning(shift)->[1] } ],
465 [ threshold => sub { &$usage_warning(shift)->[2] } ],
472 my $registrar = qsearchs('registrar',
473 { registrarnum => shift->registrarnum} );
474 $registrar ? $registrar->registrarname : ''
478 my $svc_acct = qsearchs('svc_acct', { svcnum => shift->catchall });
479 $svc_acct ? $svc_acct->email : ''
490 'svc_broadband' => [qw(
498 # for payment receipts
503 [ paid => sub { sprintf("%.2f", shift->paid) } ],
504 # overrides the one in cust_main in cases where a cust_pay is passed
505 [ payby => sub { FS::payby->shortname(shift->payby) } ],
506 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
508 my $cust_pay = shift;
509 ($cust_pay->payby eq 'CARD' || $cust_pay->payby eq 'CHEK') ?
510 $cust_pay->paymask : $cust_pay->decrypt($cust_pay->payinfo)
513 # for payment decline messages
514 # try to support all cust_pay fields
515 # 'error' is a special case, it contains the raw error from the gateway
516 'cust_pay_pending' => [qw(
520 [ paid => sub { sprintf("%.2f", shift->paid) } ],
521 [ payby => sub { FS::payby->shortname(shift->payby) } ],
522 [ date => sub { time2str("%a %B %o, %Y", shift->_date) } ],
525 ($pending->payby eq 'CARD' || $pending->payby eq 'CHEK') ?
526 $pending->paymask : $pending->decrypt($pending->payinfo)
534 Stub, returns nothing.
542 Returns the L<FS::agent> object for this template.
547 my ($self, %opts) = @_;
550 # First move any historical templates in config to real message templates
554 [ 'alerter_msgnum', 'alerter_template', '', '', '' ],
555 [ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
556 [ 'decline_msgnum', 'declinetemplate', '', '', '' ],
557 [ 'impending_recur_msgnum', 'impending_recur_template', '', '', 'impending_recur_bcc' ],
558 [ 'payment_receipt_msgnum', 'payment_receipt_email', '', '', '' ],
559 [ 'welcome_msgnum', 'welcome_email', 'welcome_email-subject', 'welcome_email-from', '' ],
560 [ 'warning_msgnum', 'warning_email', 'warning_email-subject', 'warning_email-from', '' ],
563 my @agentnums = ('', map {$_->agentnum} qsearch('agent', {}));
564 foreach my $agentnum (@agentnums) {
566 my ($newname, $oldname, $subject, $from, $bcc) = @$_;
567 if ($conf->exists($oldname, $agentnum)) {
568 my $new = new FS::msg_template({
569 'msgname' => $oldname,
570 'agentnum' => $agentnum,
571 'from_addr' => ($from && $conf->config($from, $agentnum)) || '',
572 'bcc_addr' => ($bcc && $conf->config($from, $agentnum)) || '',
573 'subject' => ($subject && $conf->config($subject, $agentnum)) || '',
574 'mime_type' => 'text/html',
575 'body' => join('<BR>',$conf->config($oldname, $agentnum)),
577 my $error = $new->insert;
578 die $error if $error;
579 $conf->set($newname, $new->msgnum, $agentnum);
580 $conf->delete($oldname, $agentnum);
581 $conf->delete($from, $agentnum) if $from;
582 $conf->delete($subject, $agentnum) if $subject;
586 if ( $conf->exists('alert_expiration', $agentnum) ) {
587 my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
588 my $template = FS::msg_template->by_key($msgnum) if $msgnum;
590 warn "template for alerter_msgnum $msgnum not found\n";
593 # this is now a set of billing events
594 foreach my $days (30, 15, 5) {
595 my $event = FS::part_event->new({
596 'agentnum' => $agentnum,
597 'event' => "Card expiration warning - $days days",
598 'eventtable' => 'cust_main',
599 'check_freq' => '1d',
600 'action' => 'notice',
601 'disabled' => 'Y', #initialize first
603 my $error = $event->insert( 'msgnum' => $msgnum );
605 warn "error creating expiration alert event:\n$error\n\n";
608 # make it work like before:
609 # only send each warning once before the card expires,
610 # only warn active customers,
611 # only warn customers with CARD/DCRD,
612 # only warn customers who get email invoices
614 'once_every' => { 'run_delay' => '30d' },
615 'cust_paydate_within' => { 'within' => $days.'d' },
616 'cust_status' => { 'status' => { 'active' => 1 } },
617 'payby' => { 'payby' => { 'CARD' => 1,
620 'message_email' => {},
622 foreach (keys %conds) {
623 my $condition = FS::part_event_condition->new({
624 'conditionname' => $_,
625 'eventpart' => $event->eventpart,
627 $error = $condition->insert( %{ $conds{$_} });
629 warn "error creating expiration alert event:\n$error\n\n";
633 $error = $event->initialize;
635 warn "expiration alert event was created, but not initialized:\n$error\n\n";
638 $conf->delete('alerter_msgnum', $agentnum);
639 $conf->delete('alert_expiration', $agentnum);
641 } # if alerter_msgnum
646 # Move subject and body from msg_template to template_content
649 foreach my $msg_template ( qsearch('msg_template', {}) ) {
650 if ( $msg_template->subject || $msg_template->body ) {
651 # create new default content
653 $content{subject} = $msg_template->subject;
654 $msg_template->set('subject', '');
656 # work around obscure Pg/DBD bug
657 # https://rt.cpan.org/Public/Bug/Display.html?id=60200
658 # (though the right fix is to upgrade DBD)
659 my $body = $msg_template->body;
660 if ( $body =~ /^x([0-9a-f]+)$/ ) {
661 # there should be no real message templates that look like that
662 warn "converting template body to TEXT\n";
663 $body = pack('H*', $1);
665 $content{body} = $body;
666 $msg_template->set('body', '');
667 my $error = $msg_template->replace(%content);
668 die $error if $error;
671 if ( !$msg_template->msgclass ) {
672 # set default message class
673 $msg_template->set('msgclass', 'email');
674 my $error = $msg_template->replace;
675 die $error if $error;
680 # Add new-style default templates if missing
682 $self->_populate_initial_data;
686 sub _populate_initial_data { #class method
687 #my($class, %opts) = @_;
690 eval "use FS::msg_template::InitialData;";
693 my $initial_data = FS::msg_template::InitialData->_initial_data;
695 foreach my $hash ( @$initial_data ) {
697 next if $hash->{_conf} && $conf->config( $hash->{_conf} );
699 my $msg_template = new FS::msg_template($hash);
700 my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
701 die $error if $error;
703 $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
715 L<FS::Record>, schema.html from the base documentation.