estimate tax on quotations, #32489
[freeside.git] / FS / FS / Template_Mixin.pm
index 95d001e..ed6c8e0 100644 (file)
@@ -7,7 +7,7 @@ use vars qw( $DEBUG $me
            );
              # but NOT $conf
 use vars qw( $invoice_lines @buf ); #yuck
-use List::Util qw(sum first);
+use List::Util qw(sum); #can't import first, it conflicts with cust_main.first
 use Date::Format;
 use Date::Language;
 use Text::Template 1.20;
@@ -316,9 +316,6 @@ sub print_generic {
     unless $format =~ /^(latex|html|template)$/;
 
   my $cust_main = $self->cust_main || $self->prospect_main;
-  $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
-    unless $cust_main->payname
-        && $cust_main->payby !~ /^(CARD|DCRD|CHEK|DCHK)$/;
 
   my $locale = $params{'locale'} || $cust_main->locale;
 
@@ -565,9 +562,11 @@ sub print_generic {
     'custnum'         => $cust_main->display_custnum,
     'prospectnum'     => $cust_main->prospectnum,
     'agent_custid'    => &$escape_function($cust_main->agent_custid),
-    ( map { $_ => &$escape_function($cust_main->$_()) } qw(
-      payname company address1 address2 city state zip fax
-    )),
+    ( map { $_ => &$escape_function($cust_main->$_()) }
+        qw( company address1 address2 city state zip fax )
+    ),
+    'payname'         => &$escape_function( $cust_main->invoice_attn
+                                             || $cust_main->contact_firstlast ),
 
     #global config
     'ship_enable'     => $conf->exists('invoice-ship_address'),
@@ -655,10 +654,10 @@ sub print_generic {
   my @address = ();
   $invoice_data{'address'} = \@address;
   push @address,
-    $cust_main->payname.
-      ( ( $cust_main->payby eq 'BILL' ) && $cust_main->payinfo
-        ? " (P.O. #". $cust_main->payinfo. ")"
-        : ''
+    $invoice_data{'payname'}.
+      ( $cust_main->po_number
+          ? " (P.O. #". $cust_main->po_number. ")"
+          : ''
       )
   ;
   push @address, $cust_main->company
@@ -1214,7 +1213,8 @@ sub print_generic {
 
   # create a tax section if we don't yet have one
   my $tax_description = 'Taxes, Surcharges, and Fees';
-  my $tax_section = first { $_->{description} eq $tax_description } @sections;
+  my $tax_section =
+    List::Util::first { $_->{description} eq $tax_description } @sections;
   if (!$tax_section) {
     $tax_section = { 'description' => $tax_description };
     push @sections, $tax_section if $multisection;
@@ -1266,7 +1266,7 @@ sub print_generic {
               ];
 
   }
-  
   if ( @items_tax ) {
     my $total = {};
     $total->{'total_item'} = $self->mt('Sub-total');
@@ -1316,13 +1316,12 @@ sub print_generic {
 
   if ( $self->can('_items_total') ) { # quotations
 
-    $self->_items_total(\@total_items);
+    my @new_total_items = $self->_items_total;
 
-    foreach ( @total_items ) {
+    foreach ( @new_total_items ) {
       $_->{'total_item'}   = &$embolden_function( $_->{'total_item'} );
-      $_->{'total_amount'} = &$embolden_function( $other_money_char.
-                                                   $_->{'total_amount'}
-                                                );
+      $_->{'total_amount'} = &$embolden_function( $other_money_char.$_->{'total_amount'});
+      push @total_items, $_;
     }
 
   } else { #normal invoice case
@@ -1544,7 +1543,7 @@ sub print_generic {
   # invoice history "section" (not really a section)
   # not to be included in any subtotals, completely independent of 
   # everything...
-  if ( $conf->exists('previous_invoice_history') ) {
+  if ( $conf->exists('previous_invoice_history') and $cust_main->isa('FS::cust_main') ) {
     my %history;
     my %monthorder;
     foreach my $cust_bill ( $cust_main->cust_bill ) {
@@ -2037,10 +2036,6 @@ sender address, required
 
 alternate template name, optional
 
-=item print_text
-
-text attachment arrayref, optional
-
 =item subject
 
 email subject, optional
@@ -2084,61 +2079,61 @@ sub generate_email {
 
   my $tc = $self->template_conf;
 
-  if ( $conf->exists($tc.'html') ) {
+  my @text; # array of lines
+  my $html; # a big string
+  my @related_parts; # will contain the text/HTML alternative, and images
+  my $related; # will contain the multipart/related object
 
-    warn "$me creating HTML/text multipart message"
-      if $DEBUG;
+  if ( $conf->exists($tc. 'email_pdf') ) {
+    if ( my $msgnum = $conf->config($tc.'email_pdf_msgnum') ) {
 
-    $return{'nobody'} = 1;
+      warn "$me using '${tc}email_pdf_msgnum' in multipart message"
+        if $DEBUG;
 
-    my $alternative = build MIME::Entity
-      'Type'        => 'multipart/alternative',
-      #'Encoding'    => '7bit',
-      'Disposition' => 'inline'
-    ;
+      my $msg_template = FS::msg_template->by_key($msgnum)
+        or die "${tc}email_pdf_msgnum $msgnum not found\n";
+      my %prepared = $msg_template->prepare(
+        cust_main => $self->cust_main,
+        object    => $self
+      );
+
+      @text = split(/(?=\n)/, $prepared{'text_body'});
+      $html = $prepared{'html_body'};
 
-    my $data = '';
-    if ( $conf->exists($tc. 'email_pdf')
-         and scalar($conf->config($tc. 'email_pdf_note')) ) {
+    } elsif ( my @note = $conf->config($tc.'email_pdf_note') ) {
 
       warn "$me using '${tc}email_pdf_note' in multipart message"
         if $DEBUG;
-      $data = [ map { $_ . "\n" }
-                    $conf->config($tc.'email_pdf_note')
-              ];
+      @text = $conf->config($tc.'email_pdf_note');
+      $html = join('<BR>', @text);
+  
+    } # else use the plain text invoice
+  }
 
-    } else {
+  if (!@text) {
 
-      warn "$me not using '${tc}email_pdf_note' in multipart message"
-        if $DEBUG;
-      if ( ref($args{'print_text'}) eq 'ARRAY' ) {
-        $data = $args{'print_text'};
-      } elsif ( $conf->exists($tc.'template') ) { #plaintext invoice_template
-        $data = [ $self->print_text(\%args) ];
-      }
+    warn "$me generating plain text invoice"
+      if $DEBUG;
 
-    }
+    # 'print_text' argument is no longer used
+    @text = $self->print_text(\%args);
 
-    if ( $data ) {
-      $alternative->attach(
-        'Type'        => 'text/plain',
-        'Encoding'    => 'quoted-printable',
-        'Charset'     => 'UTF-8',
-        #'Encoding'    => '7bit',
-        'Data'        => $data,
-        'Disposition' => 'inline',
-      );
-    }
+  }
 
-    my $htmldata;
-    my $image = '';
-    my $barcode = '';
-    if ( $conf->exists($tc.'email_pdf')
-         and scalar($conf->config($tc.'email_pdf_note')) ) {
+  my $text_part = build MIME::Entity (
+    'Type'        => 'text/plain',
+    'Encoding'    => 'quoted-printable',
+    'Charset'     => 'UTF-8',
+    #'Encoding'    => '7bit',
+    'Data'        => \@text,
+    'Disposition' => 'inline',
+  );
 
-      $htmldata = join('<BR>', $conf->config($tc.'email_pdf_note') );
+  if (!$html) {
 
-    } else {
+    if ( $conf->exists($tc.'html') ) {
+      warn "$me generating HTML invoice"
+        if $DEBUG;
 
       $args{'from'} =~ /\@([\w\.\-]+)/;
       my $from = $1 || 'example.com';
@@ -2157,7 +2152,7 @@ sub generate_email {
       }
       my $image_data = $conf->config_binary( $logo, $agentnum);
 
-      $image = build MIME::Entity
+      push @related_parts, build MIME::Entity
         'Type'       => 'image/png',
         'Encoding'   => 'base64',
         'Data'       => $image_data,
@@ -2167,7 +2162,7 @@ sub generate_email {
    
       if ( ref($self) eq 'FS::cust_bill' && $conf->exists('invoice-barcode') ) {
         my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
-        $barcode = build MIME::Entity
+        push @related_parts, build MIME::Entity
           'Type'       => 'image/png',
           'Encoding'   => 'base64',
           'Data'       => $self->invoice_barcode(0),
@@ -2177,7 +2172,26 @@ sub generate_email {
         $args{'barcode_cid'} = $barcode_content_id;
       }
 
-      $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
+      $html = $self->print_html({ 'cid'=>$content_id, %args });
+    }
+
+  }
+
+  if ( $html ) {
+
+    warn "$me creating HTML/text multipart message"
+      if $DEBUG;
+
+    $return{'nobody'} = 1;
+
+    my $alternative = build MIME::Entity
+      'Type'        => 'multipart/alternative',
+      #'Encoding'    => '7bit',
+      'Disposition' => 'inline'
+    ;
+
+    if ( @text ) {
+      $alternative->add_part($text_part);
     }
 
     $alternative->attach(
@@ -2190,7 +2204,7 @@ sub generate_email {
                          '    </title>',
                          '  </head>',
                          '  <body bgcolor="#e8e8e8">',
-                         $htmldata,
+                         $html,
                          '  </body>',
                          '</html>',
                        ],
@@ -2198,104 +2212,68 @@ sub generate_email {
       #'Filename'    => 'invoice.pdf',
     );
 
+    unshift @related_parts, $alternative;
 
-    my @otherparts = ();
-    if ( ref($self) eq 'FS::cust_bill' && $cust_main->email_csv_cdr ) {
+    $related = build MIME::Entity 'Type'     => 'multipart/related',
+                                  'Encoding' => '7bit';
 
-      push @otherparts, build MIME::Entity
-        'Type'        => 'text/csv',
-        'Encoding'    => '7bit',
-        'Data'        => [ map { "$_\n" }
-                             $self->call_details('prepend_billed_number' => 1)
-                         ],
-        'Disposition' => 'attachment',
-        'Filename'    => 'usage-'. $self->invnum. '.csv',
-      ;
-
-    }
-
-    if ( $conf->exists($tc.'email_pdf') ) {
-
-      #attaching pdf too:
-      # multipart/mixed
-      #   multipart/related
-      #     multipart/alternative
-      #       text/plain
-      #       text/html
-      #     image/png
-      #   application/pdf
-
-      my $related = build MIME::Entity 'Type'     => 'multipart/related',
-                                       'Encoding' => '7bit';
-
-      #false laziness w/Misc::send_email
-      $related->head->replace('Content-type',
-        $related->mime_type.
-        '; boundary="'. $related->head->multipart_boundary. '"'.
-        '; type=multipart/alternative'
-      );
-
-      $related->add_part($alternative);
-
-      $related->add_part($image) if $image;
-
-      my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
+    #false laziness w/Misc::send_email
+    $related->head->replace('Content-type',
+      $related->mime_type.
+      '; boundary="'. $related->head->multipart_boundary. '"'.
+      '; type=multipart/alternative'
+    );
 
-      $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
+    $related->add_part($_) foreach @related_parts;
 
-    } else {
+  }
 
-      #no other attachment:
-      # multipart/related
-      #   multipart/alternative
-      #     text/plain
-      #     text/html
-      #   image/png
+  my @otherparts = ();
+  if ( ref($self) eq 'FS::cust_bill' && $cust_main->email_csv_cdr ) {
 
-      $return{'content-type'} = 'multipart/related';
-      if ($conf->exists('invoice-barcode') && $barcode) {
-        $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
-      } else {
-        $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
-      }
-      $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
-      #$return{'disposition'} = 'inline';
+    push @otherparts, build MIME::Entity
+      'Type'        => 'text/csv',
+      'Encoding'    => '7bit',
+      'Data'        => [ map { "$_\n" }
+                           $self->call_details('prepend_billed_number' => 1)
+                       ],
+      'Disposition' => 'attachment',
+      'Filename'    => 'usage-'. $self->invnum. '.csv',
+    ;
 
-    }
-  
-  } else {
+  }
 
-    if ( $conf->exists($tc.'email_pdf') ) {
-      warn "$me creating PDF attachment"
-        if $DEBUG;
+  if ( $conf->exists($tc.'email_pdf') ) {
 
-      #mime parts arguments a la MIME::Entity->build().
-      $return{'mimeparts'} = [
-        { $self->mimebuild_pdf(\%args) }
-      ];
-    }
-  
-    if ( $conf->exists($tc.'email_pdf')
-         and scalar($conf->config($tc.'email_pdf_note')) ) {
+    #attaching pdf too:
+    # multipart/mixed
+    #   multipart/related
+    #     multipart/alternative
+    #       text/plain
+    #       text/html
+    #     image/png
+    #   application/pdf
 
-      warn "$me using '${tc}email_pdf_note'"
-        if $DEBUG;
-      $return{'body'} = [ map { $_ . "\n" }
-                              $conf->config($tc.'email_pdf_note')
-                        ];
+    my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
+    push @otherparts, $pdf;
+  }
 
+  if (@otherparts) {
+    $return{'content-type'} = 'multipart/mixed'; # of the outer container
+    if ( $html ) {
+      $return{'mimeparts'} = [ $related, @otherparts ];
+      $return{'type'} = 'multipart/related'; # of the first part
     } else {
-
-      warn "$me not using '${tc}email_pdf_note'"
-        if $DEBUG;
-      if ( ref($args{'print_text'}) eq 'ARRAY' ) {
-        $return{'body'} = $args{'print_text'};
-      } else {
-        $return{'body'} = [ $self->print_text(\%args) ];
-      }
-
+      $return{'mimeparts'} = [ $text_part, @otherparts ];
+      $return{'type'} = 'text/plain';
     }
-
+  } elsif ( $html ) { # no PDF or CSV, strip the outer container
+    $return{'mimeparts'} = \@related_parts;
+    $return{'content-type'} = 'multipart/related';
+    $return{'type'} = 'multipart/alternative';
+  } else { # no HTML either
+    $return{'body'} = \@text;
+    $return{'content-type'} = 'text/plain';
   }
 
   %return;
@@ -3115,6 +3093,7 @@ sub _items_cust_bill_pkg {
                         );
 
       if ( ref($cust_bill_pkg) eq 'FS::quotation_pkg' ) {
+        # XXX this should be pulled out into quotation_pkg
 
         warn "$me _items_cust_bill_pkg cust_bill_pkg is quotation_pkg\n"
           if $DEBUG > 1;