RT# 82094 - updated UI for bulk emailing from advanced customer reports
[freeside.git] / httemplate / misc / email-customers.html
index 3327303..cf3ab1b 100644 (file)
@@ -1,37 +1,43 @@
 <%doc>
 
-Allows emailing one or more customers, based on a search for customers.  Search can
-be specified either through cust_main fields as cgi params, or through a base64 encoded
-frozen hash in the 'search' cgi param.  Form allows selecting an existing msg_template,
-or creating a custom message, and shows a preview of the message before sending.
-If linked to as a popup, include the cgi parameter 'popup' for proper header handling.
-
-This may also be used as an element in other pages, enabling you to provide an
-alternate initial form while using this for search freezing/thawing and 
+Allows emailing one or more customers, based on a search for customers.
+Search can be specified either through cust_main fields as cgi params, or
+through a base64 encoded frozen hash in the 'search' cgi param.  Form allows
+selecting an existing msg_template, or creating a custom message, and shows a
+preview of the message before sending.  If linked to as a popup, include the
+cgi parameter 'popup' for proper header handling.
+
+This may also be used as an element in other pages, enabling you to provide
+an alternate initial form while using this for search freezing/thawing and 
 preview/send actions, with the following options:
 
+acl - the access right to use (defaults to 'Bulk send customer notices')
+
 form_action - the URL to submit the form to
 
+process_url - the URL for starting the JSRPC process
+
 title - the title of the page
 
 no_search_fields - arrayref of additional fields that are not search parameters
 
 alternate_form - subroutine that returns alternate html for the initial form,
-replaces msgnum/from/subject/html_body/action inputs and submit button,
-not used if an action is specified
+replaces msgnum/from/subject/body/action inputs and submit button, not
+used if an action is specified
 
-post_search_hook - sub hook for additional processing after search has been processed from cgi,
-gets passed options 'conf' and 'search' (a reference to the unfrozen %search hash),
-should be used to set msgnum or from/subject/html_body cgi params
+post_search_hook - sub hook for additional processing after search has been
+processed from cgi, gets passed options 'conf' and 'search' (a reference to
+the unfrozen %search hash), should be used to set msgnum or
+from/subject/body cgi params
 
 </%doc>
-
 % if ($popup) {
-<% include('/elements/header-popup.html', $title) %>
+<& /elements/header-popup.html, $title &>
 % } else {
-<% include('/elements/header.html', $title) %>
+<& /elements/header.html, $title &>
 % }
 
+<& /elements/error.html &>
 
 <FORM NAME="OneTrueForm" ACTION="<% $form_action %>" METHOD="POST">
 <INPUT TYPE="hidden" NAME="table" VALUE="<% $table %>">
@@ -42,55 +48,51 @@ should be used to set msgnum or from/subject/html_body cgi params
 <INPUT TYPE="hidden" NAME="search" VALUE="<% encode_base64(nfreeze(\%search)) %>">
 <INPUT TYPE="hidden" NAME="popup" VALUE="<% $popup %>">
 <INPUT TYPE="hidden" NAME="url" VALUE="<% $url | h %>">
+<INPUT TYPE="hidden" NAME="to_contact_classnum" VALUE="<% join(',', @contact_classnum) %>">
 
