c6a9b9fd229ad6d913ab51e83e38c260e894b8a2
[freeside.git] / FS / FS / Template_Mixin.pm
1 package FS::Template_Mixin;
2
3 use strict;
4 use vars qw( $DEBUG $me
5              $money_char
6              $date_format
7            );
8              # but NOT $conf
9 use vars qw( $invoice_lines @buf ); #yuck
10 use List::Util qw(sum); #can't import first, it conflicts with cust_main.first
11 use Date::Format;
12 use Date::Language;
13 use Time::Local qw( timelocal );
14 use Text::Template 1.20;
15 use File::Temp 0.14;
16 use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
17 use IO::Scalar;
18 use HTML::Entities;
19 use Cwd;
20 use FS::UID;
21 use FS::Misc qw( send_email );
22 use FS::Record qw( qsearch qsearchs dbh );
23 use FS::Conf;
24 use FS::Misc qw( generate_ps generate_pdf );
25 use FS::pkg_category;
26 use FS::pkg_class;
27 use FS::invoice_mode;
28 use FS::L10N;
29 use FS::Log;
30
31 $DEBUG = 0;
32 $me = '[FS::Template_Mixin]';
33 FS::UID->install_callback( sub {
34   my $conf = new FS::Conf; #global
35   $money_char  = $conf->config('money_char')  || '$';
36   $date_format = $conf->config('date_format') || '%x'; #/YY
37 } );
38
39 =item conf [ MODE ]
40
41 Returns a configuration handle (L<FS::Conf>) set to the customer's locale.
42
43 If the "mode" pseudo-field is set on the object, the configuration handle
44 will be an L<FS::invoice_conf> for that invoice mode (and the customer's
45 locale).
46
47 =cut
48
49 sub conf {
50   my $self = shift;
51   my $mode = $self->get('mode');
52   if ($self->{_conf} and !defined($mode)) {
53     return $self->{_conf};
54   }
55
56   my $cust_main = $self->cust_main;
57   my $locale = $cust_main ? $cust_main->locale : '';
58   my $conf;
59   if ( $mode ) {
60     if ( ref $mode and $mode->isa('FS::invoice_mode') ) {
61       $mode = $mode->modenum;
62     } elsif ( $mode =~ /\D/ ) {
63       die "invalid invoice mode $mode";
64     }
65     $conf = qsearchs('invoice_conf', { modenum => $mode, locale => $locale });
66     if (!$conf) {
67       $conf = qsearchs('invoice_conf', { modenum => $mode, locale => '' });
68       # it doesn't have a locale, but system conf still might
69       $conf->set('locale' => $locale) if $conf;
70     }
71   }
72   # if $mode is unspecified, or if there is no invoice_conf matching this mode
73   # and locale, then use the system config only (but with the locale)
74   $conf ||= FS::Conf->new({ 'locale' => $locale });
75   # cache it
76   return $self->{_conf} = $conf;
77 }
78
79 =item print_text OPTIONS
80
81 Returns an text invoice, as a list of lines.
82
83 Options can be passed as a hash.
84
85 I<time>, if specified, is used to control the printing of overdue messages.  The
86 default is now.  It isn't the date of the invoice; that's the `_date' field.
87 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
88 L<Time::Local> and L<Date::Parse> for conversion functions.
89
90 I<template>, if specified, is the name of a suffix for alternate invoices.
91
92 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
93
94 =cut
95
96 sub print_text {
97   my $self = shift;
98   my %params;
99   if ( ref($_[0]) ) {
100     %params = %{ shift() };
101   } else {
102     %params = @_;
103   }
104
105   $params{'format'} = 'template'; # for some reason
106
107   $self->print_generic( %params );
108 }
109
110 =item print_latex HASHREF
111
112 Internal method - returns a filename of a filled-in LaTeX template for this
113 invoice (Note: add ".tex" to get the actual filename), and a filename of
114 an associated logo (with the .eps extension included).
115
116 See print_ps and print_pdf for methods that return PostScript and PDF output.
117
118 Options can be passed as a hash.
119
120 I<time>, if specified, is used to control the printing of overdue messages.  The
121 default is now.  It isn't the date of the invoice; that's the `_date' field.
122 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
123 L<Time::Local> and L<Date::Parse> for conversion functions.
124
125 I<template>, if specified, is the name of a suffix for alternate invoices.
126 This is strongly deprecated; see L<FS::invoice_conf> for the right way to
127 customize invoice templates for different purposes.
128
129 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
130
131 =cut
132
133 sub print_latex {
134   my $self = shift;
135   my %params;
136
137   if ( ref($_[0]) ) {
138     %params = %{ shift() };
139   } else {
140     %params = @_;
141   }
142
143   $params{'format'} = 'latex';
144   my $conf = $self->conf;
145
146   # this needs to go away
147   my $template = $params{'template'};
148   # and this especially
149   $template ||= $self->_agent_template
150     if $self->can('_agent_template');
151
152   #the new way
153   $self->set('mode', $params{mode})
154     if $params{mode};
155
156   my $pkey = $self->primary_key;
157   my $tmp_template = $self->table. '.'. $self->$pkey. '.XXXXXXXX';
158
159   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
160   my $lh = new File::Temp(
161     TEMPLATE => $tmp_template,
162     DIR      => $dir,
163     SUFFIX   => '.eps',
164     UNLINK   => 0,
165   ) or die "can't open temp file: $!\n";
166
167   my $agentnum = $self->agentnum;
168
169   if ( $template && $conf->exists("logo_${template}.eps", $agentnum) ) {
170     print $lh $conf->config_binary("logo_${template}.eps", $agentnum)
171       or die "can't write temp file: $!\n";
172   } else {
173     print $lh $conf->config_binary('logo.eps', $agentnum)
174       or die "can't write temp file: $!\n";
175   }
176   close $lh;
177   $params{'logo_file'} = $lh->filename;
178
179   if( $conf->exists('invoice-barcode')
180         && $self->can('invoice_barcode')
181         && $self->invnum ) { # don't try to barcode statements
182       my $png_file = $self->invoice_barcode($dir);
183       my $eps_file = $png_file;
184       $eps_file =~ s/\.png$/.eps/g;
185       $png_file =~ /(barcode.*png)/;
186       $png_file = $1;
187       $eps_file =~ /(barcode.*eps)/;
188       $eps_file = $1;
189
190       my $curr_dir = cwd();
191       chdir($dir);
192       # after painfuly long experimentation, it was determined that sam2p won't
193       # accept : and other chars in the path, no matter how hard I tried to
194       # escape them, hence the chdir (and chdir back, just to be safe)
195       system('sam2p', '-j:quiet', $png_file, 'EPS:', $eps_file ) == 0
196         or die "sam2p failed: $!\n";
197       unlink($png_file);
198       chdir($curr_dir);
199
200       $params{'barcode_file'} = $eps_file;
201   }
202
203   my @filled_in = $self->print_generic( %params );
204
205   my $fh = new File::Temp( TEMPLATE => $tmp_template,
206                            DIR      => $dir,
207                            SUFFIX   => '.tex',
208                            UNLINK   => 0,
209                          ) or die "can't open temp file: $!\n";
210   binmode($fh, ':utf8'); # language support
211   print $fh join('', @filled_in );
212   close $fh;
213
214   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
215   return ($1, $params{'logo_file'}, $params{'barcode_file'});
216
217 }
218
219 sub agentnum {
220   my $self = shift;
221   my $cust_main = $self->cust_main;
222   $cust_main ? $cust_main->agentnum : $self->prospect_main->agentnum;
223 }
224
225 =item print_generic OPTION => VALUE ...
226
227 Internal method - returns a filled-in template for this invoice as a scalar.
228
229 See print_ps and print_pdf for methods that return PostScript and PDF output.
230
231 Required options
232
233 =over 4
234
235 =item format
236
237 The B<format> option is required and should be set to html, latex (print and PDF) or template (plaintext).
238
239 =back
240
241 Additional options
242
243 =over 4
244
245 =item notice_name
246
247 Overrides "Invoice" as the name of the sent document.
248
249 =item today
250
251 Used to control the printing of overdue messages.  The
252 default is now.  It isn't the date of the invoice; that's the `_date' field.
253 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
254 L<Time::Local> and L<Date::Parse> for conversion functions.
255
256 =item logo_file
257
258 Logo file (path to temporary EPS file on the local filesystem)
259
260 =item cid
261
262 CID for inline (emailed) images (logo)
263
264 =item locale
265
266 Override customer's locale
267
268 =item unsquelch_cdr
269
270 Overrides any per customer cdr squelching when true
271
272 =item no_number
273
274 Supress the (invoice, quotation, statement, etc.) number
275
276 =item no_date
277
278 Supress the date
279
280 =item no_coupon
281
282 Supress the payment coupon
283
284 =item barcode_file
285
286 Barcode file (path to temporary EPS file on the local filesystem)
287
288 =item barcode_img
289
290 Flag indicating the barcode image should be a link (normal HTML dipaly)
291
292 =item barcode_cid
293
294 Barcode CID for inline (emailed) images
295
296 =item preref_callback
297
298 Coderef run for each line item, code should return HTML to be displayed
299 before that line item (quotations only)
300
301 =item template
302
303 Deprecated.  Used as a suffix for a configuration template.  Please
304 don't use this, it deprecated in favor of more flexible alternatives.
305
306 =back
307
308 =cut
309
310 #what's with all the sprintf('%10.2f')'s in here?  will it cause any
311 # (alignment in text invoice?) problems to change them all to '%.2f' ?
312 # yes: fixed width/plain text printing will be borked
313 sub print_generic {
314   my( $self, %params ) = @_;
315   my $conf = $self->conf;
316
317   my $today = $params{today} ? $params{today} : time;
318   warn "$me print_generic called on $self with suffix $params{template}\n"
319     if $DEBUG;
320
321   my $format = $params{format};
322   die "Unknown format: $format"
323     unless $format =~ /^(latex|html|template)$/;
324
325   my $cust_main = $self->cust_main || $self->prospect_main;
326
327   my $locale = $params{'locale'} || $cust_main->locale;
328
329   my %delimiters = ( 'latex'    => [ '[@--', '--@]' ],
330                      'html'     => [ '<%=', '%>' ],
331                      'template' => [ '{', '}' ],
332                    );
333
334   warn "$me print_generic creating template\n"
335     if $DEBUG > 1;
336
337   # set the notice name here, and nowhere else.
338   my $notice_name =  $params{notice_name}
339                   || $conf->config('notice_name')
340                   || $self->notice_name;
341
342   #create the template
343   my $template = $params{template} ? $params{template} : $self->_agent_template;
344   my $templatefile = $self->template_conf. $format;
345   $templatefile .= "_$template"
346     if length($template) && $conf->exists($templatefile."_$template");
347
348   $self->set('_template',$template);
349
350   # the base template
351   my @invoice_template = map "$_\n", $conf->config($templatefile)
352     or die "cannot load config data $templatefile";
353
354   if ( $format eq 'latex' && grep { /^%%Detail/ } @invoice_template ) {
355     #change this to a die when the old code is removed
356     # it's been almost ten years, changing it to a die
357     die "old-style invoice template $templatefile; ".
358          "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
359          #$old_latex = 'true';
360          #@invoice_template = _translate_old_latex_format(@invoice_template);
361   }
362
363   warn "$me print_generic creating T:T object\n"
364     if $DEBUG > 1;
365
366   my $text_template = new Text::Template(
367     TYPE => 'ARRAY',
368     SOURCE => \@invoice_template,
369     DELIMITERS => $delimiters{$format},
370   );
371
372   warn "$me print_generic compiling T:T object\n"
373     if $DEBUG > 1;
374
375   $text_template->compile()
376     or die "Can't compile $templatefile: $Text::Template::ERROR\n";
377
378
379   # additional substitution could possibly cause breakage in existing templates
380   my %convert_maps = (
381     'latex' => {
382                  'notes'         => sub { map "$_", @_ },
383                  'footer'        => sub { map "$_", @_ },
384                  'smallfooter'   => sub { map "$_", @_ },
385                  'returnaddress' => sub { map "$_", @_ },
386                  'coupon'        => sub { map "$_", @_ },
387                  'summary'       => sub { map "$_", @_ },
388                },
389     'html'  => {
390                  'notes' =>
391                    sub {
392                      map {
393                        s/%%(.*)$/<!-- $1 -->/g;
394                        s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
395                        s/\\begin\{enumerate\}/<ol>/g;
396                        s/\\item /  <li>/g;
397                        s/\\end\{enumerate\}/<\/ol>/g;
398                        s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
399                        s/\\\\\*/<br>/g;
400                        s/\\dollar ?/\$/g;
401                        s/\\#/#/g;
402                        s/~/&nbsp;/g;
403                        $_;
404                      }  @_
405                    },
406                  'footer' =>
407                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
408                  'smallfooter' =>
409                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
410                  'returnaddress' =>
411                    sub {
412                      map {
413                        s/~/&nbsp;/g;
414                        s/\\\\\*?\s*$/<BR>/;
415                        s/\\hyphenation\{[\w\s\-]+}//;
416                        s/\\([&])/$1/g;
417                        $_;
418                      }  @_
419                    },
420                  'coupon'        => sub { "" },
421                  'summary'       => sub { "" },
422                },
423     'template' => {
424                  'notes' =>
425                    sub {
426                      map {
427                        s/%%.*$//g;
428                        s/\\section\*\{\\textsc\{(.*)\}\}/\U$1/g;
429                        s/\\begin\{enumerate\}//g;
430                        s/\\item /  * /g;
431                        s/\\end\{enumerate\}//g;
432                        s/\\textbf\{(.*)\}/$1/g;
433                        s/\\\\\*/ /;
434                        s/\\dollar ?/\$/g;
435                        $_;
436                      }  @_
437                    },
438                  'footer' =>
439                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
440                  'smallfooter' =>
441                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
442                  'returnaddress' =>
443                    sub {
444                      map {
445                        s/~/ /g;
446                        s/\\\\\*?\s*$/\n/;             # dubious
447                        s/\\hyphenation\{[\w\s\-]+}//;
448                        $_;
449                      }  @_
450                    },
451                  'coupon'        => sub { "" },
452                  'summary'       => sub { "" },
453                },
454   );
455
456
457   # hashes for differing output formats
458   my %nbsps = ( 'latex'    => '~',
459                 'html'     => '',    # '&nbps;' would be nice
460                 'template' => '',    # not used
461               );
462   my $nbsp = $nbsps{$format};
463
464   my %escape_functions = ( 'latex'    => \&_latex_escape,
465                            'html'     => \&_html_escape_nbsp,#\&encode_entities,
466                            'template' => sub { shift },
467                          );
468   my $escape_function = $escape_functions{$format};
469   my $escape_function_nonbsp = ($format eq 'html')
470                                  ? \&_html_escape : $escape_function;
471
472   my %newline_tokens = (  'latex'     => '\\\\',
473                           'html'      => '<br>',
474                           'template'  => "\n",
475                         );
476   my $newline_token = $newline_tokens{$format};
477
478   warn "$me generating template variables\n"
479     if $DEBUG > 1;
480
481   # generate template variables
482   my $returnaddress;
483
484   if (
485          defined( $conf->config_orbase( "invoice_${format}returnaddress",
486                                         $template
487                                       )
488                 )
489        && length( $conf->config_orbase( "invoice_${format}returnaddress",
490                                         $template
491                                       )
492                 )
493   ) {
494
495     $returnaddress = join("\n",
496       $conf->config_orbase("invoice_${format}returnaddress", $template)
497     );
498
499   } elsif ( grep /\S/,
500             $conf->config_orbase('invoice_latexreturnaddress', $template) ) {
501
502     my $convert_map = $convert_maps{$format}{'returnaddress'};
503     $returnaddress =
504       join( "\n",
505             &$convert_map( $conf->config_orbase( "invoice_latexreturnaddress",
506                                                  $template
507                                                )
508                          )
509           );
510   } elsif ( grep /\S/, $conf->config('company_address', $cust_main->agentnum) ) {
511
512     my $convert_map = $convert_maps{$format}{'returnaddress'};
513     $returnaddress = join( "\n", &$convert_map(
514                                    map { s/( {2,})/'~' x length($1)/eg;
515                                          s/$/\\\\\*/;
516                                          $_
517                                        }
518                                      ( $conf->config('company_name', $cust_main->agentnum),
519                                        $conf->config('company_address', $cust_main->agentnum),
520                                      )
521                                  )
522                      );
523
524   } else {
525
526     my $warning = "Couldn't find a return address; ".
527                   "do you need to set the company_address configuration value?";
528     warn "$warning\n";
529     $returnaddress = $nbsp;
530     #$returnaddress = $warning;
531
532   }
533
534   warn "$me generating invoice data\n"
535     if $DEBUG > 1;
536
537   my $agentnum = $cust_main->agentnum;
538
539   my %invoice_data = (
540
541     #invoice from info
542     'company_name'    => scalar( $conf->config('company_name', $agentnum) ),
543     'company_address' => join("\n", $conf->config('company_address', $agentnum) ). "\n",
544     'company_phonenum'=> scalar( $conf->config('company_phonenum', $agentnum) ),
545     'returnaddress'   => $returnaddress,
546     'agent'           => &$escape_function($cust_main->agent->agent),
547
548     #invoice/quotation info
549     'no_number'       => $params{'no_number'},
550     'invnum'          => ( $params{'no_number'} ? '' : $self->invnum ),
551     'quotationnum'    => $self->quotationnum,
552     'no_date'         => $params{'no_date'},
553     '_date'           => ( $params{'no_date'} ? '' : $self->_date ),
554       # workaround for inconsistent behavior in the early plain text
555       # templates; see RT#28271
556     'date'            => ( $params{'no_date'}
557                              ? ''
558                              : ($format eq 'template'
559                                ? $self->_date
560                                : $self->time2str_local('long', $self->_date, $format)
561                                )
562                          ),
563     'today'           => $self->time2str_local('long', $today, $format),
564     'terms'           => $self->terms,
565     'template'        => $template, #params{'template'},
566     'notice_name'     => $notice_name, # escape?
567     'current_charges' => sprintf("%.2f", $self->charged),
568     'duedate'         => $self->due_date2str('rdate'), #date_format?
569     'duedate_long'    => $self->due_date2str('long'),
570
571     #customer info
572     'custnum'         => $cust_main->display_custnum,
573     'prospectnum'     => $cust_main->prospectnum,
574     'agent_custid'    => &$escape_function($cust_main->agent_custid),
575     ( map { $_ => &$escape_function($cust_main->$_()) }
576         qw( company address1 address2 city state zip fax )
577     ),
578     'payname'         => &$escape_function( $cust_main->invoice_attn
579                                              || $cust_main->contact_firstlast ),
580
581     #global config
582     'ship_enable'     => $cust_main->invoice_ship_address || $conf->exists('invoice-ship_address'),
583     'unitprices'      => $conf->exists('invoice-unitprice'),
584     'smallernotes'    => $conf->exists('invoice-smallernotes'),
585     'smallerfooter'   => $conf->exists('invoice-smallerfooter'),
586     'balance_due_below_line' => $conf->exists('balance_due_below_line'),
587
588     #layout info -- would be fancy to calc some of this and bury the template
589     #               here in the code
590     'topmargin'             => scalar($conf->config('invoice_latextopmargin', $agentnum)),
591     'headsep'               => scalar($conf->config('invoice_latexheadsep', $agentnum)),
592     'textheight'            => scalar($conf->config('invoice_latextextheight', $agentnum)),
593     'extracouponspace'      => scalar($conf->config('invoice_latexextracouponspace', $agentnum)),
594     'couponfootsep'         => scalar($conf->config('invoice_latexcouponfootsep', $agentnum)),
595     'verticalreturnaddress' => $conf->exists('invoice_latexverticalreturnaddress', $agentnum),
596     'addresssep'            => scalar($conf->config('invoice_latexaddresssep', $agentnum)),
597     'amountenclosedsep'     => scalar($conf->config('invoice_latexcouponamountenclosedsep', $agentnum)),
598     'coupontoaddresssep'    => scalar($conf->config('invoice_latexcoupontoaddresssep', $agentnum)),
599     'addcompanytoaddress'   => $conf->exists('invoice_latexcouponaddcompanytoaddress', $agentnum),
600     'couponlocation'        => (scalar($conf->config('invoice_latexcouponlocation', $agentnum)) eq "top") ? 'top' : 'bottom',
601
602     # better hang on to conf_dir for a while (for old templates)
603     'conf_dir'        => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
604
605     #these are only used when doing paged plaintext
606     'page'            => 1,
607     'total_pages'     => 1,
608
609   );
610
611   #quotations have $name
612   $invoice_data{'name'} = $invoice_data{'payname'};
613
614   #localization
615   $invoice_data{'emt'} = sub { &$escape_function($self->mt(@_)) };
616   # prototype here to silence warnings
617   $invoice_data{'time2str'} = sub ($;$$) { $self->time2str_local(@_, $format) };
618
619   my $min_sdate = 999999999999;
620   my $max_edate = 0;
621   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
622     next unless $cust_bill_pkg->pkgnum > 0;
623     $min_sdate = $cust_bill_pkg->sdate
624       if length($cust_bill_pkg->sdate) && $cust_bill_pkg->sdate < $min_sdate;
625     $max_edate = $cust_bill_pkg->edate
626       if length($cust_bill_pkg->edate) && $cust_bill_pkg->edate > $max_edate;
627   }
628
629   $invoice_data{'bill_period'} = '';
630   $invoice_data{'bill_period'} =
631       $self->time2str_local('%e %h', $min_sdate, $format)
632       . " to " .
633       $self->time2str_local('%e %h', $max_edate, $format)
634     if ($max_edate != 0 && $min_sdate != 999999999999);
635
636   $invoice_data{finance_section} = '';
637   if ( $conf->config('finance_pkgclass') ) {
638     my $pkg_class =
639       qsearchs('pkg_class', { classnum => $conf->config('finance_pkgclass') });
640     $invoice_data{finance_section} = $pkg_class->categoryname;
641   }
642   $invoice_data{finance_amount} = '0.00';
643   $invoice_data{finance_section} ||= 'Finance Charges'; #avoid config confusion
644
645   my $countrydefault = $conf->config('countrydefault') || 'US';
646   foreach ( qw( address1 address2 city state zip country fax) ){
647     my $method = 'ship_'.$_;
648     $invoice_data{"ship_$_"} = $escape_function->($cust_main->$method);
649   }
650   if ( length($cust_main->ship_company) ) {
651     $invoice_data{'ship_company'} = $escape_function->($cust_main->ship_company);
652   } else {
653     $invoice_data{'ship_company'} = $escape_function->($cust_main->company);
654   }
655   $invoice_data{'ship_contact'} = $escape_function->($cust_main->contact);
656   $invoice_data{'ship_country'} = ''
657     if ( $invoice_data{'ship_country'} eq $countrydefault );
658
659   $invoice_data{'cid'} = $params{'cid'}
660     if $params{'cid'};
661
662   if ( $cust_main->bill_locationnum
663        && $cust_main->bill_location->country ne $countrydefault ) {
664     $invoice_data{'country'} = &$escape_function($cust_main->bill_country_full);
665   } else {
666     $invoice_data{'country'} = '';
667   }
668
669   my @address = ();
670   $invoice_data{'address'} = \@address;
671   push @address,
672     $invoice_data{'payname'}.
673       ( $cust_main->po_number
674           ? " (P.O. #". $cust_main->po_number. ")"
675           : ''
676       )
677   ;
678   push @address, $cust_main->company
679     if $cust_main->company;
680   push @address, $cust_main->address1;
681   push @address, $cust_main->address2
682     if $cust_main->address2;
683   push @address,
684     $cust_main->city. ", ". $cust_main->state. "  ".  $cust_main->zip;
685   push @address, $invoice_data{'country'}
686     if $invoice_data{'country'};
687   push @address, ''
688     while (scalar(@address) < 5);
689
690   $invoice_data{'logo_file'} = $params{'logo_file'}
691     if $params{'logo_file'};
692   $invoice_data{'barcode_file'} = $params{'barcode_file'}
693     if $params{'barcode_file'};
694   $invoice_data{'barcode_img'} = $params{'barcode_img'}
695     if $params{'barcode_img'};
696   $invoice_data{'barcode_cid'} = $params{'barcode_cid'}
697     if $params{'barcode_cid'};
698
699
700   # re: rt:78190
701   #   using owed_on_invoice() instead of owed() here for $balance_due
702   #   using _items_previous_total() instead of ->previous() for $pr_total
703   #
704   #   owed_on_invoice() is aware of configuration flags that affect how an
705   #     invoice is rendered.  May not return actual current balance. Will
706   #     return balance appropriate for the invoice being rendered, based
707   #     on which past due items, current charges, and future payments are
708   #     displayed.
709   #
710   #   Going forward, usage of owed(), or bypassing cust_bill helper methods
711   #     when generating invoice lines may lead to incorrect or misleading
712   #     math on invoices.
713   #
714   #   Helper methods that are aware of invoicing conf flags:
715   #   - owed_on_invoice          # use instead of owed()
716   #   - _items_previous()        # use instead of previous()
717   #   - _items_credits()         # use instead of cust_credit()
718   #   - _items_payments()
719   #   - _items_total()
720   #   - _items_previous_total()  # use instead of previous()
721   #   - _items_payments_total()
722   #   - _items_credits_total()   # use instead of cust_credit()
723
724   my $pr_total    = $self->_items_previous_total();
725
726   my $balance_due = $self->owed_on_invoice();
727   $invoice_data{'balance'} = sprintf("%.2f", $balance_due);
728
729   # flag telling this invoice to have a first-page summary
730   my $summarypage = '';
731
732   if ( $self->custnum && $self->invnum ) {
733     # XXX should be an FS::cust_bill method to set the defaults, instead
734     # of checking the type here
735
736     # info from customer's last invoice before this one, for some
737     # summary formats
738     $invoice_data{'last_bill'} = {};
739
740     #    my $last_bill = $self->previous_bill;
741     # if ( $last_bill ) {
742
743     # Populate template stash for previous balance and payments
744     if ($pr_total) {
745       # Used on summary page as "Previous Balance"
746       $invoice_data{'true_previous_balance'} = sprintf("%.2f", $pr_total);
747
748       # Used on summary page as "Payments"
749       $invoice_data{'balance_adjustments'} = sprintf("%.2f",
750         $self->_items_payments_total() + $self->_items_credits_total()
751       );
752
753       # Used in invoice template as "Previous Balance"
754       $invoice_data{'previous_balance'} = sprintf("%.2f", $pr_total);
755
756       # $invoice_data{last_bill}{_date}:
757       # Not used in default templates, but may be in use by someone
758       #
759       # ! May be a problem field if they are using it... this field
760       #   stores the date of the previous invoice... it is possible to
761       #   carry a balance, but have the immediately previous invoice paid off.
762       #   In this case, this field might be presenting bad data?  Not
763       #   altering the problematic behavior, because someone might be
764       #   expecting this bad behavior in their templates for some other
765       #   purpose, such as a "your last bill was dated %_date%"
766       my $last_bill = $self->previous_bill;
767       $invoice_data{'last_bill'}{'_date'}
768         = ref $last_bill
769         ? $last_bill->_date()
770         : undef;
771
772       # $invoice_data{previous_payments}
773       # Not used in default templates, but may be in use by someone
774       #
775       # Returns an array of hrefs representing payments, each with keys:
776       #  - _date:       epoch timestamp
777       #  - date:        text formatted date
778       #  - amount:      money formatted amount string
779       #  - payinfo:     string from payby_payinfo_pretty()
780       #  - paynum:      id for cust_pay
781       #  - description: Text description for bill line item
782       #
783       my @payments = $self->_items_payments();
784       $invoice_data{previous_payments} = \@payments;
785
786       # $invoice_data{previous_credits}
787       # Not used in default templates, but may be in use by someone
788       #
789       # Returns an array of hrefs representing credits, each with keys:
790       #  - _date:        epoch timestamp
791       #  - date:         text formatted date
792       #  - amount:       money formatted amount string
793       #  - crednum:      id for cust_credit
794       #  - description:  Text description for bill line item
795       #  - creditreason: reason() from cust_credit
796       #
797       my @credits = $self->_items_credits();
798       $invoice_data{previous_credits} = \@credits;
799
800       # Populate formatted date field
801       for my $pmt_href (@payments, @credits) {
802         $pmt_href->{date} = $self->time2str_local(
803           'long',
804           $pmt_href->{_date},
805           $format
806         );
807       }
808
809     } else {
810       # There are no outstanding invoices    = YAPH
811       $invoice_data{'true_previous_balance'} =
812       $invoice_data{'balance_adjustments'}   =
813       $invoice_data{'previous_balance'}      = '0.00';
814       $invoice_data{'previous_payments'}     =
815       $invoice_data{'previous_credits'}      = [];
816     }
817
818     # Condencing a lot of debug staements here
819     if ($DEBUG) {
820       warn "\$invoice_data{$_}: $invoice_data{$_}"
821         for qw(
822           true_previous_balance
823           balance_adjustments
824           previous_balance
825           previous_payments
826           previous_credits
827         );
828     }
829
830     if ( $conf->config_bool('invoice_usesummary', $agentnum) ) {
831       $invoice_data{'summarypage'} = $summarypage = 1;
832     }
833
834   } # if this is an invoice
835
836   warn "$me substituting variables in notes, footer, smallfooter\n"
837     if $DEBUG > 1;
838
839   my $tc = $self->template_conf;
840   my @include = ( [ $tc,        'notes' ],
841                   [ 'invoice_', 'footer' ],
842                   [ 'invoice_', 'smallfooter', ],
843                   [ 'invoice_', 'watermark' ],
844                 );
845   push @include, [ $tc,        'coupon', ]
846     unless $params{'no_coupon'};
847
848   foreach my $i (@include) {
849
850     # load the configuration for this sub-template
851
852     my($base, $include) = @$i;
853
854     my $inc_file = $conf->key_orbase("$base$format$include", $template);
855
856     my @inc_src = $conf->config($inc_file, $agentnum);
857     if (!@inc_src) {
858       my $converter = $convert_maps{$format}{$include};
859       if ( $converter ) {
860         # then attempt to convert LaTeX to the requested format
861         $inc_file = $conf->key_orbase($base.'latex'.$include, $template);
862         @inc_src = &$converter( $conf->config($inc_file, $agentnum) );
863         foreach (@inc_src) {
864           # this isn't included in the convert_maps
865           my ($open, $close) = @{ $delimiters{$format} };
866           s/\[\@--/$open/g;
867           s/--\@\]/$close/g;
868         }
869       }
870     } # else @inc_src is empty and that's fine
871
872     # make a Text::Template out of it
873
874     my $inc_tt = new Text::Template (
875       TYPE       => 'ARRAY',
876       SOURCE     => [ map "$_\n", @inc_src ],
877       DELIMITERS => $delimiters{$format},
878     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
879
880     unless ( $inc_tt->compile() ) {
881       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
882       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
883       die $error;
884     }
885
886     # fill in variables
887
888     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
889
890     $invoice_data{$include} =~ s/\n+$//
891       if ($format eq 'latex');
892   }
893
894 # if (well, probably when) we still need PO numbers in the brave new world of
895 # 4.x, then we'll have to add them back as their own customer fields
896 #  # let invoices use either of these as needed
897 #  $invoice_data{'po_num'} = ($cust_main->payby eq 'BILL')
898 #    ? $cust_main->payinfo : '';
899 #  $invoice_data{'po_line'} =
900 #    (  $cust_main->payby eq 'BILL' && $cust_main->payinfo )
901 #      ? &$escape_function($self->mt("Purchase Order #").$cust_main->payinfo)
902 #      : $nbsp;
903
904   my %money_chars = ( 'latex'    => '',
905                       'html'     => $conf->config('money_char') || '$',
906                       'template' => '',
907                     );
908   my $money_char = $money_chars{$format};
909
910   # extremely dubious
911   my %other_money_chars = ( 'latex'    => '\dollar ',#XXX should be a config too
912                             'html'     => $conf->config('money_char') || '$',
913                             'template' => '',
914                           );
915   my $other_money_char = $other_money_chars{$format};
916   $invoice_data{'dollar'} = $other_money_char;
917
918   my %minus_signs = ( 'latex'    => '$-$',
919                       'html'     => '&minus;',
920                       'template' => '- ' );
921   my $minus = $minus_signs{$format};
922
923   my @detail_items = ();
924   my @total_items = ();
925   my @buf = ();
926   my @sections = ();
927
928   $invoice_data{'detail_items'} = \@detail_items;
929   $invoice_data{'total_items'} = \@total_items;
930   $invoice_data{'buf'} = \@buf;
931   $invoice_data{'sections'} = \@sections;
932
933   warn "$me generating sections\n"
934     if $DEBUG > 1;
935
936   my $unsquelched = $params{unsquelch_cdr} || $cust_main->squelch_cdr ne 'Y';
937   my $multisection = $self->has_sections;
938   if ( $multisection ) {
939     $invoice_data{multisection} = $conf->config($tc.'sections_method') || 1;
940   }
941   my $late_sections;
942   my $extra_sections = [];
943   my $extra_lines = ();
944
945   # default section ('Charges')
946   my $default_section = { 'description' => '',
947                           'subtotal'    => '',
948                           'no_subtotal' => 1,
949                         };
950
951   # Previous Charges section
952   # subtotal is the first return value from $self->previous
953   my $previous_section;
954   # if the invoice has major sections, or if we're summarizing previous
955   # charges with a single line, or if we've been specifically told to put them
956   # in a section, create a section for previous charges:
957   if ( $multisection or
958        $conf->exists('previous_balance-summary_only') or
959        $conf->exists('previous_balance-section') ) {
960
961     $previous_section =  { 'description' => $self->mt('Previous Charges'),
962                            'subtotal'    => $other_money_char.
963                                             sprintf('%.2f', $pr_total),
964                            'summarized'  => '', #why? $summarypage ? 'Y' : '',
965                          };
966
967     # Include balance aging line and template variables
968     my @aged_balances = $self->_items_aging_balances();
969     ( $invoice_data{aged_balance_current},
970       $invoice_data{aged_balance_30d},
971       $invoice_data{aged_balance_60d},
972       $invoice_data{aged_balance_90d}
973     ) = @aged_balances;
974
975     if ($conf->exists('invoice_include_aging')) {
976       $previous_section->{posttotal} = sprintf(
977         '0 / 30 / 60 / 90 days overdue %.2f / %.2f / %.2f / %.2f',
978         @aged_balances,
979       );
980     }
981
982   } else {
983     # otherwise put them in the main section
984     $previous_section = $default_section;
985   }
986
987   my $adjust_section = {
988     'description'    => $self->mt('Credits, Payments, and Adjustments'),
989     'adjust_section' => 1,
990     'subtotal'       => 0,   # adjusted below
991   };
992   my $adjust_weight = _pkg_category($adjust_section->{description})
993                         ? _pkg_category($adjust_section->{description})->weight
994                         : 0;
995   $adjust_section->{'summarized'} = ''; #why? $summarypage && !$adjust_weight ? 'Y' : '';
996   # Note: 'sort_weight' here is actually a flag telling whether there is an
997   # explicit package category for the adjust section. If so, certain behavior
998   # happens.
999   $adjust_section->{'sort_weight'} = $adjust_weight;
1000
1001
1002   if ( $multisection ) {
1003     ($extra_sections, $extra_lines) =
1004       $self->_items_extra_usage_sections($escape_function_nonbsp, $format)
1005       if $conf->exists('usage_class_as_a_section', $cust_main->agentnum)
1006       && $self->can('_items_extra_usage_sections');
1007
1008     push @$extra_sections, $adjust_section if $adjust_section->{sort_weight};
1009
1010     push @detail_items, @$extra_lines if $extra_lines;
1011
1012     # the code is written so that both methods can be used together, but
1013     # we haven't yet changed the template to take advantage of that, so for
1014     # now, treat them as mutually exclusive.
1015     my %section_method = ( by_category => 1 );
1016     if ( $conf->config($tc.'sections_method') eq 'location' ) {
1017       %section_method = ( by_location => 1 );
1018     }
1019     my ($early, $late) =
1020       $self->_items_sections( 'summary' => $summarypage,
1021                               'escape'  => $escape_function_nonbsp,
1022                               'extra_sections' => $extra_sections,
1023                               'format'  => $format,
1024                               %section_method
1025                             );
1026     push @sections, @$early;
1027     $late_sections = $late;
1028
1029     if (    $conf->exists('svc_phone_sections')
1030          && $self->can('_items_svc_phone_sections')
1031        )
1032     {
1033       my ($phone_sections, $phone_lines) =
1034         $self->_items_svc_phone_sections($escape_function_nonbsp, $format);
1035       push @{$late_sections}, @$phone_sections;
1036       push @detail_items, @$phone_lines;
1037     }
1038     if ( $conf->exists('voip-cust_accountcode_cdr')
1039          && $cust_main->accountcode_cdr
1040          && $self->can('_items_accountcode_cdr')
1041        )
1042     {
1043       my ($accountcode_section, $accountcode_lines) =
1044         $self->_items_accountcode_cdr($escape_function_nonbsp,$format);
1045       if ( scalar(@$accountcode_lines) ) {
1046           push @{$late_sections}, $accountcode_section;
1047           push @detail_items, @$accountcode_lines;
1048       }
1049     }
1050   } else {# not multisection
1051     # make a default section
1052     push @sections, $default_section;
1053     # and calculate the finance charge total, since it won't get done otherwise.
1054     # and the default section total
1055     # XXX possibly finance_pkgclass should not be used in this manner?
1056     my @finance_charges;
1057     my @charges;
1058     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1059       if ( $invoice_data{finance_section} and
1060         grep { $_->section eq $invoice_data{finance_section} }
1061            $cust_bill_pkg->cust_bill_pkg_display ) {
1062         # I think these are always setup fees, but just to be sure...
1063         push @finance_charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1064       } else {
1065         push @charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1066       }
1067     }
1068     $invoice_data{finance_amount} =
1069       sprintf('%.2f', sum( @finance_charges ) || 0);
1070     $default_section->{subtotal} = $other_money_char.
1071                                     sprintf('%.2f', sum( @charges ) || 0);
1072   }
1073
1074   # start setting up summary subtotals
1075   my @summary_subtotals;
1076   my $method = $conf->config('summary_subtotals_method');
1077   if ( $method and $method ne $conf->config($tc.'sections_method') ) {
1078     # then re-section them by the correct method
1079     my %section_method = ( by_category => 1 );
1080     if ( $conf->config('summary_subtotals_method') eq 'location' ) {
1081       %section_method = ( by_location => 1 );
1082     }
1083     my ($early, $late) =
1084       $self->_items_sections( 'summary' => $summarypage,
1085                               'escape'  => $escape_function_nonbsp,
1086                               'extra_sections' => $extra_sections,
1087                               'format'  => $format,
1088                               %section_method
1089                             );
1090     foreach ( @$early ) {
1091       next if $_->{subtotal} == 0;
1092       $_->{subtotal} = $other_money_char.sprintf('%.2f', $_->{subtotal});
1093       push @summary_subtotals, $_;
1094     }
1095   } else {
1096     # subtotal sectioning is the same as for the actual invoice sections
1097     @summary_subtotals = @sections;
1098   }
1099
1100   # Hereafter, push sections to both @sections and @summary_subtotals
1101   # if they belong in both places (e.g. tax section).  Late sections are
1102   # never in @summary_subtotals.
1103
1104   # previous invoice balances in the Previous Charges section if there
1105   # is one, otherwise in the main detail section
1106   # (except if summary_only is enabled, don't show them at all)
1107   if ( $self->can('_items_previous') &&
1108        $self->enable_previous &&
1109        ! $conf->exists('previous_balance-summary_only') ) {
1110
1111     warn "$me adding previous balances\n"
1112       if $DEBUG > 1;
1113
1114     foreach my $line_item ( $self->_items_previous ) {
1115
1116       my $detail = {
1117         ref             => $line_item->{'pkgnum'},
1118         pkgpart         => $line_item->{'pkgpart'},
1119         #quantity        => 1, # not really correct
1120         section         => $previous_section, # which might be $default_section
1121         description     => &$escape_function($line_item->{'description'}),
1122         ext_description => [ map { &$escape_function($_) }
1123                              @{ $line_item->{'ext_description'} || [] }
1124                            ],
1125         amount          => $money_char . $line_item->{'amount'},
1126         product_code    => $line_item->{'pkgpart'} || 'N/A',
1127       };
1128
1129       push @detail_items, $detail;
1130       push @buf, [ $detail->{'description'},
1131                    $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1132                  ];
1133     }
1134
1135   }
1136
1137   if ( $pr_total && $self->enable_previous ) {
1138     push @buf, ['','-----------'];
1139     push @buf, [ $self->mt('Total Previous Balance'),
1140                  $money_char. sprintf("%10.2f", $pr_total) ];
1141     push @buf, ['',''];
1142   }
1143
1144   if ( $conf->exists('svc_phone-did-summary') && $self->can('_did_summary') ) {
1145       warn "$me adding DID summary\n"
1146         if $DEBUG > 1;
1147
1148       my ($didsummary,$minutes) = $self->_did_summary;
1149       my $didsummary_desc = 'DID Activity Summary (since last invoice)';
1150       push @detail_items,
1151        { 'description' => $didsummary_desc,
1152            'ext_description' => [ $didsummary, $minutes ],
1153        };
1154   }
1155
1156   foreach my $section (@sections, @$late_sections) {
1157
1158     # begin some normalization
1159     $section->{'subtotal'} = $section->{'amount'}
1160       if $multisection
1161          && !exists($section->{subtotal})
1162          && exists($section->{amount});
1163
1164     $invoice_data{finance_amount} = sprintf('%.2f', $section->{'subtotal'} )
1165       if ( $invoice_data{finance_section} &&
1166            $section->{'description'} eq $invoice_data{finance_section} );
1167
1168     if ( $multisection ) {
1169
1170       if ( ref($section->{'subtotal'}) ) {
1171
1172         $section->{'subtotal'} =
1173           sprintf("$other_money_char%.2f to $other_money_char%.2f",
1174                     $section->{'subtotal'}[0],
1175                     $section->{'subtotal'}[1]
1176                  );
1177
1178       } else {
1179
1180         $section->{'subtotal'} = $other_money_char.
1181                                  sprintf('%.2f', $section->{'subtotal'})
1182
1183       }
1184
1185       # continue some normalization
1186       $section->{'amount'}   = $section->{'subtotal'}
1187
1188     }
1189
1190     if ( $section->{'description'} ) {
1191       push @buf, ( [ &$escape_function($section->{'description'}), '' ],
1192                    [ '', '' ],
1193                  );
1194     }
1195
1196     warn "$me   setting options\n"
1197       if $DEBUG > 1;
1198
1199     my %options = ();
1200     $options{'section'} = $section if $multisection;
1201     $options{'section_with_taxes'} = 1
1202       if $multisection
1203       && $conf->config_bool('invoice_sections_with_taxes', $cust_main->agentnum);
1204     $options{'format'} = $format;
1205     $options{'escape_function'} = $escape_function;
1206     $options{'no_usage'} = 1 unless $unsquelched;
1207     $options{'unsquelched'} = $unsquelched;
1208     $options{'summary_page'} = $summarypage;
1209     $options{'skip_usage'} =
1210       scalar(@$extra_sections) && !grep{$section == $_} @$extra_sections;
1211     $options{'preref_callback'} = $params{'preref_callback'};
1212     $options{'disable_line_item_date_ranges'} =
1213       $conf->exists('disable_line_item_date_ranges');
1214
1215     warn "$me   searching for line items\n"
1216       if $DEBUG > 1;
1217
1218     my %section_tax_lines;
1219     my %seen_tax_lines;
1220     foreach my $line_item ( $self->_items_pkg(%options),
1221                             $self->_items_fee(%options) ) {
1222
1223       # When bill is sectioned by location, fees may be displayed within the
1224       # appropriate location section.  Suppress this fee from the taxes/fees
1225       # end section, so it doesn't appear to be charged twice and make the
1226       # subtotals seem incorrect
1227       next
1228         if $line_item->{locationnum}
1229         && ref $options{section}
1230         && !exists $options{section}->{locationnum}
1231         && $self->has_sections
1232         && $conf->config($tc.'sections_method') eq 'location';
1233
1234       warn "$me     adding line item ".
1235            join(', ', map "$_=>".$line_item->{$_}, keys %$line_item). "\n"
1236         if $DEBUG > 1;
1237
1238       push @buf, ( [ $line_item->{'description'},
1239                      $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1240                    ],
1241                    map { [ " ". $_, '' ] } @{$line_item->{'ext_description'}},
1242                  );
1243
1244       $line_item->{'ref'} = $line_item->{'pkgnum'};
1245       $line_item->{'product_code'} = $line_item->{'pkgpart'} || 'N/A'; # mt()?
1246       $line_item->{'section'} = $section;
1247       $line_item->{'description'} = &$escape_function($line_item->{'description'});
1248       $line_item->{'amount'} = $money_char.$line_item->{'amount'};
1249
1250       if ( length($line_item->{'unit_amount'}) ) {
1251         $line_item->{'unit_amount'} = $money_char.$line_item->{'unit_amount'};
1252       }
1253       $line_item->{'ext_description'} ||= [];
1254
1255       if ( $options{section_with_taxes} && ref $line_item->{pkg_tax} ) {
1256         for my $line_tax ( @{$ line_item->{pkg_tax} } ) {
1257
1258           # It is rarely possible for the same tax record to be presented here
1259           # multiple times.  See cust_bill_pkg::_pkg_tax_list for more info
1260           next if $seen_tax_lines{ $line_tax->{billpkgtaxlocationnum} };
1261           $seen_tax_lines{ $line_tax->{billpkgtaxlocationnum} } = 1;
1262
1263           $section_tax_lines{ $line_tax->{taxname} } += $line_tax->{amount};
1264         }
1265       }
1266
1267       push @detail_items, $line_item;
1268     }
1269
1270     # If conf flag invoice_sections_with_taxes:
1271     # - Add @detail_items for taxes into each section
1272     # - Update section subtotal to include taxes
1273     if ( $options{section_with_taxes} && %section_tax_lines ) {
1274       for my $taxname ( keys %section_tax_lines ) {
1275
1276         push @detail_items, {
1277           section => $section,
1278           amount  => sprintf($money_char."%.2f",$section_tax_lines{$taxname}),
1279           description => &$escape_function($taxname),
1280         };
1281
1282         # Append taxes to total.  If line format resembles "$5.00 to $12.00"
1283         # append to the second value.
1284
1285         # $section->{subtotal} = '$5.00 to 12.00'; # for testing:
1286         if ($section->{subtotal} =~ /to/) {
1287           my @subtotal = split /\s/, $section->{subtotal};
1288           $subtotal[2] =~ s/[^\d\.]//g;
1289           $subtotal[2] = sprintf(
1290             $money_char."%.2f",
1291             ( $subtotal[2] + $section_tax_lines{$taxname} )
1292           );
1293           $section->{subtotal} = join ' ', @subtotal;
1294         } else {
1295           $section->{subtotal} =~ s/[^\d\.]//g;
1296           $section->{subtotal} = sprintf(
1297             $money_char . "%.2f",
1298             ( $section->{subtotal} + $section_tax_lines{$taxname} )
1299           );
1300         }
1301
1302       }
1303     }
1304
1305     if ( $section->{'description'} ) {
1306       push @buf, ( ['','-----------'],
1307                    [ $section->{'description'}. ' sub-total',
1308                       $section->{'subtotal'} # already formatted this
1309                    ],
1310                    [ '', '' ],
1311                    [ '', '' ],
1312                  );
1313     }
1314
1315   }
1316
1317   $invoice_data{current_less_finance} =
1318     sprintf('%.2f', $self->charged - $invoice_data{finance_amount} );
1319
1320   # if there's anything in the Previous Charges section, prepend it to the list
1321   if ( $pr_total and $previous_section ne $default_section ) {
1322     unshift @sections, $previous_section;
1323     # but not @summary_subtotals
1324   }
1325
1326   warn "$me adding taxes\n"
1327     if $DEBUG > 1;
1328
1329   # create a tax section if we don't yet have one
1330   my @items_tax = $self->_items_tax;
1331   my $tax_description = 'Taxes, Surcharges, and Fees';
1332   my $tax_section =
1333     List::Util::first { $_->{description} eq $tax_description } @sections;
1334   if (!$tax_section) {
1335     $tax_section = { 'description' => $tax_description };
1336     push @sections, $tax_section if $multisection and @items_tax > 0;
1337   }
1338   $tax_section->{tax_section} = 1; # mark this section as containing taxes
1339   # if this is an existing tax section, we're merging the tax items into it.
1340   # grab the taxtotal that's already there, strip the money symbol if any
1341   my $taxtotal = $tax_section->{'subtotal'} || 0;
1342   $taxtotal =~ s/^\Q$other_money_char\E//;
1343
1344   # this does nothing
1345   #my $tax_weight = _pkg_category($tax_section->{description})
1346   #                      ? _pkg_category($tax_section->{description})->weight
1347   #                      : 0;
1348   #$tax_section->{'summarized'} = ''; #why? $summarypage && !$tax_weight ? 'Y' : '';
1349   #$tax_section->{'sort_weight'} = $tax_weight;
1350
1351   my $invoice_sections_with_taxes = $conf->config_bool(
1352     'invoice_sections_with_taxes', $cust_main->agentnum
1353   );
1354
1355   foreach my $tax ( @items_tax ) {
1356
1357
1358     my $description = &$escape_function( $tax->{'description'} );
1359     my $amount      = sprintf( '%.2f', $tax->{'amount'} );
1360
1361     if ( $multisection ) {
1362       if ( !$invoice_sections_with_taxes ) {
1363
1364         $taxtotal += $tax->{'amount'};
1365
1366         push @detail_items, {
1367           ext_description => [],
1368           ref          => '',
1369           quantity     => '',
1370           description  => $description,
1371           amount       => $money_char. $amount,
1372           product_code => '',
1373           section      => $tax_section,
1374         };
1375
1376       }
1377     } else {
1378
1379       $taxtotal += $tax->{'amount'};
1380
1381       push @total_items, {
1382         'total_item'   => $description,
1383         'total_amount' => $other_money_char. $amount,
1384       };
1385
1386     }
1387
1388     push @buf,[ $description,
1389                 $money_char. $amount,
1390               ];
1391
1392   }
1393
1394   if ( @items_tax ) {
1395     my $total = {};
1396     $total->{'total_item'} = $self->mt('Sub-total');
1397     $total->{'total_amount'} =
1398       $other_money_char. sprintf('%.2f', $self->charged - $taxtotal );
1399
1400     if ( $multisection ) {
1401
1402       if ( $conf->config_bool('invoice_sections_with_taxes', $cust_main->agentnum) ) {
1403         # If all tax items are displayed in location/category sections,
1404         # remove the empty tax section
1405         @sections = grep{ $_ ne $tax_section } @sections
1406           unless grep{ $_->{section} eq $tax_section } @detail_items;
1407       }
1408
1409       if ( $taxtotal > 0 ) {
1410         # there are taxes, so prepare the section to be displayed.
1411         # $taxtotal already includes any line items that were already in the
1412         # section (fees, taxes that are charged as packages for some reason).
1413         # also set 'summarized' to false so that this isn't a summary-only
1414         # section.
1415         $tax_section->{'subtotal'} = $other_money_char.
1416                                      sprintf('%.2f', $taxtotal);
1417         $tax_section->{'pretotal'} = 'New charges sub-total '.
1418                                      $total->{'total_amount'};
1419         $tax_section->{'description'} = $self->mt($tax_description);
1420         $tax_section->{'summarized'} = '';
1421
1422         # append tax section unless it's already there
1423         push @sections, $tax_section
1424           unless grep {$_ eq $tax_section} @sections;
1425
1426         push @summary_subtotals, $tax_section
1427           unless grep {$_ eq $tax_section} @summary_subtotals;
1428
1429       }
1430     } else {
1431       unshift @total_items, $total;
1432     }
1433   }
1434   $invoice_data{'taxtotal'} = sprintf('%.2f', $taxtotal);
1435
1436   ###
1437   # Totals
1438   ###
1439
1440   my %embolden_functions = (
1441     'latex'    => sub { return '\textbf{'. shift(). '}' },
1442     'html'     => sub { return '<b>'. shift(). '</b>' },
1443     'template' => sub { shift },
1444   );
1445   my $embolden_function = $embolden_functions{$format};
1446
1447   if ( $multisection ) {
1448
1449     if ( $adjust_section->{'sort_weight'} ) {
1450       $adjust_section->{'posttotal'} = $self->mt('Balance Forward').' '.
1451         $other_money_char.  sprintf("%.2f", ($self->billing_balance || 0) );
1452     } else{
1453       $adjust_section->{'pretotal'} = $self->mt('New charges total').' '.
1454         $other_money_char.  sprintf('%.2f', $self->charged );
1455     }
1456
1457   }
1458
1459   if ( $self->can('_items_total') ) { # should always be true now
1460
1461     # even for multisection, need plain text version
1462
1463     my @new_total_items = $self->_items_total;
1464
1465     push @buf,['','-----------'];
1466
1467     foreach ( @new_total_items ) {
1468       my ($item, $amount) = ($_->{'total_item'}, $_->{'total_amount'});
1469       $_->{'total_item'}   = &$embolden_function( $item );
1470
1471       if ( ref($amount) ) {
1472         $_->{'total_amount'} = &$embolden_function(
1473                                  $other_money_char.$amount->[0]. ' to '.
1474                                  $other_money_char.$amount->[1]
1475                                );
1476       } else {
1477         $_->{'total_amount'} = &$embolden_function( $other_money_char.$amount );
1478       }
1479
1480       # but if it's multisection, don't append to @total_items. the adjust
1481       # section has all this stuff
1482       push @total_items, $_ if !$multisection;
1483       push @buf, [ $item, $money_char.sprintf('%10.2f',$amount) ];
1484     }
1485
1486     push @buf, [ '', '' ];
1487
1488     # if we're showing previous invoices, also show previous
1489     # credits and payments
1490     if ( $self->enable_previous
1491           and $self->can('_items_credits')
1492           and $self->can('_items_payments') )
1493       {
1494
1495       # credits
1496       my $credittotal = 0;
1497       foreach my $credit (
1498         $self->_items_credits( 'template' => $template, 'trim_len' => 40 )
1499       ) {
1500
1501         my $total;
1502         $total->{'total_item'} = &$escape_function($credit->{'description'});
1503         $credittotal += $credit->{'amount'};
1504         $total->{'total_amount'} = $minus.$other_money_char.$credit->{'amount'};
1505         if ( $multisection ) {
1506           push @detail_items, {
1507             ext_description => [],
1508             ref          => '',
1509             quantity     => '',
1510             description  => &$escape_function($credit->{'description'}),
1511             amount       => $money_char . $credit->{'amount'},
1512             product_code => '',
1513             section      => $adjust_section,
1514           };
1515         } else {
1516           push @total_items, $total;
1517         }
1518
1519       }
1520       $invoice_data{'credittotal'} = sprintf('%.2f', $credittotal);
1521
1522       #credits (again)
1523       foreach my $credit (
1524         $self->_items_credits( 'template' => $template, 'trim_len'=>32 )
1525       ) {
1526         push @buf, [ $credit->{'description'}, $money_char.$credit->{'amount'} ];
1527       }
1528
1529       # payments
1530       my $paymenttotal = 0;
1531       foreach my $payment (
1532         $self->_items_payments( 'template' => $template )
1533       ) {
1534         my $total = {};
1535         $total->{'total_item'} = &$escape_function($payment->{'description'});
1536         $paymenttotal += $payment->{'amount'};
1537         $total->{'total_amount'} = $minus.$other_money_char.$payment->{'amount'};
1538         if ( $multisection ) {
1539           push @detail_items, {
1540             ext_description => [],
1541             ref          => '',
1542             quantity     => '',
1543             description  => &$escape_function($payment->{'description'}),
1544             amount       => $money_char . $payment->{'amount'},
1545             product_code => '',
1546             section      => $adjust_section,
1547           };
1548         }else{
1549           push @total_items, $total;
1550         }
1551         push @buf, [ $payment->{'description'},
1552                      $money_char. sprintf("%10.2f", $payment->{'amount'}),
1553                    ];
1554       }
1555       $invoice_data{'paymenttotal'} = sprintf('%.2f', $paymenttotal);
1556
1557       if ( $multisection ) {
1558         $adjust_section->{'subtotal'} = $other_money_char.
1559                                         sprintf('%.2f', $credittotal + $paymenttotal);
1560
1561         #why this? because {sort_weight} forces the adjust_section to appear
1562         #in @extra_sections instead of @sections. obviously.
1563         push @sections, $adjust_section
1564           unless $adjust_section->{sort_weight};
1565         # do not summarize; adjustments there are shown according to
1566         # different rules
1567       }
1568
1569       # create Balance Due message
1570       {
1571         my $total;
1572         $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1573         $total->{'total_amount'} =
1574           &$embolden_function(
1575             $other_money_char. sprintf('%.2f', #why? $summarypage
1576                                                #  ? $self->charged +
1577                                                #    $self->billing_balance
1578                                                #  :
1579                                                    $balance_due
1580                                       )
1581           );
1582         if ( $multisection && !$adjust_section->{sort_weight} ) {
1583           $adjust_section->{'posttotal'} = $total->{'total_item'}. ' '.
1584                                            $total->{'total_amount'};
1585         } else {
1586           push @total_items, $total;
1587         }
1588         push @buf,['','-----------'];
1589         push @buf,[$self->balance_due_msg, $money_char.
1590           sprintf("%10.2f", $balance_due ) ];
1591       }
1592
1593       if ( $conf->exists('previous_balance-show_credit')
1594           and $cust_main->balance < 0 ) {
1595         my $credit_total = {
1596           'total_item'    => &$embolden_function($self->credit_balance_msg),
1597           'total_amount'  => &$embolden_function(
1598             $other_money_char. sprintf('%.2f', -$cust_main->balance)
1599           ),
1600         };
1601         if ( $multisection ) {
1602           $adjust_section->{'posttotal'} .= $newline_token .
1603             $credit_total->{'total_item'} . ' ' . $credit_total->{'total_amount'};
1604         }
1605         else {
1606           push @total_items, $credit_total;
1607         }
1608         push @buf,['','-----------'];
1609         push @buf,[$self->credit_balance_msg, $money_char.
1610           sprintf("%10.2f", -$cust_main->balance ) ];
1611       }
1612     }
1613
1614   } #end of default total adding ! can('_items_total')
1615
1616   if ( $multisection ) {
1617     if (    $conf->exists('svc_phone_sections')
1618          && $self->can('_items_svc_phone_sections')
1619        )
1620     {
1621       my $total;
1622       $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1623       $total->{'total_amount'} =
1624         &$embolden_function(
1625           $other_money_char. sprintf('%.2f', $balance_due)
1626         );
1627       my $last_section = pop @sections;
1628       $last_section->{'posttotal'} = $total->{'total_item'}. ' '.
1629                                      $total->{'total_amount'};
1630       push @sections, $last_section;
1631     }
1632     push @sections, @$late_sections
1633       if $unsquelched;
1634   }
1635
1636   # make a discounts-available section, even without multisection
1637   if ( $conf->exists('discount-show_available')
1638        and my @discounts_avail = $self->_items_discounts_avail ) {
1639     my $discount_section = {
1640       'description' => $self->mt('Discounts Available'),
1641       'subtotal'    => '',
1642       'no_subtotal' => 1,
1643     };
1644
1645     push @sections, $discount_section; # do not summarize
1646     push @detail_items, map { +{
1647         'ref'         => '', #should this be something else?
1648         'section'     => $discount_section,
1649         'description' => &$escape_function( $_->{description} ),
1650         'amount'      => $money_char . &$escape_function( $_->{amount} ),
1651         'ext_description' => [ &$escape_function($_->{ext_description}) || () ],
1652     } } @discounts_avail;
1653   }
1654
1655   # not adding any more sections after this
1656   $invoice_data{summary_subtotals} = \@summary_subtotals;
1657
1658   # usage subtotals
1659   if ( $conf->exists('usage_class_summary')
1660        and $self->can('_items_usage_class_summary') ) {
1661     my @usage_subtotals = $self->_items_usage_class_summary(escape => $escape_function, 'money_char' => $other_money_char);
1662     if ( @usage_subtotals ) {
1663       unshift @sections, $usage_subtotals[0]->{section}; # do not summarize
1664       unshift @detail_items, @usage_subtotals;
1665     }
1666   }
1667
1668   # invoice history "section" (not really a section)
1669   # not to be included in any subtotals, completely independent of
1670   # everything...
1671   if ( $conf->exists('previous_invoice_history') and $cust_main->isa('FS::cust_main') ) {
1672     my %history;
1673     my %monthorder;
1674     foreach my $cust_bill ( $cust_main->cust_bill ) {
1675       # XXX hardcoded format, and currently only 'charged'; add other fields
1676       # if they become necessary
1677       my $date = $self->time2str_local('%b %Y', $cust_bill->_date);
1678       $history{$date} ||= 0;
1679       $history{$date} += $cust_bill->charged;
1680       # just so we have a numeric sort key
1681       $monthorder{$date} ||= $cust_bill->_date;
1682     }
1683     my @sorted_months = sort { $monthorder{$a} <=> $monthorder{$b} }
1684                         keys %history;
1685     my @sorted_amounts = map { sprintf('%.2f', $history{$_}) } @sorted_months;
1686     $invoice_data{monthly_history} = [ \@sorted_months, \@sorted_amounts ];
1687   }
1688
1689   # service locations: another option for template customization
1690   my %location_info;
1691   foreach my $item (@detail_items) {
1692     if ( $item->{locationnum} ) {
1693       $location_info{ $item->{locationnum} } ||= {
1694         FS::cust_location->by_key( $item->{locationnum} )->location_hash
1695       };
1696     }
1697   }
1698   $invoice_data{location_info} = \%location_info;
1699
1700   # debugging hook: call this with 'diag' => 1 to just get a hash of
1701   # the invoice variables
1702   return \%invoice_data if ( $params{'diag'} );
1703
1704   # All sections and items are built; now fill in templates.
1705   my @includelist = ();
1706   push @includelist, 'summary' if $summarypage;
1707   foreach my $include ( @includelist ) {
1708
1709     my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
1710     my @inc_src;
1711
1712     if ( length( $conf->config($inc_file, $agentnum) ) ) {
1713
1714       @inc_src = $conf->config($inc_file, $agentnum);
1715
1716     } else {
1717
1718       $inc_file = $conf->key_orbase("invoice_latex$include", $template);
1719
1720       my $convert_map = $convert_maps{$format}{$include};
1721
1722       @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
1723                        s/--\@\]/$delimiters{$format}[1]/g;
1724                        $_;
1725                      }
1726                  &$convert_map( $conf->config($inc_file, $agentnum) );
1727
1728     }
1729
1730     my $inc_tt = new Text::Template (
1731       TYPE       => 'ARRAY',
1732       SOURCE     => [ map "$_\n", @inc_src ],
1733       DELIMITERS => $delimiters{$format},
1734     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
1735
1736     unless ( $inc_tt->compile() ) {
1737       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
1738       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
1739       die $error;
1740     }
1741
1742     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
1743
1744     $invoice_data{$include} =~ s/\n+$//
1745       if ($format eq 'latex');
1746   }
1747
1748   $invoice_lines = 0;
1749   my $wasfunc = 0;
1750   foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
1751     /invoice_lines\((\d*)\)/;
1752     $invoice_lines += $1 || scalar(@buf);
1753     $wasfunc=1;
1754   }
1755   die "no invoice_lines() functions in template?"
1756     if ( $format eq 'template' && !$wasfunc );
1757
1758   if ( $invoice_lines ) {
1759     $invoice_data{'total_pages'} = int( scalar(@buf) / $invoice_lines );
1760     $invoice_data{'total_pages'}++
1761       if scalar(@buf) % $invoice_lines;
1762   }
1763
1764   #setup subroutine for the template
1765   $invoice_data{invoice_lines} = sub {
1766     my $lines = shift || scalar(@buf);
1767     map {
1768       scalar(@buf)
1769         ? shift @buf
1770         : [ '', '' ];
1771     }
1772     ( 1 .. $lines );
1773   };
1774
1775   if ($format eq 'template') {
1776
1777     my $lines;
1778     my @collect;
1779     while (@buf) {
1780       push @collect, split("\n",
1781         $text_template->fill_in( HASH => \%invoice_data )
1782       );
1783       $invoice_data{'page'}++;
1784     }
1785     map "$_\n", @collect;
1786
1787   } else { # this is where we actually create the invoice
1788
1789     if ( $params{no_addresses} ) {
1790       delete $invoice_data{$_} foreach qw(
1791         payname company address1 address2 city state zip country
1792       );
1793       $invoice_data{returnaddress} = '~';
1794     }
1795
1796     warn "filling in template for invoice ". $self->invnum. "\n"
1797       if $DEBUG;
1798     warn join("\n", map " $_ => ". $invoice_data{$_}, keys %invoice_data). "\n"
1799       if $DEBUG > 1;
1800
1801     $text_template->fill_in(HASH => \%invoice_data);
1802   }
1803 }
1804
1805 sub notice_name { '('.shift->table.')'; }
1806
1807 # this is not supposed to happen
1808 sub template_conf { warn "bare FS::Template_Mixin::template_conf";
1809   'invoice_';
1810 }
1811
1812 =item print_ps HASHREF | [ TIME [ , TEMPLATE ] ]
1813
1814 Returns an postscript invoice, as a scalar.
1815
1816 Options can be passed as a hashref (recommended) or as a list of time, template
1817 and then any key/value pairs for any other options.
1818
1819 I<time> an optional value used to control the printing of overdue messages.  The
1820 default is now.  It isn't the date of the invoice; that's the `_date' field.
1821 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1822 L<Time::Local> and L<Date::Parse> for conversion functions.
1823
1824 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1825
1826 =cut
1827
1828 sub print_ps {
1829   my $self = shift;
1830
1831   my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1832   my $ps = generate_ps($file);
1833   unlink($logofile);
1834   unlink($barcodefile) if $barcodefile;
1835
1836   $ps;
1837 }
1838
1839 =item print_pdf HASHREF | [ TIME [ , TEMPLATE ] ]
1840
1841 Returns an PDF invoice, as a scalar.
1842
1843 Options can be passed as a hashref (recommended) or as a list of time, template
1844 and then any key/value pairs for any other options.
1845
1846 I<time> an optional value used to control the printing of overdue messages.  The
1847 default is now.  It isn't the date of the invoice; that's the `_date' field.
1848 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1849 L<Time::Local> and L<Date::Parse> for conversion functions.
1850
1851 I<template>, if specified, is the name of a suffix for alternate invoices.
1852
1853 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1854
1855 =cut
1856
1857 sub print_pdf {
1858   my $self = shift;
1859
1860   my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1861   my $pdf = generate_pdf($file);
1862   unlink($logofile);
1863   unlink($barcodefile) if $barcodefile;
1864
1865   $pdf;
1866 }
1867
1868 =item print_html HASHREF | [ TIME [ , TEMPLATE [ , CID ] ] ]
1869
1870 Returns an HTML invoice, as a scalar.
1871
1872 I<time> an optional value used to control the printing of overdue messages.  The
1873 default is now.  It isn't the date of the invoice; that's the `_date' field.
1874 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1875 L<Time::Local> and L<Date::Parse> for conversion functions.
1876
1877 I<template>, if specified, is the name of a suffix for alternate invoices.
1878
1879 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1880
1881 I<cid> is a MIME Content-ID used to create a "cid:" URL for the logo image, used
1882 when emailing the invoice as part of a multipart/related MIME email.
1883
1884 =cut
1885
1886 sub print_html {
1887   my $self = shift;
1888   my %params;
1889   if ( ref($_[0]) ) {
1890     %params = %{ shift() };
1891   } else {
1892     %params = @_;
1893   }
1894   $params{'format'} = 'html';
1895
1896   $self->print_generic( %params );
1897 }
1898
1899 # quick subroutine for print_latex
1900 #
1901 # There are ten characters that LaTeX treats as special characters, which
1902 # means that they do not simply typeset themselves:
1903 #      # $ % & ~ _ ^ \ { }
1904 #
1905 # TeX ignores blanks following an escaped character; if you want a blank (as
1906 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ...").
1907
1908 sub _latex_escape {
1909   my $value = shift;
1910   $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
1911   $value =~ s/([<>])/\$$1\$/g;
1912   $value;
1913 }
1914
1915 sub _html_escape {
1916   my $value = shift;
1917   encode_entities($value);
1918   $value;
1919 }
1920
1921 sub _html_escape_nbsp {
1922   my $value = _html_escape(shift);
1923   $value =~ s/ +/&nbsp;/g;
1924   $value;
1925 }
1926
1927 #utility methods for print_*
1928
1929 sub _translate_old_latex_format {
1930   warn "_translate_old_latex_format called\n"
1931     if $DEBUG;
1932
1933   my @template = ();
1934   while ( @_ ) {
1935     my $line = shift;
1936
1937     if ( $line =~ /^%%Detail\s*$/ ) {
1938
1939       push @template, q![@--!,
1940                       q!  foreach my $_tr_line (@detail_items) {!,
1941                       q!    if ( scalar ($_tr_item->{'ext_description'} ) ) {!,
1942                       q!      $_tr_line->{'description'} .= !,
1943                       q!        "\\tabularnewline\n~~".!,
1944                       q!        join( "\\tabularnewline\n~~",!,
1945                       q!          @{$_tr_line->{'ext_description'}}!,
1946                       q!        );!,
1947                       q!    }!;
1948
1949       while ( ( my $line_item_line = shift )
1950               !~ /^%%EndDetail\s*$/                            ) {
1951         $line_item_line =~ s/'/\\'/g;    # nice LTS
1952         $line_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
1953         $line_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1954         push @template, "    \$OUT .= '$line_item_line';";
1955       }
1956
1957       push @template, '}',
1958                       '--@]';
1959       #' doh, gvim
1960     } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
1961
1962       push @template, '[@--',
1963                       '  foreach my $_tr_line (@total_items) {';
1964
1965       while ( ( my $total_item_line = shift )
1966               !~ /^%%EndTotalDetails\s*$/                      ) {
1967         $total_item_line =~ s/'/\\'/g;    # nice LTS
1968         $total_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
1969         $total_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1970         push @template, "    \$OUT .= '$total_item_line';";
1971       }
1972
1973       push @template, '}',
1974                       '--@]';
1975
1976     } else {
1977       $line =~ s/\$(\w+)/[\@-- \$$1 --\@]/g;
1978       push @template, $line;
1979     }
1980
1981   }
1982
1983   if ($DEBUG) {
1984     warn "$_\n" foreach @template;
1985   }
1986
1987   (@template);
1988 }
1989
1990 =item terms
1991
1992 =cut
1993
1994 sub terms {
1995   my $self = shift;
1996   my $conf = $self->conf;
1997
1998   #check for an invoice-specific override
1999   return $self->invoice_terms if $self->invoice_terms;
2000
2001   #check for a customer- specific override
2002   my $cust_main = $self->cust_main;
2003   return $cust_main->invoice_terms if $cust_main && $cust_main->invoice_terms;
2004
2005   my $agentnum = '';
2006   if ( $cust_main ) {
2007     $agentnum = $cust_main->agentnum;
2008   } elsif ( my $prospect_main = $self->prospect_main ) {
2009     $agentnum = $prospect_main->agentnum;
2010   }
2011
2012   #use configured default
2013   $conf->config('invoice_default_terms', $agentnum) || '';
2014 }
2015
2016 =item due_date
2017
2018 =cut
2019
2020 sub due_date {
2021   my $self = shift;
2022   my $duedate = '';
2023   if ( $self->terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
2024     $duedate = $self->_date() + ( $1 * 86400 );
2025   } elsif ( $self->terms =~ /^End of Month$/ ) {
2026     my ($mon,$year) = (localtime($self->_date) )[4,5];
2027     $mon++;
2028     until ( $mon < 12 ) { $mon -= 12; $year++; }
2029     my $nextmonth_first = timelocal(0,0,0,1,$mon,$year);
2030     $duedate = $nextmonth_first - 86400;
2031   }
2032   $duedate;
2033 }
2034
2035 =item due_date2str
2036
2037 =cut
2038
2039 sub due_date2str {
2040   my $self = shift;
2041   $self->due_date ? $self->time2str_local(shift, $self->due_date) : '';
2042 }
2043
2044 =item invoice_pay_by_msg
2045
2046   displays the invoice_pay_by_msg or default Please pay by [_1] if empty.
2047
2048 =cut
2049
2050 sub invoice_pay_by_msg {
2051   my $self = shift;
2052   my $msg = '';
2053   my $please_pay_by =
2054         $self->conf->config('invoice_pay_by_msg', $self->agentnum)
2055         || 'Please pay by [_1]';
2056   $msg .= ' - ' . $self->mt($please_pay_by, $self->due_date2str('short')) . ' ';
2057
2058   $msg;
2059 }
2060
2061 =item balance_due_msg
2062
2063 =cut
2064
2065 sub balance_due_msg {
2066   my $self = shift;
2067   my $msg = $self->mt('Balance Due');
2068   return $msg unless $self->terms; # huh?
2069   if ( !$self->conf->exists('invoice_show_prior_due_date')
2070        || $self->has_sections ) {
2071     # if enabled, the due date is shown with Total New Charges (see
2072     # _items_total) and not here
2073     # (yes, or if invoice_sections is enabled; this is just for compatibility)
2074     if ( $self->due_date ) {
2075       $msg .= $self->invoice_pay_by_msg
2076        unless $self->conf->config_bool('invoice_omit_due_date',$self->agentnum);
2077     } elsif ( $self->terms ) {
2078       $msg .= ' - '. $self->mt($self->terms);
2079     }
2080   }
2081   $msg;
2082 }
2083
2084 =item balance_due_date
2085
2086 =cut
2087
2088 sub balance_due_date {
2089   my $self = shift;
2090   my $conf = $self->conf;
2091   my $duedate = '';
2092   my $terms = $self->terms;
2093   if ( $terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
2094     $duedate = $self->time2str_local('rdate', $self->_date + ($1*86400) );
2095   }
2096   $duedate;
2097 }
2098
2099 sub credit_balance_msg {
2100   my $self = shift;
2101   $self->mt('Credit Balance Remaining')
2102 }
2103
2104 =item _date_pretty
2105
2106 Returns a string with the date, for example: "3/20/2008", localized for the
2107 customer.  Use _date_pretty_unlocalized for non-end-customer display use.
2108
2109 =cut
2110
2111 sub _date_pretty {
2112   my $self = shift;
2113   $self->time2str_local('short', $self->_date);
2114 }
2115
2116 =item _date_pretty_unlocalized
2117
2118 Returns a string with the date, for example: "3/20/2008", in the format
2119 configured for the back-office.  Use _date_pretty for end-customer display use.
2120
2121 =cut
2122
2123 sub _date_pretty_unlocalized {
2124   my $self = shift;
2125   time2str($date_format, $self->_date);
2126 }
2127
2128 =item email HASHREF
2129
2130 Emails this template.
2131
2132 Options are passed as a hashref.  Available options:
2133
2134 =over 4
2135
2136 =item from
2137
2138 If specified, overrides the default From: address.
2139
2140 =item notice_name
2141
2142 If specified, overrides the name of the sent document ("Invoice" or "Quotation")
2143
2144 =item template
2145
2146 (Deprecated) If specified, is the name of a suffix for alternate template files.
2147
2148 =back
2149
2150 Options accepted by generate_email can also be used.
2151
2152 =cut
2153
2154 sub email {
2155   my $self = shift;
2156   my $opt = shift || {};
2157   if ($opt and !ref($opt)) {
2158     die ref($self). '->email called with positional parameters';
2159   }
2160
2161   return if $self->hide;
2162
2163   my $error = send_email(
2164     $self->generate_email(
2165       'subject'     => $self->email_subject($opt->{template}),
2166       %$opt, # template, etc.
2167     )
2168   );
2169
2170   die "can't email: $error\n" if $error;
2171 }
2172
2173 =item generate_email OPTION => VALUE ...
2174
2175 Options:
2176
2177 =over 4
2178
2179 =item from
2180
2181 sender address, required
2182
2183 =item template
2184
2185 alternate template name, optional
2186
2187 =item subject
2188
2189 email subject, optional
2190
2191 =item notice_name
2192
2193 notice name instead of "Invoice", optional
2194
2195 =back
2196
2197 Returns an argument list to be passed to L<FS::Misc::send_email>.
2198
2199 =cut
2200
2201 use MIME::Entity;
2202 use Encode;
2203
2204 sub generate_email {
2205
2206   my $self = shift;
2207   my %args = @_;
2208   my $conf = $self->conf;
2209
2210   my $me = '[FS::Template_Mixin::generate_email]';
2211
2212   my %return = (
2213     'from'      => $args{'from'},
2214     'subject'   => ($args{'subject'} || $self->email_subject),
2215     'custnum'   => $self->custnum,
2216     'msgtype'   => 'invoice',
2217   );
2218
2219   $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
2220
2221   my $cust_main = $self->cust_main;
2222
2223   if (ref($args{'to'}) eq 'ARRAY') {
2224     $return{'to'} = $args{'to'};
2225   } elsif ( $cust_main ) {
2226     $return{'to'} = [ $cust_main->invoicing_list_emailonly ];
2227   }
2228
2229   my $tc = $self->template_conf;
2230
2231   my @text; # array of lines
2232   my $html; # a big string
2233   my @related_parts; # will contain the text/HTML alternative, and images
2234   my $related; # will contain the multipart/related object
2235
2236   if ( $conf->exists($tc. 'email_pdf') ) {
2237     if ( my $msgnum = $conf->config($tc.'email_pdf_msgnum') ) {
2238
2239       warn "$me using '${tc}email_pdf_msgnum' in multipart message"
2240         if $DEBUG;
2241
2242       my $msg_template = FS::msg_template->by_key($msgnum)
2243         or die "${tc}email_pdf_msgnum $msgnum not found\n";
2244       my $cust_msg = $msg_template->prepare(
2245         cust_main => $self->cust_main,
2246         object    => $self,
2247         msgtype   => 'invoice',
2248       );
2249
2250       # XXX hack to make this work in the new cust_msg era; consider replacing
2251       # with cust_bill_send_with_notice events.
2252       my @parts = $cust_msg->parts;
2253       foreach my $part (@parts) { # will only have two parts, normally
2254         if ( $part->mime_type eq 'text/plain' ) {
2255           @text = @{ $part->body };
2256         } elsif ( $part->mime_type eq 'text/html' ) {
2257           $html = $part->bodyhandle->as_string;
2258         }
2259       }
2260
2261     } elsif ( my @note = $conf->config($tc.'email_pdf_note') ) {
2262
2263       warn "$me using '${tc}email_pdf_note' in multipart message"
2264         if $DEBUG;
2265       @text = $conf->config($tc.'email_pdf_note');
2266       $html = join('<BR>', @text);
2267
2268     } # else use the plain text invoice
2269   }
2270
2271   if (!@text) {
2272
2273     if ( $conf->exists($tc.'template') ) {
2274
2275       warn "$me generating plain text invoice"
2276         if $DEBUG;
2277
2278       @text = $self->print_text(\%args);
2279
2280     } else {
2281
2282       warn "$me no plain text version exists; sending empty message body"
2283         if $DEBUG;
2284
2285     }
2286
2287   }
2288
2289   my $text_part = build MIME::Entity (
2290     'Type'        => 'text/plain',
2291     'Encoding'    => 'quoted-printable',
2292     'Charset'     => 'UTF-8',
2293     #'Encoding'    => '7bit',
2294     'Data'        => [
2295       map
2296         { Encode::encode('UTF-8', $_, Encode::FB_WARN | Encode::LEAVE_SRC ) }
2297         @text
2298     ],
2299     'Disposition' => 'inline',
2300   );
2301
2302   if (!$html) {
2303
2304     if ( $conf->exists($tc.'html') ) {
2305       warn "$me generating HTML invoice"
2306         if $DEBUG;
2307
2308       $args{'from'} =~ /\@([\w\.\-]+)/;
2309       my $from = $1 || 'example.com';
2310       my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2311
2312       my $logo;
2313       my $agentnum = $cust_main ? $cust_main->agentnum
2314                                 : $self->prospect_main->agentnum;
2315       if ( defined($args{'template'}) && length($args{'template'})
2316            && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
2317          )
2318       {
2319         $logo = 'logo_'. $args{'template'}. '.png';
2320       } else {
2321         $logo = "logo.png";
2322       }
2323       my $image_data = $conf->config_binary( $logo, $agentnum);
2324
2325       push @related_parts, build MIME::Entity
2326         'Type'       => 'image/png',
2327         'Encoding'   => 'base64',
2328         'Data'       => $image_data,
2329         'Filename'   => 'logo.png',
2330         'Content-ID' => "<$content_id>",
2331       ;
2332
2333       if ( ref($self) eq 'FS::cust_bill' && $conf->exists('invoice-barcode') ) {
2334         my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
2335         push @related_parts, build MIME::Entity
2336           'Type'       => 'image/png',
2337           'Encoding'   => 'base64',
2338           'Data'       => $self->invoice_barcode(0),
2339           'Filename'   => 'barcode.png',
2340           'Content-ID' => "<$barcode_content_id>",
2341         ;
2342         $args{'barcode_cid'} = $barcode_content_id;
2343       }
2344
2345       $html = $self->print_html({ 'cid'=>$content_id, %args });
2346     }
2347
2348   }
2349
2350   if ( $html ) {
2351
2352     warn "$me creating HTML/text multipart message"
2353       if $DEBUG;
2354
2355     $return{'nobody'} = 1;
2356
2357     my $alternative = build MIME::Entity
2358       'Type'        => 'multipart/alternative',
2359       #'Encoding'    => '7bit',
2360       'Disposition' => 'inline'
2361     ;
2362
2363     if ( @text ) {
2364       $alternative->add_part($text_part);
2365     }
2366
2367     $alternative->attach(
2368       'Type'        => 'text/html',
2369       'Encoding'    => 'quoted-printable',
2370       'Data'        => [ '<html>',
2371                          '  <head>',
2372                          '    <title>',
2373                          '      '. encode_entities($return{'subject'}),
2374                          '    </title>',
2375                          '  </head>',
2376                          '  <body bgcolor="#e8e8e8">',
2377                          Encode::encode(
2378                            'UTF-8',
2379                            $html,
2380                            Encode::FB_WARN | Encode::LEAVE_SRC
2381                          ),
2382                          '  </body>',
2383                          '</html>',
2384                        ],
2385       'Disposition' => 'inline',
2386       #'Filename'    => 'invoice.pdf',
2387     );
2388
2389     unshift @related_parts, $alternative;
2390
2391     $related = build MIME::Entity 'Type'     => 'multipart/related',
2392                                   'Encoding' => '7bit';
2393
2394     #false laziness w/Misc::send_email
2395     $related->head->replace('Content-type',
2396       $related->mime_type.
2397       '; boundary="'. $related->head->multipart_boundary. '"'.
2398       '; type=multipart/alternative'
2399     );
2400
2401     $related->add_part($_) foreach @related_parts;
2402
2403   }
2404
2405   my @otherparts = ();
2406   if ( ref($self) eq 'FS::cust_bill' && $cust_main->email_csv_cdr ) {
2407
2408     if ( $conf->config('voip-cdr_email_attach') eq 'zip' ) {
2409
2410       my $data = join('', map "$_\n",
2411                    $self->call_details(prepend_billed_number=>1)
2412                  );
2413
2414       my $zip = new Archive::Zip;
2415       my $file = $zip->addString( $data, 'usage-'.$self->invnum.'.csv' );
2416       $file->desiredCompressionMethod( COMPRESSION_DEFLATED );
2417
2418       my $zipdata = '';
2419       my $SH = IO::Scalar->new(\$zipdata);
2420       my $status = $zip->writeToFileHandle($SH);
2421       die "Error zipping CDR attachment: $!" unless $status == AZ_OK;
2422
2423       push @otherparts, build MIME::Entity
2424         'Type'        => 'application/zip',
2425         'Encoding'    => 'base64',
2426         'Data'        => $zipdata,
2427         'Disposition' => 'attachment',
2428         'Filename'    => 'usage-'. $self->invnum. '.zip',
2429       ;
2430
2431     } else { # } elsif ( $conf->config('voip-cdr_email_attach') eq 'csv' ) {
2432
2433       push @otherparts, build MIME::Entity
2434         'Type'        => 'text/csv',
2435         'Encoding'    => '7bit',
2436         'Data'        => [ map { "$_\n" }
2437                              $self->call_details('prepend_billed_number' => 1)
2438                          ],
2439         'Disposition' => 'attachment',
2440         'Filename'    => 'usage-'. $self->invnum. '.csv',
2441       ;
2442
2443     }
2444
2445   }
2446
2447   if ( $conf->exists($tc.'email_pdf') ) {
2448
2449     #attaching pdf too:
2450     # multipart/mixed
2451     #   multipart/related
2452     #     multipart/alternative
2453     #       text/plain
2454     #       text/html
2455     #     image/png
2456     #   application/pdf
2457
2458     my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
2459     push @otherparts, $pdf;
2460   }
2461
2462   if (@otherparts) {
2463     $return{'content-type'} = 'multipart/mixed'; # of the outer container
2464     if ( $html ) {
2465       $return{'mimeparts'} = [ $related, @otherparts ];
2466       $return{'type'} = 'multipart/related'; # of the first part
2467     } else {
2468       $return{'mimeparts'} = [ $text_part, @otherparts ];
2469       $return{'type'} = 'text/plain';
2470     }
2471   } elsif ( $html ) { # no PDF or CSV, strip the outer container
2472     $return{'mimeparts'} = \@related_parts;
2473     $return{'content-type'} = 'multipart/related';
2474     $return{'type'} = 'multipart/alternative';
2475   } else { # no HTML either
2476     $return{'body'} = \@text;
2477     $return{'content-type'} = 'text/plain';
2478   }
2479
2480   %return;
2481
2482 }
2483
2484 =item mimebuild_pdf
2485
2486 Returns a list suitable for passing to MIME::Entity->build(), representing
2487 this quotation or invoice as PDF attachment.
2488
2489 =cut
2490
2491 sub mimebuild_pdf {
2492   my $self = shift;
2493   (
2494     'Type'        => 'application/pdf',
2495     'Encoding'    => 'base64',
2496     'Data'        => [ $self->print_pdf(@_) ],
2497     'Disposition' => 'attachment',
2498     'Filename'    => $self->pdf_filename,
2499   );
2500 }
2501
2502 =item postal_mail_fsinc
2503
2504 Sends this invoice to the Freeside Internet Services, Inc. print and mail
2505 service.
2506
2507 =cut
2508
2509 use CAM::PDF;
2510 use IO::Socket::SSL;
2511 use LWP::UserAgent;
2512 use HTTP::Request::Common qw( POST );
2513 use Cpanel::JSON::XS;
2514 use MIME::Base64;
2515 sub postal_mail_fsinc {
2516   my ( $self, %opt ) = @_;
2517
2518   if ( $FS::Misc::DISABLE_PRINT ) {
2519     warn 'postal_mail_fsinc() disabled by $FS::Misc::DISABLE_PRINT' if $DEBUG;
2520     return;
2521   }
2522
2523   my $url = 'https://ws.freeside.biz/print';
2524
2525   my $cust_main = $self->cust_main;
2526   my $agentnum = $cust_main->agentnum;
2527   my $bill_location = $cust_main->bill_location;
2528
2529   die "Extra charges for international mailing; contact support\@freeside.biz to enable\n"
2530     if $bill_location->country ne 'US';
2531
2532   my $conf = new FS::Conf;
2533
2534   my @company_address = $conf->config('company_address', $agentnum);
2535   my ( $company_address1, $company_address2, $company_city, $company_state, $company_zip );
2536   if ( $company_address[2] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2537     $company_address1 = $company_address[0];
2538     $company_address2 = $company_address[1];
2539     $company_city  = $1;
2540     $company_state = $2;
2541     $company_zip   = $3;
2542   } elsif ( $company_address[1] =~ /^\s*(\S.*\S)\s*[\s,](\w\w),?\s*(\d{5}(-\d{4})?)\s*$/ ) {
2543     $company_address1 = $company_address[0];
2544     $company_address2 = '';
2545     $company_city  = $1;
2546     $company_state = $2;
2547     $company_zip   = $3;
2548   } else {
2549     die "Unparsable company_address; contact support\@freeside.biz\n";
2550   }
2551   $company_city =~ s/,$//;
2552
2553   my $file = $self->print_pdf(%opt, 'no_addresses' => 1);
2554   my $pages = CAM::PDF->new($file)->numPages;
2555
2556   my $ua = LWP::UserAgent->new(
2557     'ssl_opts' => {
2558       verify_hostname => 0,
2559       SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
2560       SSL_version     => 'SSLv3',
2561     }
2562   );
2563   my $response = $ua->request( POST $url, [
2564     'support-key'      => scalar($conf->config('support-key')),
2565     'file'             => encode_base64($file),
2566     'pages'            => $pages,
2567
2568     #from:
2569     'company_name'     => scalar( $conf->config('company_name', $agentnum) ),
2570     'company_address1' => $company_address1,
2571     'company_address2' => $company_address2,
2572     'company_city'     => $company_city,
2573     'company_state'    => $company_state,
2574     'company_zip'      => $company_zip,
2575     'company_country'  => 'US',
2576     'company_phonenum' => scalar($conf->config('company_phonenum', $agentnum)),
2577     'company_email'    => scalar($conf->config('invoice_from', $agentnum)),
2578
2579     #to:
2580     'name'             => $cust_main->invoice_attn
2581                             || $cust_main->contact_firstlast,
2582     'company'          => $cust_main->company,
2583     'address1'         => $bill_location->address1,
2584     'address2'         => $bill_location->address2,
2585     'city'             => $bill_location->city,
2586     'state'            => $bill_location->state,
2587     'zip'              => $bill_location->zip,
2588     'country'          => $bill_location->country,
2589   ]);
2590
2591   die "Print connection error: ". $response->message.
2592       ' ('. $response->as_string. ")\n"
2593     unless $response->is_success;
2594
2595   local $@;
2596   my $content = eval { decode_json($response->content) };
2597   die "Print JSON error : $@\n" if $@;
2598
2599   die $content->{error}."\n"
2600     if $content->{error};
2601
2602   #TODO: store this so we can query for a status later
2603   warn "Invoice printed, ID ". $content->{id}. "\n";
2604
2605   $content->{id};
2606
2607 }
2608
2609 =item _items_sections OPTIONS
2610
2611 Generate section information for all items appearing on this invoice.
2612 This will only be called for multi-section invoices.
2613
2614 For each line item (L<FS::cust_bill_pkg> record), this will fetch all
2615 related display records (L<FS::cust_bill_pkg_display>) and organize
2616 them into two groups ("early" and "late" according to whether they come
2617 before or after the total), then into sections.  A subtotal is calculated
2618 for each section.
2619
2620 Section descriptions are returned in sort weight order.  Each consists
2621 of a hash containing:
2622
2623 description: the package category name, escaped
2624 subtotal: the total charges in that section
2625 tax_section: a flag indicating that the section contains only tax charges
2626 summarized: same as tax_section, for some reason
2627 sort_weight: the package category's sort weight
2628
2629 If 'condense' is set on the display record, it also contains everything
2630 returned from C<_condense_section()>, i.e. C<_condensed_foo_generator>
2631 coderefs to generate parts of the invoice.  This is not advised.
2632
2633 The method returns two arrayrefs, one of "early" sections and one of "late"
2634 sections.
2635
2636 OPTIONS may include:
2637
2638 by_location: a flag to divide the invoice into sections by location.
2639 Each section hash will have a 'location' element containing a hashref of
2640 the location fields (see L<FS::cust_location>).  The section description
2641 will be the location label, but the template can use any of the location
2642 fields to create a suitable label.
2643
2644 by_category: a flag to divide the invoice into sections using display
2645 records (see L<FS::cust_bill_pkg_display>).  This is the "traditional"
2646 behavior.  Each section hash will have a 'category' element containing
2647 the section name from the display record (which probably equals the
2648 category name of the package, but may not in some cases).
2649
2650 summary: a flag indicating that this is a summary-format invoice.
2651 Turning this on has the following effects:
2652 - Ignores display items with the 'summary' flag.
2653 - Places all sections in the "early" group even if they have post_total.
2654 - Creates sections for all non-disabled package categories, even if they
2655 have no charges on this invoice, as well as a section with no name.
2656
2657 escape: an escape function to use for section titles.
2658
2659 extra_sections: an arrayref of additional sections to return after the
2660 sorted list.  If there are any of these, section subtotals exclude
2661 usage charges.
2662
2663 format: 'latex', 'html', or 'template' (i.e. text).  Not used, but
2664 passed through to C<_condense_section()>.
2665
2666 =cut
2667
2668 use vars qw(%pkg_category_cache);
2669 sub _items_sections {
2670   my $self = shift;
2671   my %opt = @_;
2672
2673   my $escape = $opt{escape};
2674   my @extra_sections = @{ $opt{extra_sections} || [] };
2675
2676   # $subtotal{$locationnum}{$categoryname} = amount.
2677   # if we're not using by_location, $locationnum is undef.
2678   # if we're not using by_category, you guessed it, $categoryname is undef.
2679   # if we're not using either one, we shouldn't be here in the first place...
2680   my %subtotal = ();
2681   my %late_subtotal = ();
2682   my %not_tax = ();
2683
2684   # About tax items + multisection invoices:
2685   # If either invoice_*summary option is enabled, AND there is a
2686   # package category with the name of the tax, then there will be
2687   # a display record assigning the tax item to that category.
2688   #
2689   # However, the taxes are always placed in the "Taxes, Surcharges,
2690   # and Fees" section regardless of that.  The only effect of the
2691   # display record is to create a subtotal for the summary page.
2692
2693   # cache these
2694   my $pkg_hash = $self->cust_pkg_hash;
2695
2696   foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2697   {
2698
2699       my $usage = $cust_bill_pkg->usage;
2700
2701       my $locationnum;
2702       if ( $opt{by_location} ) {
2703         if ( $cust_bill_pkg->pkgnum ) {
2704           $locationnum = $pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum;
2705         } else {
2706           $locationnum = '';
2707         }
2708       } else {
2709         $locationnum = undef;
2710       }
2711
2712       # as in _items_cust_pkg, if a line item has no display records,
2713       # cust_bill_pkg_display() returns a default record for it
2714
2715       foreach my $display ($cust_bill_pkg->cust_bill_pkg_display) {
2716         next if ( $display->summary && $opt{summary} );
2717
2718         #my $section = $display->section;
2719         #false laziness with the method, but for efficiency inside this loop
2720         my $section = $display->get('section');
2721         if ( !$section && !$cust_bill_pkg->hidden ) {
2722           $section = $cust_bill_pkg->get('categoryname'); #cust_bill->cust_bill_pkg added it (XXX quotations / quotation_section)
2723         }
2724
2725         my $type    = $display->type;
2726         # Set $section = undef if we're sectioning by location and this
2727         # line item _has_ a location (i.e. isn't a fee).
2728         $section = undef if $locationnum;
2729
2730         # set this flag if the section is not tax-only
2731         $not_tax{$locationnum}{$section} = 1
2732           if $cust_bill_pkg->pkgnum  or $cust_bill_pkg->feepart;
2733
2734         # there's actually a very important piece of logic buried in here:
2735         # incrementing $late_subtotal{$section} CREATES
2736         # $late_subtotal{$section}.  keys(%late_subtotal) is later used
2737         # to define the list of late sections, and likewise keys(%subtotal).
2738         # When _items_cust_bill_pkg is called to generate line items for
2739         # real, it will be called with 'section' => $section for each
2740         # of these.
2741         if ( $display->post_total && !$opt{summary} ) {
2742           if (! $type || $type eq 'S') {
2743             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2744               if $cust_bill_pkg->setup != 0
2745               || $cust_bill_pkg->setup_show_zero;
2746           }
2747
2748           if (! $type) {
2749             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur
2750               if $cust_bill_pkg->recur != 0
2751               || $cust_bill_pkg->recur_show_zero;
2752           }
2753
2754           if ($type && $type eq 'R') {
2755             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2756               if $cust_bill_pkg->recur != 0
2757               || $cust_bill_pkg->recur_show_zero;
2758           }
2759
2760           if ($type && $type eq 'U') {
2761             $late_subtotal{$locationnum}{$section} += $usage
2762               unless scalar(@extra_sections);
2763           }
2764
2765         } else { # it's a pre-total (normal) section
2766
2767           # skip tax items unless they're explicitly included in a section
2768           next if $cust_bill_pkg->pkgnum == 0 and
2769                   ! $cust_bill_pkg->feepart   and
2770                   ! $section;
2771
2772           if ( $type eq 'S' ) {
2773             $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2774               if $cust_bill_pkg->setup != 0
2775               || $cust_bill_pkg->setup_show_zero;
2776           } elsif ( $type eq 'R' ) {
2777             $subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2778               if $cust_bill_pkg->recur != 0
2779               || $cust_bill_pkg->recur_show_zero;
2780           } elsif ( $type eq 'U' ) {
2781             $subtotal{$locationnum}{$section} += $usage
2782               unless scalar(@extra_sections);
2783           } elsif ( !$type ) {
2784             $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2785                                                + $cust_bill_pkg->recur;
2786           }
2787
2788         }
2789
2790       }
2791
2792   }
2793
2794   %pkg_category_cache = ();
2795
2796   # summary invoices need subtotals for all non-disabled package categories,
2797   # even if they're zero
2798   # but currently assume that there are no location sections, or at least
2799   # that the summary page doesn't care about them
2800   if ( $opt{summary} ) {
2801     foreach my $category (qsearch('pkg_category', {disabled => ''})) {
2802       $subtotal{''}{$category->categoryname} ||= 0;
2803     }
2804     $subtotal{''}{''} ||= 0;
2805   }
2806
2807   my @sections;
2808   foreach my $post_total (0,1) {
2809     my @these;
2810     my $s = $post_total ? \%late_subtotal : \%subtotal;
2811     foreach my $locationnum (keys %$s) {
2812       foreach my $sectionname (keys %{ $s->{$locationnum} }) {
2813         my $section = {
2814                         'subtotal'    => $s->{$locationnum}{$sectionname},
2815                         'sort_weight' => 0,
2816                       };
2817         if ( $locationnum ) {
2818           $section->{'locationnum'} = $locationnum;
2819           my $location = FS::cust_location->by_key($locationnum);
2820           $section->{'description'} = &{ $escape }($location->location_label);
2821           # Better ideas? This will roughly group them by proximity,
2822           # which alpha sorting on any of the address fields won't.
2823           # Sorting by locationnum is meaningless.
2824           # We have to sort on _something_ or the order may change
2825           # randomly from one invoice to the next, which will confuse
2826           # people.
2827           $section->{'sort_weight'} = sprintf('%012s',$location->zip) .
2828                                       $locationnum;
2829           $section->{'location'} = {
2830             label_prefix => &{ $escape }($location->label_prefix),
2831             map { $_ => &{ $escape }($location->get($_)) }
2832               $location->fields
2833           };
2834         } else {
2835           $section->{'category'} = $sectionname;
2836           $section->{'description'} = &{ $escape }($sectionname);
2837           if ( _pkg_category($sectionname) ) {
2838             $section->{'sort_weight'} = _pkg_category($sectionname)->weight;
2839             if ( _pkg_category($sectionname)->condense ) {
2840               $section = { %$section, $self->_condense_section($opt{format}) };
2841             }
2842           }
2843         }
2844         if ( !$post_total and !$not_tax{$locationnum}{$sectionname} ) {
2845           # then it's a tax-only section
2846           $section->{'summarized'} = 'Y';
2847           $section->{'tax_section'} = 'Y';
2848         }
2849         push @these, $section;
2850       } # foreach $sectionname
2851     } #foreach $locationnum
2852     push @these, @extra_sections if $post_total == 0;
2853     # need an alpha sort for location sections, because postal codes can
2854     # be non-numeric
2855     $sections[ $post_total ] = [ sort {
2856       $opt{'by_location'} ?
2857         ($a->{sort_weight} cmp $b->{sort_weight}) :
2858         ($a->{sort_weight} <=> $b->{sort_weight})
2859       } @these ];
2860   } #foreach $post_total
2861
2862   return @sections; # early, late
2863 }
2864
2865 #helper subs for above
2866
2867 sub cust_pkg_hash {
2868   my $self = shift;
2869   $self->{cust_pkg} ||= { map { $_->pkgnum => $_ } $self->cust_pkg };
2870 }
2871
2872 sub _pkg_category {
2873   my $categoryname = shift;
2874   $pkg_category_cache{$categoryname} ||=
2875     qsearchs( 'pkg_category', { 'categoryname' => $categoryname } );
2876 }
2877
2878 my %condensed_format = (
2879   'label' => [ qw( Description Qty Amount ) ],
2880   'fields' => [
2881                 sub { shift->{description} },
2882                 sub { shift->{quantity} },
2883                 sub { my($href, %opt) = @_;
2884                       ($opt{dollar} || ''). $href->{amount};
2885                     },
2886               ],
2887   'align'  => [ qw( l r r ) ],
2888   'span'   => [ qw( 5 1 1 ) ],            # unitprices?
2889   'width'  => [ qw( 10.7cm 1.4cm 1.6cm ) ],   # don't like this
2890 );
2891
2892 sub _condense_section {
2893   my ( $self, $format ) = ( shift, shift );
2894   ( 'condensed' => 1,
2895     map { my $method = "_condensed_$_"; $_ => $self->$method($format) }
2896       qw( description_generator
2897           header_generator
2898           total_generator
2899           total_line_generator
2900         )
2901   );
2902 }
2903
2904 sub _condensed_generator_defaults {
2905   my ( $self, $format ) = ( shift, shift );
2906   return ( \%condensed_format, ' ', ' ', ' ', sub { shift } );
2907 }
2908
2909 my %html_align = (
2910   'c' => 'center',
2911   'l' => 'left',
2912   'r' => 'right',
2913 );
2914
2915 sub _condensed_header_generator {
2916   my ( $self, $format ) = ( shift, shift );
2917
2918   my ( $f, $prefix, $suffix, $separator, $column ) =
2919     _condensed_generator_defaults($format);
2920
2921   if ($format eq 'latex') {
2922     $prefix = "\\hline\n\\rule{0pt}{2.5ex}\n\\makebox[1.4cm]{}&\n";
2923     $suffix = "\\\\\n\\hline";
2924     $separator = "&\n";
2925     $column =
2926       sub { my ($d,$a,$s,$w) = @_;
2927             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2928           };
2929   } elsif ( $format eq 'html' ) {
2930     $prefix = '<th></th>';
2931     $suffix = '';
2932     $separator = '';
2933     $column =
2934       sub { my ($d,$a,$s,$w) = @_;
2935             return qq!<th align="$html_align{$a}">$d</th>!;
2936       };
2937   }
2938
2939   sub {
2940     my @args = @_;
2941     my @result = ();
2942
2943     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2944       push @result,
2945         &{$column}( map { $f->{$_}->[$i] } qw(label align span width) );
2946     }
2947
2948     $prefix. join($separator, @result). $suffix;
2949   };
2950
2951 }
2952
2953 sub _condensed_description_generator {
2954   my ( $self, $format ) = ( shift, shift );
2955
2956   my ( $f, $prefix, $suffix, $separator, $column ) =
2957     _condensed_generator_defaults($format);
2958
2959   my $money_char = '$';
2960   if ($format eq 'latex') {
2961     $prefix = "\\hline\n\\multicolumn{1}{c}{\\rule{0pt}{2.5ex}~} &\n";
2962     $suffix = '\\\\';
2963     $separator = " & \n";
2964     $column =
2965       sub { my ($d,$a,$s,$w) = @_;
2966             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2967           };
2968     $money_char = '\\dollar';
2969   }elsif ( $format eq 'html' ) {
2970     $prefix = '"><td align="center"></td>';
2971     $suffix = '';
2972     $separator = '';
2973     $column =
2974       sub { my ($d,$a,$s,$w) = @_;
2975             return qq!<td align="$html_align{$a}">$d</td>!;
2976       };
2977     #$money_char = $conf->config('money_char') || '$';
2978     $money_char = '';  # this is madness
2979   }
2980
2981   sub {
2982     #my @args = @_;
2983     my $href = shift;
2984     my @result = ();
2985
2986     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2987       my $dollar = '';
2988       $dollar = $money_char if $i == scalar(@{$f->{label}})-1;
2989       push @result,
2990         &{$column}( &{$f->{fields}->[$i]}($href, 'dollar' => $dollar),
2991                     map { $f->{$_}->[$i] } qw(align span width)
2992                   );
2993     }
2994
2995     $prefix. join( $separator, @result ). $suffix;
2996   };
2997
2998 }
2999
3000 sub _condensed_total_generator {
3001   my ( $self, $format ) = ( shift, shift );
3002
3003   my ( $f, $prefix, $suffix, $separator, $column ) =
3004     _condensed_generator_defaults($format);
3005   my $style = '';
3006
3007   if ($format eq 'latex') {
3008     $prefix = "& ";
3009     $suffix = "\\\\\n";
3010     $separator = " & \n";
3011     $column =
3012       sub { my ($d,$a,$s,$w) = @_;
3013             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3014           };
3015   }elsif ( $format eq 'html' ) {
3016     $prefix = '';
3017     $suffix = '';
3018     $separator = '';
3019     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3020     $column =
3021       sub { my ($d,$a,$s,$w) = @_;
3022             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3023       };
3024   }
3025
3026
3027   sub {
3028     my @args = @_;
3029     my @result = ();
3030
3031     #  my $r = &{$f->{fields}->[$i]}(@args);
3032     #  $r .= ' Total' unless $i;
3033
3034     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3035       push @result,
3036         &{$column}( &{$f->{fields}->[$i]}(@args). ($i ? '' : ' Total'),
3037                     map { $f->{$_}->[$i] } qw(align span width)
3038                   );
3039     }
3040
3041     $prefix. join( $separator, @result ). $suffix;
3042   };
3043
3044 }
3045
3046 =item total_line_generator FORMAT
3047
3048 Returns a coderef used for generation of invoice total line items for this
3049 usage_class.  FORMAT is either html or latex
3050
3051 =cut
3052
3053 # should not be used: will have issues with hash element names (description vs
3054 # total_item and amount vs total_amount -- another array of functions?
3055
3056 sub _condensed_total_line_generator {
3057   my ( $self, $format ) = ( shift, shift );
3058
3059   my ( $f, $prefix, $suffix, $separator, $column ) =
3060     _condensed_generator_defaults($format);
3061   my $style = '';
3062
3063   if ($format eq 'latex') {
3064     $prefix = "& ";
3065     $suffix = "\\\\\n";
3066     $separator = " & \n";
3067     $column =
3068       sub { my ($d,$a,$s,$w) = @_;
3069             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3070           };
3071   }elsif ( $format eq 'html' ) {
3072     $prefix = '';
3073     $suffix = '';
3074     $separator = '';
3075     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3076     $column =
3077       sub { my ($d,$a,$s,$w) = @_;
3078             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3079       };
3080   }
3081
3082
3083   sub {
3084     my @args = @_;
3085     my @result = ();
3086
3087     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3088       push @result,
3089         &{$column}( &{$f->{fields}->[$i]}(@args),
3090                     map { $f->{$_}->[$i] } qw(align span width)
3091                   );
3092     }
3093
3094     $prefix. join( $separator, @result ). $suffix;
3095   };
3096
3097 }
3098
3099 =item _items_pkg [ OPTIONS ]
3100
3101 Return line item hashes for each package item on this invoice. Nearly
3102 equivalent to
3103
3104 $self->_items_cust_bill_pkg([ $self->cust_bill_pkg ])
3105
3106 OPTIONS are passed through to _items_cust_bill_pkg, and should include
3107 'format' and 'escape_function' at minimum.
3108
3109 To produce items for a specific invoice section, OPTIONS should include
3110 'section', a hashref containing 'category' and/or 'locationnum' keys.
3111
3112 'section' may also contain a key named 'condensed'. If this is present
3113 and has a true value, _items_pkg will try to merge identical items into items
3114 with 'quantity' equal to the number of items (not the sum of their separate
3115 quantities, for some reason).
3116
3117 =cut
3118
3119 sub _items_nontax {
3120   my $self = shift;
3121   # The order of these is important.  Bundled line items will be merged into
3122   # the most recent non-hidden item, so it needs to be the one with:
3123   # - the same pkgnum
3124   # - the same start date
3125   # - no pkgpart_override
3126   #
3127   # So: sort by pkgnum,
3128   # then by sdate
3129   # then sort the base line item before any overrides
3130   # then sort hidden before non-hidden add-ons
3131   # then sort by override pkgpart (for consistency)
3132   sort { $a->pkgnum <=> $b->pkgnum        or
3133          $a->sdate  <=> $b->sdate         or
3134          ($a->pkgpart_override ? 0 : -1)  or
3135          ($b->pkgpart_override ? 0 : 1)   or
3136          $b->hidden cmp $a->hidden        or
3137          $a->pkgpart_override <=> $b->pkgpart_override
3138        }
3139   # and of course exclude taxes and fees
3140   grep { $_->pkgnum > 0 } $self->cust_bill_pkg;
3141 }
3142
3143 sub _items_fee {
3144   my $self = shift;
3145   my %options = @_;
3146   my @cust_bill_pkg = grep { $_->feepart } $self->cust_bill_pkg;
3147   my $escape_function = $options{escape_function};
3148
3149   my $locale = $self->cust_main
3150              ? $self->cust_main->locale
3151              : $self->prospect_main->locale;
3152
3153   my @items;
3154   foreach my $cust_bill_pkg (@cust_bill_pkg) {
3155     # cache this, so we don't look it up again in every section
3156     my $part_fee = $cust_bill_pkg->get('part_fee')
3157        || $cust_bill_pkg->part_fee;
3158     $cust_bill_pkg->set('part_fee', $part_fee);
3159     if (!$part_fee) {
3160       #die "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n"; # might make more sense
3161       warn "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n";
3162       next;
3163     }
3164
3165     # If _items_fee is called while building a sectioned invoice,
3166     #   - invoice_sections_method: category
3167     #     Skip fee records that do not match the section category.
3168     #   - invoice_sections_method: location
3169     #     Skip fee records always for location sections.
3170     #     The fee records will be presented in the tax/fee section instead.
3171     if (
3172       exists( $options{section} )
3173       and
3174       (
3175         (
3176           exists( $options{section}{category} )
3177           and
3178           $part_fee->categoryname ne $options{section}{category}
3179         )
3180         or
3181         exists( $options{section}{location})
3182       )
3183     ) {
3184       warn "skipping fee '".$part_fee->itemdesc.
3185            "'--not in section $options{section}{category}\n" if $DEBUG;
3186       next;
3187     }
3188
3189     my @ext_desc;
3190     my %base_invnums; # invnum => invoice date
3191     foreach ($cust_bill_pkg->cust_bill_pkg_fee) {
3192       if ($_->base_invnum) {
3193         my $base_bill = FS::cust_bill->by_key($_->base_invnum);
3194         my $base_date = $self->time2str_local('short', $base_bill->_date)
3195           if $base_bill;
3196         $base_invnums{$_->base_invnum} = $base_date || '';
3197       }
3198     }
3199     foreach (sort keys(%base_invnums)) {
3200       next if $_ == $self->invnum;
3201       # per convention, we must escape ext_description lines
3202       push @ext_desc,
3203         &{$escape_function}(
3204           $self->mt('from invoice #[_1] on [_2]', $_, $base_invnums{$_})
3205         );
3206     }
3207     my $desc = $part_fee->itemdesc_locale($locale);
3208     # but not escape the base description line
3209
3210     my @pkg_tax = $cust_bill_pkg->_pkg_tax_list
3211       if $options{section_with_taxes};
3212
3213     push @items,
3214       { feepart     => $cust_bill_pkg->feepart,
3215         billpkgnum  => $cust_bill_pkg->billpkgnum,
3216         amount      => sprintf('%.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
3217         description => $desc,
3218         pkg_tax     => \@pkg_tax,
3219         ext_description => \@ext_desc,
3220         # sdate/edate?
3221       };
3222   }
3223   @items;
3224 }
3225
3226 sub _items_pkg {
3227   my $self = shift;
3228   my %options = @_;
3229
3230   warn "$me _items_pkg searching for all package line items\n"
3231     if $DEBUG > 1;
3232
3233   my @cust_bill_pkg = $self->_items_nontax;
3234
3235   warn "$me _items_pkg filtering line items\n"
3236     if $DEBUG > 1;
3237   my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3238
3239   if ($options{section} && $options{section}->{condensed}) {
3240
3241     warn "$me _items_pkg condensing section\n"
3242       if $DEBUG > 1;
3243
3244     my %itemshash = ();
3245     local $Storable::canonical = 1;
3246     foreach ( @items ) {
3247       my $item = { %$_ };
3248       delete $item->{ref};
3249       delete $item->{ext_description};
3250       my $key = freeze($item);
3251       $itemshash{$key} ||= 0;
3252       $itemshash{$key} ++; # += $item->{quantity};
3253     }
3254     @items = sort { $a->{description} cmp $b->{description} }
3255              map { my $i = thaw($_);
3256                    $i->{quantity} = $itemshash{$_};
3257                    $i->{amount} =
3258                      sprintf( "%.2f", $i->{quantity} * $i->{amount} );#unit_amount
3259                    $i;
3260                  }
3261              keys %itemshash;
3262   }
3263
3264   warn "$me _items_pkg returning ". scalar(@items). " items\n"
3265     if $DEBUG > 1;
3266
3267   @items;
3268 }
3269
3270 sub _taxsort {
3271   return 0 unless $a->itemdesc cmp $b->itemdesc;
3272   return -1 if $b->itemdesc eq 'Tax';
3273   return 1 if $a->itemdesc eq 'Tax';
3274   return -1 if $b->itemdesc eq 'Other surcharges';
3275   return 1 if $a->itemdesc eq 'Other surcharges';
3276   $a->itemdesc cmp $b->itemdesc;
3277 }
3278
3279 sub _items_tax {
3280   my $self = shift;
3281   my @cust_bill_pkg = sort _taxsort grep { ! $_->pkgnum and ! $_->feepart }
3282     $self->cust_bill_pkg;
3283   my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3284
3285   if ( $self->conf->exists('always_show_tax') ) {
3286     my $itemdesc = $self->conf->config('always_show_tax') || 'Tax';
3287     if (0 == grep { $_->{description} eq $itemdesc } @items) {
3288       push @items,
3289         { 'description' => $itemdesc,
3290           'amount'      => 0.00 };
3291     }
3292   }
3293   @items;
3294 }
3295
3296 =item _items_cust_bill_pkg CUST_BILL_PKGS OPTIONS
3297
3298 Takes an arrayref of L<FS::cust_bill_pkg> objects, and returns a
3299 list of hashrefs describing the line items they generate on the invoice.
3300
3301 OPTIONS may include:
3302
3303 format: the invoice format.
3304
3305 escape_function: the function used to escape strings.
3306
3307 DEPRECATED? (expensive, mostly unused?)
3308 format_function: the function used to format CDRs.
3309
3310 section: a hashref containing 'category' and/or 'locationnum'; if this
3311 is present, only returns line items that belong to that category and/or
3312 location (whichever is defined).
3313
3314 multisection: a flag indicating that this is a multisection invoice,
3315 which does something complicated.
3316
3317 section_with_taxes:  Look up and include applied taxes for each record
3318
3319 Returns a list of hashrefs, each of which may contain:
3320
3321 pkgnum, description, amount, unit_amount, quantity, pkgpart, _is_setup, and
3322 ext_description, which is an arrayref of detail lines to show below
3323 the package line.
3324
3325 =cut
3326
3327 sub _items_cust_bill_pkg {
3328   my $self = shift;
3329   my $conf = $self->conf;
3330   my $cust_bill_pkgs = shift;
3331   my %opt = @_;
3332
3333   my $format = $opt{format} || '';
3334   my $escape_function = $opt{escape_function} || sub { shift };
3335   my $format_function = $opt{format_function} || '';
3336   my $no_usage = $opt{no_usage} || '';
3337   my $unsquelched = $opt{unsquelched} || ''; #unused
3338   my ($section, $locationnum, $category);
3339   if ( $opt{section} ) {
3340     $category = $opt{section}->{category};
3341     $locationnum = $opt{section}->{locationnum};
3342   }
3343   my $summary_page = $opt{summary_page} || ''; #unused
3344   my $multisection = defined($category) || defined($locationnum);
3345   # this variable is the value of the config setting, not whether it applies
3346   # to this particular line item.
3347   my $discount_show_always = $conf->exists('discount-show-always');
3348
3349   my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 40;
3350
3351   my $cust_main = $self->cust_main;#for per-agent cust_bill-line_item-ate_style
3352
3353   my $agentnum = $self->agentnum;
3354
3355   # for location labels: use default location on the invoice date
3356   my $default_locationnum;
3357   if ( $conf->exists('invoice-all_pkg_addresses') ) {
3358     $default_locationnum = 0; # treat them all as non-default
3359   } elsif ( $self->custnum ) {
3360     my $h_cust_main;
3361     my @h_search = FS::h_cust_main->sql_h_search($self->_date);
3362     $h_cust_main = qsearchs({
3363         'table'     => 'h_cust_main',
3364         'hashref'   => { custnum => $self->custnum },
3365         'extra_sql' => $h_search[1],
3366         'addl_from' => $h_search[3],
3367     }) || $cust_main;
3368     $default_locationnum = $h_cust_main->ship_locationnum;
3369   } elsif ( $self->prospectnum ) {
3370     my $cust_location = qsearchs('cust_location',
3371       { prospectnum => $self->prospectnum,
3372         disabled => '' });
3373     $default_locationnum = $cust_location->locationnum if $cust_location;
3374   }
3375
3376   my @b = (); # accumulator for the line item hashes that we'll return
3377   my ($s, $r, $u, $d) = ( undef, undef, undef, undef );
3378             # the 'current' line item hashes for setup, recur, usage, discount
3379   foreach my $cust_bill_pkg ( @$cust_bill_pkgs )
3380   {
3381     # if the current line item is waiting to go out, and the one we're about
3382     # to start is not bundled, then push out the current one and start a new
3383     # one.
3384     if ( $d ) {
3385       $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3386     }
3387     foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3388       if ( $_ && !$cust_bill_pkg->hidden ) {
3389         $_->{amount}      = sprintf( "%.2f", $_->{amount} );
3390         $_->{amount}      =~ s/^\-0\.00$/0.00/;
3391         if (exists($_->{unit_amount})) {
3392           $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3393         }
3394         push @b, { %$_ };
3395         # we already decided to create this display line; don't reconsider it
3396         # now.
3397         #  if $_->{amount} != 0
3398         #  || $discount_show_always
3399         #  || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3400         #  || (   $_->{_is_setup} && $_->{setup_show_zero} )
3401         ;
3402         $_ = undef;
3403       }
3404     }
3405
3406     if ( $locationnum ) {
3407       # this is a location section; skip packages that aren't at this
3408       # service location.
3409       next if $cust_bill_pkg->pkgnum == 0; # skips fees...
3410       next if $self->cust_pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum
3411               != $locationnum;
3412     }
3413
3414     # Consider display records for this item to determine if it belongs
3415     # in this section.  Note that if there are no display records, there
3416     # will be a default pseudo-record that includes all charge types
3417     # and has no section name.
3418     my @cust_bill_pkg_display = $cust_bill_pkg->can('cust_bill_pkg_display')
3419                                   ? $cust_bill_pkg->cust_bill_pkg_display
3420                                   : ( $cust_bill_pkg );
3421
3422     warn "$me _items_cust_bill_pkg considering cust_bill_pkg ".
3423          $cust_bill_pkg->billpkgnum. ", pkgnum ". $cust_bill_pkg->pkgnum. "\n"
3424       if $DEBUG > 1;
3425
3426     if ( defined($category) ) {
3427       # then this is a package category section; process all display records
3428       # that belong to this section.
3429       @cust_bill_pkg_display = grep { $_->section eq $category }
3430                                 @cust_bill_pkg_display;
3431     } else {
3432       # otherwise, process all display records that aren't usage summaries
3433       # (I don't think there should be usage summaries if you aren't using
3434       # category sections, but this is the historical behavior)
3435       @cust_bill_pkg_display = grep { !$_->summary }
3436                                 @cust_bill_pkg_display;
3437     }
3438
3439     my $classname = ''; # package class name, will fill in later
3440
3441     foreach my $display (@cust_bill_pkg_display) {
3442
3443       warn "$me _items_cust_bill_pkg considering cust_bill_pkg_display ".
3444            $display->billpkgdisplaynum. "\n"
3445         if $DEBUG > 1;
3446
3447       my $type = $display->type;
3448
3449       my $desc = $cust_bill_pkg->desc( $cust_main ? $cust_main->locale : '' );
3450       $desc = substr($desc, 0, $maxlength). '...'
3451         if $format eq 'latex' && length($desc) > $maxlength;
3452
3453       my %details_opt = ( 'format'          => $format,
3454                           'escape_function' => $escape_function,
3455                           'format_function' => $format_function,
3456                           'no_usage'        => $opt{'no_usage'},
3457                         );
3458
3459       if ( $cust_bill_pkg->pkgnum > 0 ) {
3460         # a "normal" package line item (not a quotation, not a fee, not a tax)
3461
3462         warn "$me _items_cust_bill_pkg cust_bill_pkg is non-tax\n"
3463           if $DEBUG > 1;
3464
3465         my $cust_pkg = $cust_bill_pkg->cust_pkg;
3466
3467         unless ( $cust_pkg ) {
3468           # There is no related row in cust_pkg for this cust_bill_pkg.pkgnum.
3469           # This invoice may have been broken by an unusual combination
3470           # of manually editing package dates, and aborted package changes
3471           # when the manually edited dates used are nonsensical.
3472
3473           my $error = sprintf
3474             'cust_bill_pkg(billpkgnum:%s) '.
3475             'is missing related row in cust_pkg(pkgnum:%s)! '.
3476             'cust_bill(invnum:%s) is corrupted by bad database data, '.
3477             'and should be investigated',
3478               $cust_bill_pkg->billpkgnum,
3479               $cust_bill_pkg->pkgnum,
3480               $cust_bill_pkg->invnum;
3481
3482           FS::Log->new('FS::cust_bill_pkg')->critical( $error );
3483           warn $error;
3484           next;
3485         }
3486
3487         my $part_pkg = $cust_pkg->part_pkg;
3488
3489         # which pkgpart to show for display purposes?
3490         my $pkgpart = $cust_bill_pkg->pkgpart_override || $cust_pkg->pkgpart;
3491
3492         # start/end dates for invoice formats that do nonstandard
3493         # things with them
3494         my %item_dates = ();
3495         %item_dates = map { $_ => $cust_bill_pkg->$_ } ('sdate', 'edate')
3496           unless $part_pkg->option('disable_line_item_date_ranges',1);
3497
3498         # not normally used, but pass this to the template anyway
3499         $classname = $part_pkg->classname;
3500
3501         my @pkg_tax = $cust_bill_pkg->_pkg_tax_list
3502           if $opt{section_with_taxes};
3503
3504         if (    (!$type || $type eq 'S')
3505              && (    $cust_bill_pkg->setup != 0
3506                   || $cust_bill_pkg->setup_show_zero
3507                   || ($discount_show_always and $cust_bill_pkg->unitsetup > 0)
3508                 )
3509            )
3510          {
3511
3512           warn "$me _items_cust_bill_pkg adding setup\n"
3513             if $DEBUG > 1;
3514
3515           # append the word 'Setup' to the setup line if there's going to be
3516           # a recur line for the same package (i.e. not a one-time charge)
3517           # XXX localization
3518           my $description = $desc;
3519           $description .= ' Setup'
3520             if $cust_bill_pkg->recur != 0
3521             || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3522             || $cust_bill_pkg->recur_show_zero;
3523
3524           my $disable_date_ranges =
3525                $opt{disable_line_item_date_ranges}
3526             || $part_pkg->option('disable_line_item_date_ranges', 1);
3527
3528           $description .= $cust_bill_pkg->time_period_pretty(
3529                             $part_pkg,
3530                             $agentnum,
3531                             disable_date_ranges => $disable_date_ranges,
3532                           )
3533             if $part_pkg->is_prepaid #for prepaid, "display the validity period
3534                                      # triggered by the recurring charge freq
3535                                      # (RT#26274)
3536             && $cust_bill_pkg->recur == 0
3537             && ! $cust_bill_pkg->recur_show_zero;
3538
3539           my @d = ();
3540           my @svc_labels = ();
3541           my $svc_label = '';
3542
3543           unless ( $part_pkg->hide_svc_detail ) {
3544
3545             # still pass the svc_label through to the template, even if
3546             # not displaying it as an ext_description
3547             @svc_labels = map &{$escape_function}($_),
3548               $cust_pkg->h_labels_short($self->_date,
3549                                         undef,
3550                                         'I',
3551                                         $self->conf->{locale},
3552                                        );
3553             $svc_label = $svc_labels[0];
3554
3555           }
3556
3557           unless ( $part_pkg->hide_svc_detail
3558                 || $cust_bill_pkg->hidden )
3559           {
3560
3561             push @d, @svc_labels
3562               unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3563             # show the location label if it's not the customer's default
3564             # location, and we're not grouping items by location already
3565             if ( $cust_pkg->locationnum != $default_locationnum
3566                   and !defined($locationnum) ) {
3567               my $loc = $cust_pkg->location_label;
3568               $loc = substr($loc, 0, $maxlength). '...'
3569                 if $format eq 'latex' && length($loc) > $maxlength;
3570               push @d, &{$escape_function}($loc);
3571             }
3572
3573           } #unless hiding service details
3574
3575           push @d, $cust_bill_pkg->details(%details_opt)
3576             if $cust_bill_pkg->recur == 0;
3577
3578           if ( $cust_bill_pkg->hidden ) {
3579             $s->{amount}      += $cust_bill_pkg->setup;
3580             $s->{unit_amount} += $cust_bill_pkg->unitsetup;
3581             push @{ $s->{ext_description} }, @d;
3582           } else {
3583             $s = {
3584               billpkgnum      => $cust_bill_pkg->billpkgnum,
3585               _is_setup       => 1,
3586               description     => $description,
3587               pkgpart         => $pkgpart,
3588               pkgnum          => $cust_bill_pkg->pkgnum,
3589               amount          => $cust_bill_pkg->setup,
3590               setup_show_zero => $cust_bill_pkg->setup_show_zero,
3591               unit_amount     => $cust_bill_pkg->unitsetup,
3592               quantity        => $cust_bill_pkg->quantity,
3593               ext_description => \@d,
3594               svc_label       => ($svc_label || ''),
3595               locationnum     => $cust_pkg->locationnum, # sure, why not?
3596               pkg_tax         => \@pkg_tax,
3597             };
3598           };
3599
3600         }
3601
3602         # should we show a recur line?
3603         # if type eq 'S', then NO, because we've been told not to.
3604         # otherwise, show the recur line if:
3605         # - there's a recurring charge
3606         # - or recur_show_zero is on
3607         # - or there's a positive unitrecur (so it's been discounted to zero)
3608         #   and discount-show-always is on
3609         if (    ( !$type || $type eq 'R' || $type eq 'U' )
3610              && (
3611                      $cust_bill_pkg->recur != 0
3612                   || !defined($s)
3613                   || ($discount_show_always and $cust_bill_pkg->unitrecur > 0)
3614                   || $cust_bill_pkg->recur_show_zero
3615                 )
3616            )
3617         {
3618
3619           warn "$me _items_cust_bill_pkg adding recur/usage\n"
3620             if $DEBUG > 1;
3621
3622           my $is_summary = $display->summary;
3623           my $description = $desc;
3624           if ( $type eq 'U' and defined($r) ) {
3625             # don't just show the same description as the recur line
3626             $description = $self->mt('Usage charges');
3627           }
3628
3629           my $disable_date_ranges =
3630                $opt{disable_line_item_date_ranges}
3631             || $part_pkg->option('disable_line_item_date_ranges', 1);
3632
3633           $description .= $cust_bill_pkg->time_period_pretty(
3634                                     $part_pkg,
3635                                     $agentnum,
3636                                     disable_date_ranges => $disable_date_ranges,
3637                           );
3638
3639           my @d = ();
3640           my @seconds = (); # for display of usage info
3641           my @svc_labels = ();
3642           my $svc_label = '';
3643
3644           #at least until cust_bill_pkg has "past" ranges in addition to
3645           #the "future" sdate/edate ones... see #3032
3646           my @dates = ( $self->_date );
3647           my $prev = $cust_bill_pkg->previous_cust_bill_pkg;
3648           push @dates, $prev->sdate if $prev;
3649           push @dates, undef if !$prev;
3650
3651           unless ( $part_pkg->hide_svc_detail ) {
3652             @svc_labels = map &{$escape_function}($_),
3653               $cust_pkg->h_labels_short(@dates,
3654                                         'I',
3655                                         $self->conf->{locale});
3656             $svc_label = $svc_labels[0];
3657           }
3658
3659           # show service labels, unless...
3660                     # the package is set not to display them
3661           unless ( $part_pkg->hide_svc_detail
3662                     # or this is a tax-like line item
3663                 || $cust_bill_pkg->itemdesc
3664                     # or this is a hidden (bundled) line item
3665                 || $cust_bill_pkg->hidden
3666                     # or this is a usage summary line
3667                 || $is_summary && $type && $type eq 'U'
3668                     # or this is a usage line and there's a recurring line
3669                     # for the package in the same section (which will
3670                     # have service labels already)
3671                 || ($type eq 'U' and defined($r))
3672               )
3673           {
3674
3675             warn "$me _items_cust_bill_pkg adding service details\n"
3676               if $DEBUG > 1;
3677
3678             push @d, @svc_labels
3679               unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
3680             warn "$me _items_cust_bill_pkg done adding service details\n"
3681               if $DEBUG > 1;
3682
3683             # show the location label if it's not the customer's default
3684             # location, and we're not grouping items by location already
3685             if ( $cust_pkg->locationnum != $default_locationnum
3686                   and !defined($locationnum) ) {
3687               my $loc = $cust_pkg->location_label;
3688               $loc = substr($loc, 0, $maxlength). '...'
3689                 if $format eq 'latex' && length($loc) > $maxlength;
3690               push @d, &{$escape_function}($loc);
3691             }
3692
3693             # Display of seconds_since_sqlradacct:
3694             # On the invoice, when processing @detail_items, look for a field
3695             # named 'seconds'.  This will contain total seconds for each
3696             # service, in the same order as @ext_description.  For services
3697             # that don't support this it will show undef.
3698             if ( $conf->exists('svc_acct-usage_seconds')
3699                  and ! $cust_bill_pkg->pkgpart_override ) {
3700               foreach my $cust_svc (
3701                   $cust_pkg->h_cust_svc(@dates, 'I')
3702                 ) {
3703
3704                 # eval because not having any part_export_usage exports
3705                 # is a fatal error, last_bill/_date because that's how
3706                 # sqlradius_hour billing does it
3707                 my $sec = eval {
3708                   $cust_svc->seconds_since_sqlradacct($dates[1] || 0, $dates[0]);
3709                 };
3710                 push @seconds, $sec;
3711               }
3712             } #if svc_acct-usage_seconds
3713
3714           } # if we are showing service labels
3715
3716           unless ( $is_summary ) {
3717             warn "$me _items_cust_bill_pkg adding details\n"
3718               if $DEBUG > 1;
3719
3720             #instead of omitting details entirely in this case (unwanted side
3721             # effects), just omit CDRs
3722             $details_opt{'no_usage'} = 1
3723               if $type && $type eq 'R';
3724
3725             push @d, $cust_bill_pkg->details(%details_opt);
3726           }
3727
3728           warn "$me _items_cust_bill_pkg calculating amount\n"
3729             if $DEBUG > 1;
3730
3731           my $amount = 0;
3732           if (!$type) {
3733             $amount = $cust_bill_pkg->recur;
3734           } elsif ($type eq 'R') {
3735             $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
3736           } elsif ($type eq 'U') {
3737             $amount = $cust_bill_pkg->usage;
3738           }
3739
3740           if ( !$type || $type eq 'R' ) {
3741
3742             warn "$me _items_cust_bill_pkg adding recur\n"
3743               if $DEBUG > 1;
3744
3745             my $unit_amount =
3746               ( $cust_bill_pkg->unitrecur > 0 ) ? $cust_bill_pkg->unitrecur
3747                                                 : $amount;
3748
3749             if ( $cust_bill_pkg->hidden ) {
3750               $r->{amount}      += $amount;
3751               $r->{unit_amount} += $unit_amount;
3752               push @{ $r->{ext_description} }, @d;
3753             } else {
3754               $r = {
3755                 billpkgnum      => $cust_bill_pkg->billpkgnum,
3756                 description     => $description,
3757                 pkgpart         => $pkgpart,
3758                 pkgnum          => $cust_bill_pkg->pkgnum,
3759                 amount          => $amount,
3760                 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3761                 unit_amount     => $unit_amount,
3762                 quantity        => $cust_bill_pkg->quantity,
3763                 %item_dates,
3764                 ext_description => \@d,
3765                 svc_label       => ($svc_label || ''),
3766                 locationnum     => $cust_pkg->locationnum,
3767                 pkg_tax         => \@pkg_tax,
3768               };
3769               $r->{'seconds'} = \@seconds if grep {defined $_} @seconds;
3770             }
3771
3772           } else {  # $type eq 'U'
3773
3774             warn "$me _items_cust_bill_pkg adding usage\n"
3775               if $DEBUG > 1;
3776
3777             if ( $cust_bill_pkg->hidden and defined($u) ) {
3778               # if this is a hidden package and there's already a usage
3779               # line for the bundle, add this package's total amount and
3780               # usage details to it
3781               $u->{amount}      += $amount;
3782               push @{ $u->{ext_description} }, @d;
3783             } elsif ( $amount ) {
3784               # create a new usage line
3785               $u = {
3786                 billpkgnum      => $cust_bill_pkg->billpkgnum,
3787                 description     => $description,
3788                 pkgpart         => $pkgpart,
3789                 pkgnum          => $cust_bill_pkg->pkgnum,
3790                 amount          => $amount,
3791                 usage_item      => 1,
3792                 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3793                 %item_dates,
3794                 ext_description => \@d,
3795                 locationnum     => $cust_pkg->locationnum,
3796                 pkg_tax         => \@pkg_tax,
3797               };
3798             } # else this has no usage, so don't create a usage section
3799           }
3800
3801         } # recurring or usage with recurring charge
3802
3803       } else { # taxes and fees
3804
3805         warn "$me _items_cust_bill_pkg cust_bill_pkg is tax\n"
3806           if $DEBUG > 1;
3807
3808         # items of this kind should normally not have sdate/edate.
3809         push @b, {
3810           'description' => $desc,
3811           'amount'      => sprintf('%.2f', $cust_bill_pkg->setup
3812                                            + $cust_bill_pkg->recur)
3813         };
3814
3815       } # if package line item / other line item
3816
3817       # decide whether to show active discounts here
3818       if (
3819           # case 1: we are showing a single line for the package
3820           ( !$type )
3821           # case 2: we are showing a setup line for a package that has
3822           # no base recurring fee
3823           or ( $type eq 'S' and $cust_bill_pkg->unitrecur == 0 )
3824           # case 3: we are showing a recur line for a package that has
3825           # a base recurring fee
3826           or ( $type eq 'R' and $cust_bill_pkg->unitrecur > 0 )
3827       ) {
3828
3829         my $item_discount = $cust_bill_pkg->_item_discount;
3830         if ( $item_discount ) {
3831           # $item_discount->{amount} is negative
3832
3833           if ( $d and $cust_bill_pkg->hidden ) {
3834             $d->{setup_amount} += $item_discount->{setup_amount};
3835             $d->{recur_amount} += $item_discount->{recur_amount};
3836           } else {
3837             $d = $item_discount;
3838             $_ = &{$escape_function}($_) foreach @{ $d->{ext_description} };
3839           }
3840
3841           # update the active line (before the discount) to show the
3842           # original price (whether this is a hidden line or not)
3843
3844           $s->{amount} -= $item_discount->{setup_amount} if $s;
3845           $r->{amount} -= $item_discount->{recur_amount} if $r;
3846
3847         } # if there are any discounts
3848       } # if this is an appropriate place to show discounts
3849
3850     } # foreach $display
3851
3852   }
3853
3854   # discount amount is internally split up
3855   if ( $d ) {
3856     $d->{amount} = $d->{setup_amount} + $d->{recur_amount};
3857   }
3858
3859   foreach ( $s, $r, ($opt{skip_usage} ? () : $u ), $d ) {
3860     if ( $_  ) {
3861       $_->{amount}      = sprintf( "%.2f", $_->{amount} ),
3862         if exists($_->{amount});
3863       $_->{amount}      =~ s/^\-0\.00$/0.00/;
3864       if (exists($_->{unit_amount})) {
3865         $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} );
3866       }
3867
3868       push @b, { %$_ };
3869       #if $_->{amount} != 0
3870       #  || $discount_show_always
3871       #  || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3872       #  || (   $_->{_is_setup} && $_->{setup_show_zero} )
3873     }
3874   }
3875
3876   warn "$me _items_cust_bill_pkg done considering cust_bill_pkgs\n"
3877     if $DEBUG > 1;
3878
3879   @b;
3880
3881 }
3882
3883 =item _items_discounts_avail
3884
3885 Returns an array of line item hashrefs representing available term discounts
3886 for this invoice.  This makes the same assumptions that apply to term
3887 discounts in general: that the package is billed monthly, at a flat rate,
3888 with no usage charges.  A prorated first month will be handled, as will
3889 a setup fee if the discount is allowed to apply to setup fees.
3890
3891 =cut
3892
3893 sub _items_discounts_avail {
3894   my $self = shift;
3895
3896   #maybe move this method from cust_bill when quotations support discount_plans
3897   return () unless $self->can('discount_plans');
3898   my %plans = $self->discount_plans;
3899
3900   my $list_pkgnums = 0; # if any packages are not eligible for all discounts
3901   $list_pkgnums = grep { $_->list_pkgnums } values %plans;
3902
3903   map {
3904     my $months = $_;
3905     my $plan = $plans{$months};
3906
3907     my $term_total = sprintf('%.2f', $plan->discounted_total);
3908     my $percent = sprintf('%.0f',
3909                           100 * (1 - $term_total / $plan->base_total) );
3910     my $permonth = sprintf('%.2f', $term_total / $months);
3911     my $detail = $self->mt('discount on item'). ' '.
3912                  join(', ', map { "#$_" } $plan->pkgnums)
3913       if $list_pkgnums;
3914
3915     # discounts for non-integer months don't work anyway
3916     $months = sprintf("%d", $months);
3917
3918     +{
3919       description => $self->mt('Save [_1]% by paying for [_2] months',
3920                                 $percent, $months),
3921       amount      => $self->mt('[_1] ([_2] per month)',
3922                                 $term_total, $money_char.$permonth),
3923       ext_description => ($detail || ''),
3924     }
3925   } #map
3926   sort { $b <=> $a } keys %plans;
3927
3928 }
3929
3930 =item has_sections AGENTNUM
3931
3932 Return true if invoice_sections should be enabled for this bill.
3933  (Inherited by both cust_bill and cust_bill_void)
3934
3935 Determination:
3936 * False if not an invoice
3937 * True always if conf invoice_sections is enabled
3938 * True always if sections_by_location is enabled
3939 * True if conf invoice_sections_multilocation > 1,
3940   and location_count >= invoice_sections_multilocation
3941 * Else, False
3942
3943 =cut
3944
3945 sub has_sections {
3946   my ($self, $agentnum) = @_;
3947
3948   return 0 unless $self->invnum > 0;
3949
3950   $agentnum ||= $self->agentnum;
3951   return 1 if $self->conf->config_bool('invoice_sections', $agentnum);
3952   return 1 if $self->conf->exists('sections_by_location', $agentnum);
3953
3954   my $location_min = $self->conf->config(
3955     'invoice_sections_multilocation', $agentnum,
3956   );
3957
3958   return 1
3959     if $location_min
3960     && $self->location_count >= $location_min;
3961
3962   0;
3963 }
3964
3965
3966 =item location_count
3967
3968 Return the number of locations billed on this invoice
3969
3970 =cut
3971
3972 sub location_count {
3973   my ($self) = @_;
3974   return 0 unless $self->invnum;
3975
3976   # SELECT COUNT( DISTINCT cust_pkg.locationnum )
3977   # FROM cust_bill_pkg
3978   # LEFT JOIN cust_pkg USING (pkgnum)
3979   # WHERE invnum = 278
3980   #   AND cust_bill_pkg.pkgnum > 0
3981
3982   my $result = qsearchs({
3983     select    => 'COUNT(DISTINCT cust_pkg.locationnum) as location_count',
3984     table     => 'cust_bill_pkg',
3985     addl_from => 'LEFT JOIN cust_pkg USING (pkgnum)',
3986     extra_sql => 'WHERE invnum = '.dbh->quote( $self->invnum )
3987                . '  AND cust_bill_pkg.pkgnum > 0'
3988   });
3989   ref $result ? $result->location_count : 0;
3990 }
3991
3992
3993
3994 1;