package FS::msg_template;
+use base qw( FS::Record );
use strict;
-use base qw( FS::Record );
-use Text::Template;
-use FS::Misc qw( generate_email send_email do_print );
+use vars qw( $DEBUG $conf );
+
use FS::Conf;
use FS::Record qw( qsearch qsearchs );
-use FS::UID qw( dbh );
-use FS::cust_main;
use FS::cust_msg;
use FS::template_content;
-use Date::Format qw( time2str );
-use HTML::Entities qw( decode_entities encode_entities ) ;
-use HTML::FormatText;
-use HTML::TreeBuilder;
-
-use File::Temp;
-use IPC::Run qw(run);
-use vars qw( $DEBUG $conf );
+use Date::Format qw(time2str);
FS::UID->install_callback( sub { $conf = new FS::Conf; } );
=item msgname - Name of the template. This will appear in the user interface;
if it needs to be localized for some users, add it to the message catalog.
+=item msgclass - The L<FS::msg_template> subclass that this should belong to.
+Defaults to 'email'.
+
=item agentnum - Agent associated with this template. Can be NULL for a
global template.
=item from_addr - Source email address.
+=item bcc_addr - Bcc all mail to this address.
+
=item disabled - disabled ('Y' or NULL).
=back
sub table { 'msg_template'; }
+sub _rebless {
+ my $self = shift;
+ my $class = 'FS::msg_template::' . $self->msgclass;
+ eval "use $class;";
+ bless($self, $class) unless $@;
+ $self;
+}
+
=item insert [ CONTENT ]
Adds this record to the database. If there is an error, returns the error,
otherwise returns false.
-A default (no locale) L<FS::template_content> object will be created. CONTENT
-is an optional hash containing 'subject' and 'body' for this object.
-
-=cut
-
-sub insert {
- my $self = shift;
- my %content = @_;
-
- my $oldAutoCommit = $FS::UID::AutoCommit;
- local $FS::UID::AutoCommit = 0;
- my $dbh = dbh;
-
- my $error = $self->SUPER::insert;
- if ( !$error ) {
- $content{'msgnum'} = $self->msgnum;
- $content{'subject'} ||= '';
- $content{'body'} ||= '';
- my $template_content = new FS::template_content (\%content);
- $error = $template_content->insert;
- }
-
- if ( $error ) {
- $dbh->rollback if $oldAutoCommit;
- return $error;
- }
-
- $dbh->commit if $oldAutoCommit;
- return;
-}
+# inherited
=item delete
=cut
-# the delete method can be inherited from FS::Record
+# inherited
=item replace [ OLD_RECORD ] [ CONTENT ]
Replaces the OLD_RECORD with this one in the database. If there is an error,
returns the error, otherwise returns false.
-CONTENT is an optional hash containing 'subject', 'body', and 'locale'. If
-supplied, an L<FS::template_content> object will be created (or modified, if
-one already exists for this locale).
-
=cut
-sub replace {
+# inherited
+
+sub replace_check {
my $self = shift;
- my $old = ( ref($_[0]) and $_[0]->isa('FS::Record') )
- ? shift
- : $self->replace_old;
- my %content = @_;
-
- my $oldAutoCommit = $FS::UID::AutoCommit;
- local $FS::UID::AutoCommit = 0;
- my $dbh = dbh;
-
- my $error = $self->SUPER::replace($old);
-
- if ( !$error and %content ) {
- $content{'locale'} ||= '';
- my $new_content = qsearchs('template_content', {
- 'msgnum' => $self->msgnum,
- 'locale' => $content{'locale'},
- } );
- if ( $new_content ) {
- $new_content->subject($content{'subject'});
- $new_content->body($content{'body'});
- $error = $new_content->replace;
- }
- else {
- $content{'msgnum'} = $self->msgnum;
- $new_content = new FS::template_content \%content;
- $error = $new_content->insert;
+ my $old = $self->replace_old;
+ # don't allow changing msgclass, except null to not-null (for upgrade)
+ if ( $old->msgclass ) {
+ if ( !$self->msgclass ) {
+ $self->set('msgclass', $old->msgclass);
+ } else {
+ return "Can't change message template class from ".$old->msgclass.
+ " to ".$self->msgclass.".";
}
}
-
- if ( $error ) {
- $dbh->rollback if $oldAutoCommit;
- return $error;
- }
-
- warn "committing FS::msg_template->replace\n" if $DEBUG and $oldAutoCommit;
- $dbh->commit if $oldAutoCommit;
- return;
+ '';
}
-
-
=item check
|| $self->ut_textn('mime_type')
|| $self->ut_enum('disabled', [ '', 'Y' ] )
|| $self->ut_textn('from_addr')
+ || $self->ut_textn('bcc_addr')
+ # fine for now, but change this to some kind of dynamic check if we
+ # ever have more than two msgclasses
+ || $self->ut_enum('msgclass', [ qw(email http) ]),
;
return $error if $error;
$self->SUPER::check;
}
-=item content_locales
-
-Returns a hashref of the L<FS::template_content> objects attached to
-this template, with the locale as key.
-
-=cut
-
-sub content_locales {
- my $self = shift;
- return $self->{'_content_locales'} ||= +{
- map { $_->locale , $_ }
- qsearch('template_content', { 'msgnum' => $self->msgnum })
- };
-}
-
=item prepare OPTION => VALUE
-Fills in the template and returns a hash of the 'from' address, 'to'
-addresses, subject line, and body.
+Fills in the template and returns an L<FS::cust_msg> object, containing the
+message to be sent. This method must be provided by the subclass.
Options are passed as a list of name/value pairs:
=cut
sub prepare {
+ die "unimplemented";
+}
+
+=item prepare_substitutions OPTION => VALUE ...
+
+Takes the same arguments as L</prepare>, and returns a hashref of the
+substitution variables.
+
+=cut
+
+sub prepare_substitutions {
my( $self, %opt ) = @_;
- my $cust_main = $opt{'cust_main'} or die 'cust_main required';
+ my $cust_main = $opt{'cust_main'}; # or die 'cust_main required';
my $object = $opt{'object'} or die 'object required';
- # localization
- my $locale = $cust_main->locale || '';
- warn "no locale for cust#".$cust_main->custnum."; using default content\n"
- if $DEBUG and !$locale;
- my $content = $self->content($cust_main->locale);
- warn "preparing template '".$self->msgname."' to cust#".$cust_main->custnum."\n"
- if($DEBUG);
+ warn "preparing substitutions for '".$self->msgname."'\n"
+ if $DEBUG;
my $subs = $self->substitutions;
# create substitution table
###
my %hash;
- my @objects = ($cust_main);
+ my @objects = ();
+ push @objects, $cust_main if $cust_main;
my @prefixes = ('');
my $svc;
if( ref $object ) {
$hash{$_} = $opt{substitutions}->{$_} foreach keys %{$opt{substitutions}};
}
- $_ = encode_entities($_ || '') foreach values(%hash);
-
- ###
- # clean up template
- ###
- my $subject_tmpl = new Text::Template (
- TYPE => 'STRING',
- SOURCE => $content->subject,
- );
- my $subject = $subject_tmpl->fill_in( HASH => \%hash );
-
- my $body = $content->body;
- my ($skin, $guts) = eviscerate($body);
- @$guts = map {
- $_ = decode_entities($_); # turn all punctuation back into itself
- s/\r//gs; # remove \r's
- s/<br[^>]*>/\n/gsi; # and <br /> tags
- s/<p>/\n/gsi; # and <p>
- s/<\/p>//gsi; # and </p>
- s/\240/ /gs; # and
- $_
- } @$guts;
-
- $body = '{ use Date::Format qw(time2str); "" }';
- while(@$skin || @$guts) {
- $body .= shift(@$skin) || '';
- $body .= shift(@$guts) || '';
- }
-
- ###
- # fill-in
- ###
-
- my $body_tmpl = new Text::Template (
- TYPE => 'STRING',
- SOURCE => $body,
- );
-
- $body = $body_tmpl->fill_in( HASH => \%hash );
-
- ###
- # and email
- ###
-
- my @to;
- if ( exists($opt{'to'}) ) {
- @to = split(/\s*,\s*/, $opt{'to'});
- }
- else {
- @to = $cust_main->invoicing_list_emailonly;
- }
- # no warning when preparing with no destination
-
- my $from_addr = $self->from_addr;
-
- if ( !$from_addr ) {
- if ( $opt{'from_config'} ) {
- $from_addr = scalar( $conf->config($opt{'from_config'},
- $cust_main->agentnum) );
- }
- $from_addr ||= scalar( $conf->config('invoice_from',
- $cust_main->agentnum) );
- }
-# my @cust_msg = ();
-# if ( $conf->exists('log_sent_mail') and !$opt{'preview'} ) {
-# my $cust_msg = FS::cust_msg->new({
-# 'custnum' => $cust_main->custnum,
-# 'msgnum' => $self->msgnum,
-# 'status' => 'prepared',
-# });
-# $cust_msg->insert;
-# @cust_msg = ('cust_msg' => $cust_msg);
-# }
-
- (
- 'custnum' => $cust_main->custnum,
- 'msgnum' => $self->msgnum,
- 'from' => $from_addr,
- 'to' => \@to,
- 'bcc' => $self->bcc_addr || undef,
- 'subject' => $subject,
- 'html_body' => $body,
- 'text_body' => HTML::FormatText->new(leftmargin => 0, rightmargin => 70
- )->format( HTML::TreeBuilder->new_from_content($body) ),
- );
-
+ return \%hash;
}
-=item send OPTION => VALUE
+=item send OPTION => VALUE ...
-Fills in the template and sends it to the customer. Options are as for
-'prepare'.
+Creates a message with L</prepare> (taking all the same options) and sends it.
=cut
-# broken out from prepare() in case we want to queue the sending,
-# preview it, etc.
sub send {
my $self = shift;
- send_email(generate_email($self->prepare(@_)));
+ my $cust_msg = $self->prepare(@_);
+ $self->send_prepared($cust_msg);
}
=item render OPTION => VALUE ...
=cut
+# XXX not sure where this ends up post-refactoring--a separate template
+# class? it doesn't use the same rendering OR output machinery as ::email
+
# will also have options to set paper size, margins, etc.
sub render {
# Graphics/stylesheets should probably go in /var/www on the Freeside
# machine.
+ my $script_path = `/usr/bin/which freeside-wkhtmltopdf`;
+ chomp $script_path;
my $kit = PDF::WebKit->new(\$html); #%options
# hack to use our wrapper script
- $kit->configure(sub { shift->wkhtmltopdf('freeside-wkhtmltopdf') });
+ $kit->configure(sub { shift->wkhtmltopdf($script_path) });
$kit->to_pdf;
}
return ['', '', ''];
};
-#my $conf = new FS::Conf;
-
#return contexts and fill-in values
# If you add anything, be sure to add a description in
# httemplate/edit/msg_template.html.
balance
credit_limit
invoicing_list_emailonly
- cust_status ucfirst_cust_status cust_statuscolor
+ cust_status ucfirst_cust_status cust_statuscolor cust_status_label
signupdate dundate
packages recurdates
[ company_phonenum => sub {
$conf->config('company_phonenum', shift->agentnum)
} ],
+ [ selfservice_server_base_url => sub {
+ $conf->config('selfservice_server-base_url') #, shift->agentnum)
+ } ],
],
# next_bill_date
'cust_pkg' => [qw(
'cust_bill' => [qw(
invnum
_date
- )],
+ _date_pretty
+ due_date
+ ),
+ [ due_date2str => sub { shift->due_date2str('short') } ],
+ ],
#XXX not really thinking about cust_bill substitutions quite yet
# for welcome and limit warning messages
=item content LOCALE
-Returns the L<FS::template_content> object appropriate to LOCALE, if there
-is one. If not, returns the one with a NULL locale.
+Stub, returns nothing.
=cut
-sub content {
- my $self = shift;
- my $locale = shift;
- qsearchs('template_content',
- { 'msgnum' => $self->msgnum, 'locale' => $locale }) ||
- qsearchs('template_content',
- { 'msgnum' => $self->msgnum, 'locale' => '' });
-}
+sub content {}
=item agent
=cut
-sub agent {
- qsearchs('agent', { 'agentnum' => $_[0]->agentnum });
-}
-
sub _upgrade_data {
my ($self, %opts) = @_;
+ ###
+ # First move any historical templates in config to real message templates
+ ###
+
my @fixes = (
[ 'alerter_msgnum', 'alerter_template', '', '', '' ],
[ 'cancel_msgnum', 'cancelmessage', 'cancelsubject', '', '' ],
$conf->delete($subject, $agentnum) if $subject;
}
}
+
+ if ( $conf->exists('alert_expiration', $agentnum) ) {
+ my $msgnum = $conf->exists('alerter_msgnum', $agentnum);
+ my $template = FS::msg_template->by_key($msgnum) if $msgnum;
+ if (!$template) {
+ warn "template for alerter_msgnum $msgnum not found\n";
+ next;
+ }
+ # this is now a set of billing events
+ foreach my $days (30, 15, 5) {
+ my $event = FS::part_event->new({
+ 'agentnum' => $agentnum,
+ 'event' => "Card expiration warning - $days days",
+ 'eventtable' => 'cust_main',
+ 'check_freq' => '1d',
+ 'action' => 'notice',
+ 'disabled' => 'Y', #initialize first
+ });
+ my $error = $event->insert( 'msgnum' => $msgnum );
+ if ($error) {
+ warn "error creating expiration alert event:\n$error\n\n";
+ next;
+ }
+ # make it work like before:
+ # only send each warning once before the card expires,
+ # only warn active customers,
+ # only warn customers with CARD/DCRD,
+ # only warn customers who get email invoices
+ my %conds = (
+ 'once_every' => { 'run_delay' => '30d' },
+ 'cust_paydate_within' => { 'within' => $days.'d' },
+ 'cust_status' => { 'status' => { 'active' => 1 } },
+ 'payby' => { 'payby' => { 'CARD' => 1,
+ 'DCRD' => 1, }
+ },
+ 'message_email' => {},
+ );
+ foreach (keys %conds) {
+ my $condition = FS::part_event_condition->new({
+ 'conditionname' => $_,
+ 'eventpart' => $event->eventpart,
+ });
+ $error = $condition->insert( %{ $conds{$_} });
+ if ( $error ) {
+ warn "error creating expiration alert event:\n$error\n\n";
+ next;
+ }
+ }
+ $error = $event->initialize;
+ if ( $error ) {
+ warn "expiration alert event was created, but not initialized:\n$error\n\n";
+ }
+ } # foreach $days
+ $conf->delete('alerter_msgnum', $agentnum);
+ $conf->delete('alert_expiration', $agentnum);
+
+ } # if alerter_msgnum
+
}
+
+ ###
+ # Move subject and body from msg_template to template_content
+ ###
+
foreach my $msg_template ( qsearch('msg_template', {}) ) {
if ( $msg_template->subject || $msg_template->body ) {
# create new default content
}
$content{body} = $body;
$msg_template->set('body', '');
-
my $error = $msg_template->replace(%content);
die $error if $error;
}
+
+ if ( !$msg_template->msgclass ) {
+ # set default message class
+ $msg_template->set('msgclass', 'email');
+ my $error = $msg_template->replace;
+ die $error if $error;
+ }
}
+
+ ###
+ # Add new-style default templates if missing
+ ###
+ $self->_populate_initial_data;
+
}
-sub eviscerate {
- # Every bit as pleasant as it sounds.
- #
- # We do this because Text::Template::Preprocess doesn't
- # actually work. It runs the entire template through
- # the preprocessor, instead of the code segments. Which
- # is a shame, because Text::Template already contains
- # the code to do this operation.
- my $body = shift;
- my (@outside, @inside);
- my $depth = 0;
- my $chunk = '';
- while($body || $chunk) {
- my ($first, $delim, $rest);
- # put all leading non-delimiters into $first
- ($first, $rest) =
- ($body =~ /^((?:\\[{}]|[^{}])*)(.*)$/s);
- $chunk .= $first;
- # put a leading delimiter into $delim if there is one
- ($delim, $rest) =
- ($rest =~ /^([{}]?)(.*)$/s);
-
- if( $delim eq '{' ) {
- $chunk .= '{';
- if( $depth == 0 ) {
- push @outside, $chunk;
- $chunk = '';
- }
- $depth++;
- }
- elsif( $delim eq '}' ) {
- $depth--;
- if( $depth == 0 ) {
- push @inside, $chunk;
- $chunk = '';
- }
- $chunk .= '}';
- }
- else {
- # no more delimiters
- if( $depth == 0 ) {
- push @outside, $chunk . $rest;
- } # else ? something wrong
- last;
- }
- $body = $rest;
+sub _populate_initial_data { #class method
+ #my($class, %opts) = @_;
+ #my $class = shift;
+
+ eval "use FS::msg_template::InitialData;";
+ die $@ if $@;
+
+ my $initial_data = FS::msg_template::InitialData->_initial_data;
+
+ foreach my $hash ( @$initial_data ) {
+
+ next if $hash->{_conf} && $conf->config( $hash->{_conf} );
+
+ my $msg_template = new FS::msg_template($hash);
+ my $error = $msg_template->insert( @{ $hash->{_insert_args} || [] } );
+ die $error if $error;
+
+ $conf->set( $hash->{_conf}, $msg_template->msgnum ) if $hash->{_conf};
+
}
- (\@outside, \@inside);
+
}
=back