-% if ( $cgi->param('action') eq 'send' ) { 
+% if ( $cgi->param('preview') ) {
+%   # preview mode: at this point we have a msg_template (either "real" or
+%   # draft) and $html_body and $text_body contain the preview message.
+%   # give the user a chance to back out (by going back to edit mode).
 
-    <FONT SIZE="+2">Sending notice</FONT>
-
-    <% include('/elements/progress-init.html',
+    <FONT SIZE="+2">Preview notice</FONT>
+    <& /elements/progress-init.html,
                  'OneTrueForm',
-                 [ qw( search table from subject html_body text_body msgnum ) ],
-                 'process/email-customers.html',
+                 [ qw( search table msgnum to_contact_classnum emailtovoice_contact custnum ) ],
+                 $process_url,
                  $pdest,
-              )
-    %>
-
-% } elsif ( $cgi->param('action') eq 'preview' ) {
-
-    <FONT SIZE="+2">Preview notice</FONT>
+    &>
 
-% }
+    <TABLE CLASS="fsinnerbox">
+    <INPUT TYPE="hidden" NAME="msgnum" VALUE="<% $msg_template->msgnum %>">
+%   # kludge these through hidden inputs because they're not really part
+%   # of the template, but should be sticky during draft editing
+    <INPUT TYPE="hidden" NAME="from_name" VALUE="<% scalar($cgi->param('from_name')) |h %>">
+    <INPUT TYPE="hidden" NAME="from_addr" VALUE="<% scalar($cgi->param('from_addr')) |h %>">
+    <INPUT TYPE="hidden" NAME="emailtovoice_contact" VALUE="<% scalar($cgi->param('emailtovoice_contact')) |h %>">
+    <INPUT TYPE="hidden" NAME="custnum" VALUE="<% scalar($cgi->param('custnum')) |h %>">
+
+%   if ( !$msg_template->disabled ) {
+      <& /elements/tr-td-label.html, 'label' => 'Template:' &>
+        <td><% $msg_template->msgname |h %></td>
+      </tr>
+%   }
 
-% if ( $cgi->param('action') ) {
+      <& /elements/tr-td-label.html, 'label' => 'From:' &>
+        <td><% $from |h %></td>
+      </tr>
 
-    <TABLE BGCOLOR="#cccccc" CELLSPACING=0>
-    <INPUT TYPE="hidden" NAME="msgnum" VALUE="<% $cgi->param('msgnum') %>">
+      <& /elements/tr-td-label.html, 'label' => 'To contacts:' &>
+        <td><% join('<BR>', @contact_classname) %></td>
+      </tr>
 
-%   if ( $msg_template ) {
-      <% include('/elements/tr-fixed.html',
-                   'label'      => 'Template:',
-                   'value'      => $msg_template->msgname,
-                )
-      %>
-% }
+      <& /elements/tr-td-label.html, 'label' => 'Subject:' &>
+        <td><% $subject |h %></td>
+      </tr>
 
-      <% include('/elements/tr-fixed.html',
-                   'field'      => 'from',
-                   'label'      => 'From:',
-                   'value' => scalar( $from ),
-                )
-      %>
-
-      <% include('/elements/tr-fixed.html',
-                   'field'      => 'subject',
-                   'label'      => 'Subject:',
-                   'value' => scalar( $subject ),
-                )
-      %>
-
-      <INPUT TYPE="hidden" NAME="html_body" VALUE="<% $html_body |h %>">
+      <TR><TD COLSPAN=2>&nbsp;</TD></TR>
       <TR>
-        <TD ALIGN="right" VALIGN="top">Message (HTML display): </TD>
+        <TH ALIGN="right" VALIGN="top">Message (HTML display): </TD>
         <TD CLASS="background" ALIGN="left"><% $html_body %></TD>
       </TR>
 
@@ -99,33 +101,49 @@ should be used to set msgnum or from/subject/html_body cgi params
 %                         $html_body
 %                       )
 %                     );
-      <INPUT TYPE="hidden" NAME="text_body" VALUE="<% $text_body |h %>">
+      <TR><TD COLSPAN=2>&nbsp;</TD></TR>
       <TR>
-        <TD ALIGN="right" VALIGN="top">Message (Text display): </TD>
-        <TD CLASS="background" STYLE="background-color:white" ALIGN="left"><PRE><% $text_body %></PRE></TD>
+        <TH ALIGN="right" VALIGN="top">Message (Text display): </TD>
+        <TD CLASS="background" ALIGN="left">
+          <a href="javascript:void(0)" ID="email-message-text-view" style="color:#666666" onclick="showtext()">(view)</a>
+          <a href="javascript:void(0)" ID="email-message-text-hide" style="color:#666666; display: none;" onclick="hidetext()">(hide)</a>
+          <PRE id="email-message-text" style="display: none;"><% $text_body %></PRE>
+        </TD>
       </TR>
 
     </TABLE>
 
