- if ( $cgi->param('msgnum') ) {
- $msg_template = qsearchs('msg_template',
- { msgnum => $cgi->param('msgnum') } )
- or die "template not found: ".$cgi->param('msgnum');
+ if ( !$msg_template or $msg_template->disabled eq 'D' ) {
+ # then this is a one-off template; edit it in place
+ my $subject = $cgi->param('subject') || '';
+ my $body = $cgi->param('body') || '';
+
+ # create a draft template
+ $msg_template ||= FS::msg_template->new({
+ msgclass => 'email',
+ disabled => 'D',
+ });
+ # anyone have a better idea for msgname?
+ $msg_template->set('msgname' => "Notice " . DateTime->now->iso8601);
+ $msg_template->set('from_addr' => $from);
+ my %content = (
+ subject => $subject,
+ body => $body,
+ );
+ my $error;
+ if ( $msg_template->msgnum ) {
+ $error = $msg_template->replace(%content);
+ } else {
+ $error = $msg_template->insert(%content);
+ }
+
+ if ( $error ) {
+ $cgi->param('error', $error);
+ $cgi->delete('preview'); # don't go on to preview stage yet
+ undef $msg_template;
+ }
+ }
+ # unless creating the msg_template failed, we now have one, so construct a
+ # preview message from the first customer/whatever in the search results
+
+ if ( $msg_template ) {