-%   if ( $cgi->param('action') eq 'preview' ) {
+    <SCRIPT>
+
+      function showtext() {
+        $('#email-message-text-view').css('display','none');
+        $('#email-message-text-hide').css('display','');
+        $('#email-message-text').slideDown();
+      }
 
-      <SCRIPT>
-        function areyousure(href) {
-          return confirm("Send this notice to <% ($num_cust > 1) ? "$num_cust customers" : '1 customer' %> ?");
+      function hidetext() {
+        $('#email-message-text-view').css('display','');
+        $('#email-message-text-hide').css('display','none');
+        $('#email-message-text').slideUp();
+      }
+
+      function areyousure(href) {
+        if (confirm("Send this notice to <% ($num_cust > 1) ? "$num_cust customers" : '1 customer' %> ?")) {
+          process();
         }
-      </SCRIPT>
+      }
+    </SCRIPT>
 
-      <BR>
-      <INPUT TYPE="hidden" NAME="action" VALUE="send">
-      <INPUT TYPE="submit" VALUE="Send notice" onClick="return areyousure()">
-    
-%   }
+    <BR>
+    <INPUT TYPE="submit" NAME="edit" VALUE="Edit">
+    <INPUT TYPE="button" VALUE="Send notice" onClick="areyousure()">
 
 % } elsif ($opt{'alternate_form'}) {
 
 <% &{$opt{'alternate_form'}}() %>
 
 % } else {
+%   # Edit mode.
 
 <SCRIPT TYPE="text/javascript">
 function toggle(obj) {
@@ -133,11 +151,79 @@ function toggle(obj) {
 }
 
 </SCRIPT>
+% if ( $msg_template and $msg_template->disabled ) {
+%   # if we've already established a draft template, don't let msgnum be changed
+    <& /elements/hidden.html,
+      field => 'msgnum',
+      curr_value => ( scalar($cgi->param('msgnum')) || ''),
+    &>
+% } else {
 Template: 
     <& /elements/select-msg_template.html,
-         onchange => 'toggle(this)',
+        onchange   => 'toggle(this)',
+        curr_value => ( scalar($cgi->param('msgnum')) || ''),
     &>
     <BR>
+% }
+% # select destination contact classes
+<TABLE CELLSPACING=0 id="send_to_contacts_table">
+<TR>
+ <TD>Send to contacts:</TD>
+ <TD>
+   <div id="contactclassesdiv">
+     <& /elements/checkboxes.html,
+       'style'               => 'display: inline; vertical-align: top',
+       'disable_links'       => 1,
+       'names_list'          => \@optin_checkboxes,
+       'element_name_prefix' => 'contact_class_',
+       'checked_callback'    => sub {
+         # Called for each checkbox
+         # Return true to default as checked, false as unchecked
+         my($cgi, $name) = @_;
+         exists $dest_ischecked{$name};
+       },
+     &>
+   </div>
+% if ($send_to_domain && $cgi->param('custnum')) {
+   <div>
+     <INPUT TYPE="checkbox" NAME="emailtovoice"  ID="emailtovoice" VALUE="ON" onclick="toggleDiv(this)">Email to voice
+   </div>
+   <div id="emailtovoicediv" style="display:none";>
+
+      <& /elements/select-cust_phone.html,
+               'cust_num'     => $cgi->param('custnum'),
+               'field_name'   => 'emailtovoice_contact',
+               'format'       => 'xxxxxxxxxx',
+               'phone_types'  => [ 'daytime', 'night', 'fax', 'mobile' ],
+      &>@<% $send_to_domain |h %>
+   </div>
+% }
+ </TD>
+% if (@active_classes) {
+</tr>
+<tr>
+<TD>Contact Type:</TD>
+<TD>
+  <div id="contactclassesdiv">
+    <& /elements/checkboxes.html,
+      'style'               => 'display: inline; vertical-align: top',
+      'disable_links'       => 1,
+      'names_list'          => \@classnum_checkboxes,
+      'element_name_prefix' => 'contact_class_',
+      'checked_callback'    => sub {
+        # Called for each checkbox
+        # Return true to default as checked, false as unchecked
+        my($cgi, $name) = @_;
+        exists $classnum_ischecked{$name};
+      },
+    &>
+  </div>
+</TD>
+% }
+</TR>
+</TABLE>
+<BR>
+% # if sending a one-off message, show a form to edit it
   <TABLE BGCOLOR="#cccccc" CELLSPACING=0 WIDTH="100%" id="table_no_template">
     <& /elements/tr-td-label.html, 'label' => 'From:' &>
       <TD><& /elements/input-text.html,
@@ -145,63 +231,79 @@ Template:
               'value' => $conf->config('invoice_from_name', $agent_virt_agentnum) ||
                          $conf->config('company_name', $agent_virt_agentnum), #?
               'size'  => 20,
+              'curr_value' => scalar($cgi->param('from_name')),
           &>&nbsp;&lt;\
           <& /elements/input-text.html,
               'field' => 'from_addr',
               'type'  => 'email', # HTML5, woot
               'value' => $conf->config('invoice_from', $agent_virt_agentnum),
               'size'  => 20,
+              'curr_value' => scalar($cgi->param('from_addr')),
           &>&gt;</TD>
  
-    <% include('/elements/tr-input-text.html',
+    <& /elements/tr-input-text.html,
                  'field' => 'subject',
                  'label' => 'Subject:',
                  'size'  => 50,
-              )
-    %>
+                 'curr_value' => $subject,
+    &>
 
     <TR>
       <TD ALIGN="right" VALIGN="top" STYLE="padding-top:3px">Message: </TD>
       <TD><& /elements/htmlarea.html, 
-               'field' => 'html_body',
+               'field' => 'body',
                'width' => 763,
+               'curr_value' => $body,
           &>
       </TD>
     </TR>
 
   </TABLE>
 
-%#Substitution vars:
-
-    <INPUT TYPE="hidden" NAME="action" VALUE="preview">
-    <INPUT TYPE="submit" VALUE="Preview notice">
+  <INPUT TYPE="hidden" NAME="custnum" VALUE="<% scalar($cgi->param('custnum')) |h %>">
+  <INPUT TYPE="submit" NAME="preview" VALUE="Preview notice">
 
 % } #end not action or alternate form
 
 </FORM>
 
-% if ( $cgi->param('action') eq 'send' ) {
-    <SCRIPT TYPE="text/javascript">
-      process();
-    </SCRIPT>
-% }
+<SCRIPT TYPE="text/javascript">
+function toggleDiv(obj) {
+  var box_contactclasses = document.getElementById('contactclassesdiv');
+  var box_emailtovoice = document.getElementById('emailtovoicediv');
 
-<% include('/elements/footer.html') %>
+  box_emailtovoice.style.display = (box_emailtovoice.style.display == 'none') ? 'block' : 'none';
+  document.getElementById('emailtovoice_contact').options[0].selected=true;
+
+  box_contactclasses.style.display = (box_contactclasses.style.display == 'none') ? 'block' : 'none';
+}
+</SCRIPT>
+
+<& /elements/footer.html &>
 
 <%init>
 
 my %opt = @_;
 
+$opt{'acl'} ||= 'Bulk send customer notices';
+
+my $email_to;
+
 die "access denied"
-  unless $FS::CurrentUser::CurrentUser->access_right('Bulk send customer notices');
+  unless $FS::CurrentUser::CurrentUser->access_right($opt{'acl'});
 
 my $conf = FS::Conf->new;
-my @no_search_fields = qw( action table from subject html_body text_body popup url );
+my @no_search_fields = qw( table from subject html_body text_body popup url );
+
+my $send_to_domain = $conf->config('email-to-voice_domain');
 
 my $form_action = $opt{'form_action'} || 'email-customers.html';
+my $process_url = $opt{'process_url'} || 'process/email-customers.html';
 my $title = $opt{'title'} || 'Send customer notices';
 push( @no_search_fields, @{$opt{'no_search_fields'}} ) if $opt{'no_search_fields'};
 
+$m->comp('/elements/handle_uri_query');
+
 my $table = $cgi->param('table') or die "'table' required";
 my $agent_virt_agentnum = $cgi->param('agent_virt_agentnum') || '';
 
@@ -212,7 +314,7 @@ $pdest->{'url'} = $cgi->param('url') if $url;
 
 my %search;
 if ( $cgi->param('search') ) {
-  %search = %{ thaw(decode_base64($cgi->param('search'))) };
+  %search = %{ thaw(decode_base64( $cgi->param('search') )) };
 }
 else {
   %search = $cgi->Vars;
@@ -224,6 +326,15 @@ else {
   @search{keys %search} = map { /\0/ ? [ split /\0/, $_ ] : $_ } values %search;
 }
 
+# rebuild contacts hash
+delete $search{contacts}
+    if exists $search{contacts} && ref $search{contacts};
+$search{'contacts'} = {
+  map { $_ => $search{$_}, }
+    grep { /^(contacts_*)/ && $search{$_} }
+      keys %search
+};
+
 &{$opt{'post_search_hook'}}(
   'conf'   => $conf,
   'search' => \%search,
@@ -239,12 +350,53 @@ if ( $cgi->param('from') ) {
   $from = $cgi->param('from_addr');
 }
 
-my $subject = $cgi->param('subject') || '';
-my $html_body = $cgi->param('html_body') || '';
-
 my $msg_template = '';
+if ( $cgi->param('msgnum') =~ /^(\d+)$/ ) {
+  $msg_template = FS::msg_template->by_key($1)
+    or die "template not found: ".$cgi->param('msgnum');
+}
+
+my @contact_classnum;
+my @contact_classname;
+
+my $subject = $cgi->param('subject');
+my $body = $cgi->param('body');
+my ($html_body, $text_body);
+
+if ( !$cgi->param('preview') ) {
+
+  # edit mode: initialize the fields from the saved draft, if there is one
+  if ( $msg_template and $msg_template->disabled eq 'D' ) {
+    my $content = $msg_template->content(''); # no localization on these yet
+    $subject ||= $content->subject;
+    $body ||= $content->body;
+  }
+
+  my $sql_query = "FS::$table"->search(\%search);
+  my $count_query = delete($sql_query->{'count_query'});
+  my $count_sth = dbh->prepare($count_query)
+    or die "Error preparing $count_query: ". dbh->errstr;
+  $count_sth->execute
+    or die "Error executing $count_query: ". $count_sth->errstr;
+  my $count_arrayref = $count_sth->fetchrow_arrayref;
+  $num_cust = $count_arrayref->[0];
 
-if ( $cgi->param('action') eq 'preview' ) {
+} else {
+
+  my @checked_email_dest;
+  my @checked_contact_type;
+  for ($cgi->param) {
+    if (/^contact_class_(.+)$/) {
+      my $f = $1;
+      if ($f eq 'invoice' || $f eq 'message') {
+        push @checked_email_dest, $f;
+      } elsif ( $f =~ /^\d+$/ ) {
+        push @checked_contact_type, $f;
+      }
+    }
+  }
+  $search{with_email_dest} = \@checked_email_dest if @checked_email_dest;
+  $search{with_contact_type} = \@checked_contact_type if @checked_contact_type;
 
   my $sql_query = "FS::$table"->search(\%search);
   my $count_query = delete($sql_query->{'count_query'});
@@ -255,22 +407,134 @@ if ( $cgi->param('action') eq 'preview' ) {
   my $count_arrayref = $count_sth->fetchrow_arrayref;
   $num_cust = $count_arrayref->[0];
 
-  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
+
+  my $cust;
+
+  if ( $msg_template ) { 
     $sql_query->{'extra_sql'} .= ' LIMIT 1';
     $sql_query->{'select'} = "$table.*";
     $sql_query->{'order_by'} = '';
     my $object = qsearchs($sql_query);
-    my $cust = $object->cust_main;
+    # Could use better error handling here...
+    die "No customers match the search criteria" unless ref $object;
+    $cust = $object->cust_main;
     my %msgopts = (
       'cust_main' => $cust,
       'object' => $object,
     );
-    my %message = $msg_template->prepare(%msgopts);
-    ($from, $subject, $html_body) = @message{'from', 'subject', 'html_body'};
+
+    my $cust_msg = $msg_template->prepare(%msgopts);
+    $from = $cust_msg->env_from;
+    $html_body = $cust_msg->preview;
+#hmm.  this came in with the #37098 rewrite, but isn't on v3 :/
+# causing problems with mangling subject of unrelated things
+# should probably decode instead of ignore the UTF-8 thing, but
+# this at least masks the ugliness for now :/
+    if ( $cust_msg->header =~ /^subject: (.*)/mi && $1 !~ /^\=\?UTF-8/ ) {
+      $subject = $1;
+    }
+  }
+
+  # contact_class_X params
+  #we can't switch to multi_param until we're done supporting deb 7
+  local($CGI::LIST_CONTEXT_WARN) = 0;
+
+  if ($cgi->param('emailtovoice_contact')) {
+    $email_to = $cgi->param('emailtovoice_contact') . '@' . $send_to_domain;
+    push @contact_classnum, 'emailtovoice';
+    push @contact_classname, $email_to;
+  }
+  else {
+    foreach my $param ( $cgi->param ) {
+      if ( $param =~ /^contact_class_(\w+)$/ ) {
+        push @contact_classnum, $1;
+        if ( $1 eq 'invoice' ) {
+          push @contact_classname, 'Invoice recipients';
+        } elsif ( $1 eq 'message' ) {
+          push @contact_classname, 'Message recipients';
+        } else {
+          my $contact_class = FS::contact_class->by_key($1);
+          push @contact_classname, encode_entities(
+            $contact_class ? $contact_class->classname : '(none)'
+          );
+        }
+      }
+    }
   }
 }
 
+# Build data structures for "Opt In" and "Contact Type" checkboxes
+#
+# By default, message recipients will be selected, this is a message.
+# By default, all Contact Types will be selected, but this may be
+#   overridden by passing 'classnums' get/post values.  If no contact
+#   types have been defined, the option will not be presented.
+
+my @active_classes = qsearch(contact_class => {disabled => ''} );
+
+my %classnum_ischecked;
+my %dest_ischecked;
+
+$CGI::LIST_CONTEXT_WARN = 0;
+if ( my @in_classnums = $cgi->param('classnums') ) {
+  # Set checked boxes from form input
+  for my $v (@in_classnums) {
+
+    if ( $v =~ /^\d+$/ ) {
+      $classnum_ischecked{$v} = 1
+    } elsif ( $v =~ /^(invoice|message)$/ ) {
+      $dest_ischecked{$v} = 1;
+    }
+
+  }
+} else {
+  # Checked boxes default values
+  $classnum_ischecked{$_->classnum} = 1 for @active_classes;
+  $classnum_ischecked{0} = 1;
+}
+
+# At least one destination is required
+$dest_ischecked{message} = 1 unless %dest_ischecked;
+
+my @optin_checkboxes = (
+  [ 'message' => { label => 'Message recipients', desc => 'send this notice to all message recipients for the '.$num_cust.' selected customers.' } ],
+  [ 'invoice' => { label => 'Invoice recipients', desc => 'send this notice to all invoice recipients for the '.$num_cust.' selected customers.' } ],
+);
+my @classnum_checkboxes = (
+  [ '0' => { label => '(None)' }],
+  map { [ $_->classnum => {label => $_->classname} ] } @active_classes,
+);
+
 </%init>