optimize history search (invoice rending time for svc_ records with tons of changes...
[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);
11 use Date::Format;
12 use Date::Language;
13 use Text::Template 1.20;
14 use File::Temp 0.14;
15 use HTML::Entities;
16 use Locale::Country;
17 use Cwd;
18 use FS::UID;
19 use FS::Record qw( qsearch qsearchs );
20 use FS::Conf;
21 use FS::Misc qw( generate_ps generate_pdf );
22 use FS::pkg_category;
23 use FS::pkg_class;
24 use FS::invoice_mode;
25 use FS::L10N;
26
27 $DEBUG = 0;
28 $me = '[FS::Template_Mixin]';
29 FS::UID->install_callback( sub { 
30   my $conf = new FS::Conf; #global
31   $money_char  = $conf->config('money_char')  || '$';  
32   $date_format = $conf->config('date_format') || '%x'; #/YY
33 } );
34
35 =item conf [ MODE ]
36
37 Returns a configuration handle (L<FS::Conf>) set to the customer's locale.
38
39 If the "mode" pseudo-field is set on the object, the configuration handle
40 will be an L<FS::invoice_conf> for that invoice mode (and the customer's
41 locale).
42
43 =cut
44
45 sub conf {
46   my $self = shift;
47   my $mode = $self->get('mode');
48   if ($self->{_conf} and !defined($mode)) {
49     return $self->{_conf};
50   }
51
52   my $cust_main = $self->cust_main;
53   my $locale = $cust_main ? $cust_main->locale : '';
54   my $conf;
55   if ( $mode ) {
56     if ( ref $mode and $mode->isa('FS::invoice_mode') ) {
57       $mode = $mode->modenum;
58     } elsif ( $mode =~ /\D/ ) {
59       die "invalid invoice mode $mode";
60     }
61     $conf = qsearchs('invoice_conf', { modenum => $mode, locale => $locale });
62     if (!$conf) {
63       $conf = qsearchs('invoice_conf', { modenum => $mode, locale => '' });
64       # it doesn't have a locale, but system conf still might
65       $conf->set('locale' => $locale) if $conf;
66     }
67   }
68   # if $mode is unspecified, or if there is no invoice_conf matching this mode
69   # and locale, then use the system config only (but with the locale)
70   $conf ||= FS::Conf->new({ 'locale' => $locale });
71   # cache it
72   return $self->{_conf} = $conf;
73 }
74
75 =item print_text OPTIONS
76
77 Returns an text invoice, as a list of lines.
78
79 Options can be passed as a hash.
80
81 I<time>, if specified, is used to control the printing of overdue messages.  The
82 default is now.  It isn't the date of the invoice; that's the `_date' field.
83 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
84 L<Time::Local> and L<Date::Parse> for conversion functions.
85
86 I<template>, if specified, is the name of a suffix for alternate invoices.
87
88 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
89
90 =cut
91
92 sub print_text {
93   my $self = shift;
94   my %params;
95   if ( ref($_[0]) ) {
96     %params = %{ shift() };
97   } else {
98     %params = @_;
99   }
100
101   $params{'format'} = 'template'; # for some reason
102
103   $self->print_generic( %params );
104 }
105
106 =item print_latex HASHREF
107
108 Internal method - returns a filename of a filled-in LaTeX template for this
109 invoice (Note: add ".tex" to get the actual filename), and a filename of
110 an associated logo (with the .eps extension included).
111
112 See print_ps and print_pdf for methods that return PostScript and PDF output.
113
114 Options can be passed as a hash.
115
116 I<time>, if specified, is used to control the printing of overdue messages.  The
117 default is now.  It isn't the date of the invoice; that's the `_date' field.
118 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
119 L<Time::Local> and L<Date::Parse> for conversion functions.
120
121 I<template>, if specified, is the name of a suffix for alternate invoices.  
122 This is strongly deprecated; see L<FS::invoice_conf> for the right way to
123 customize invoice templates for different purposes.
124
125 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
126
127 =cut
128
129 sub print_latex {
130   my $self = shift;
131   my %params;
132
133   if ( ref($_[0]) ) {
134     %params = %{ shift() };
135   } else {
136     %params = @_;
137   }
138
139   $params{'format'} = 'latex';
140   my $conf = $self->conf;
141
142   # this needs to go away
143   my $template = $params{'template'};
144   # and this especially
145   $template ||= $self->_agent_template
146     if $self->can('_agent_template');
147
148   my $pkey = $self->primary_key;
149   my $tmp_template = $self->table. '.'. $self->$pkey. '.XXXXXXXX';
150
151   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
152   my $lh = new File::Temp(
153     TEMPLATE => $tmp_template,
154     DIR      => $dir,
155     SUFFIX   => '.eps',
156     UNLINK   => 0,
157   ) or die "can't open temp file: $!\n";
158
159   my $agentnum = $self->agentnum;
160
161   if ( $template && $conf->exists("logo_${template}.eps", $agentnum) ) {
162     print $lh $conf->config_binary("logo_${template}.eps", $agentnum)
163       or die "can't write temp file: $!\n";
164   } else {
165     print $lh $conf->config_binary('logo.eps', $agentnum)
166       or die "can't write temp file: $!\n";
167   }
168   close $lh;
169   $params{'logo_file'} = $lh->filename;
170
171   if( $conf->exists('invoice-barcode') 
172         && $self->can('invoice_barcode')
173         && $self->invnum ) { # don't try to barcode statements
174       my $png_file = $self->invoice_barcode($dir);
175       my $eps_file = $png_file;
176       $eps_file =~ s/\.png$/.eps/g;
177       $png_file =~ /(barcode.*png)/;
178       $png_file = $1;
179       $eps_file =~ /(barcode.*eps)/;
180       $eps_file = $1;
181
182       my $curr_dir = cwd();
183       chdir($dir); 
184       # after painfuly long experimentation, it was determined that sam2p won't
185       # accept : and other chars in the path, no matter how hard I tried to
186       # escape them, hence the chdir (and chdir back, just to be safe)
187       system('sam2p', '-j:quiet', $png_file, 'EPS:', $eps_file ) == 0
188         or die "sam2p failed: $!\n";
189       unlink($png_file);
190       chdir($curr_dir);
191
192       $params{'barcode_file'} = $eps_file;
193   }
194
195   my @filled_in = $self->print_generic( %params );
196   
197   my $fh = new File::Temp( TEMPLATE => $tmp_template,
198                            DIR      => $dir,
199                            SUFFIX   => '.tex',
200                            UNLINK   => 0,
201                          ) or die "can't open temp file: $!\n";
202   binmode($fh, ':utf8'); # language support
203   print $fh join('', @filled_in );
204   close $fh;
205
206   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
207   return ($1, $params{'logo_file'}, $params{'barcode_file'});
208
209 }
210
211 sub agentnum {
212   my $self = shift;
213   my $cust_main = $self->cust_main;
214   $cust_main ? $cust_main->agentnum : $self->prospect_main->agentnum;
215 }
216
217 =item print_generic OPTION => VALUE ...
218
219 Internal method - returns a filled-in template for this invoice as a scalar.
220
221 See print_ps and print_pdf for methods that return PostScript and PDF output.
222
223 Required options
224
225 =over 4
226
227 =item format
228
229 The B<format> option is required and should be set to html, latex (print and PDF) or template (plaintext).
230
231 =back
232
233 Additional options
234
235 =over 4
236
237 =item notice_name
238
239 Overrides "Invoice" as the name of the sent document.
240
241 =item today
242
243 Used to control the printing of overdue messages.  The
244 default is now.  It isn't the date of the invoice; that's the `_date' field.
245 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
246 L<Time::Local> and L<Date::Parse> for conversion functions.
247
248 =item logo_file
249
250 Logo file (path to temporary EPS file on the local filesystem)
251
252 =item cid
253
254 CID for inline (emailed) images (logo)
255
256 =item locale
257
258 Override customer's locale
259
260 =item unsquelch_cdr
261
262 Overrides any per customer cdr squelching when true
263
264 =item no_number
265
266 Supress the (invoice, quotation, statement, etc.) number
267
268 =item no_date
269
270 Supress the date
271
272 =item no_coupon
273
274 Supress the payment coupon
275
276 =item barcode_file
277
278 Barcode file (path to temporary EPS file on the local filesystem)
279
280 =item barcode_img
281
282 Flag indicating the barcode image should be a link (normal HTML dipaly)
283
284 =item barcode_cid
285
286 Barcode CID for inline (emailed) images
287
288 =item preref_callback
289
290 Coderef run for each line item, code should return HTML to be displayed
291 before that line item (quotations only)
292
293 =item template
294
295 Dprecated.  Used as a suffix for a configuration template.  Please 
296 don't use this, it deprecated in favor of more flexible alternatives.
297
298 =back
299
300 =cut
301
302 #what's with all the sprintf('%10.2f')'s in here?  will it cause any
303 # (alignment in text invoice?) problems to change them all to '%.2f' ?
304 # yes: fixed width/plain text printing will be borked
305 sub print_generic {
306   my( $self, %params ) = @_;
307   my $conf = $self->conf;
308
309   my $today = $params{today} ? $params{today} : time;
310   warn "$me print_generic called on $self with suffix $params{template}\n"
311     if $DEBUG;
312
313   my $format = $params{format};
314   die "Unknown format: $format"
315     unless $format =~ /^(latex|html|template)$/;
316
317   my $cust_main = $self->cust_main || $self->prospect_main;
318   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
319     unless $cust_main->payname
320         && $cust_main->payby !~ /^(CARD|DCRD|CHEK|DCHK)$/;
321
322   my $locale = $params{'locale'} || $cust_main->locale;
323
324   my %delimiters = ( 'latex'    => [ '[@--', '--@]' ],
325                      'html'     => [ '<%=', '%>' ],
326                      'template' => [ '{', '}' ],
327                    );
328
329   warn "$me print_generic creating template\n"
330     if $DEBUG > 1;
331
332   # set the notice name here, and nowhere else.
333   my $notice_name =  $params{notice_name}
334                   || $conf->config('notice_name')
335                   || $self->notice_name;
336
337   #create the template
338   my $template = $params{template} ? $params{template} : $self->_agent_template;
339   my $templatefile = $self->template_conf. $format;
340   $templatefile .= "_$template"
341     if length($template) && $conf->exists($templatefile."_$template");
342
343   # the base template
344   my @invoice_template = map "$_\n", $conf->config($templatefile)
345     or die "cannot load config data $templatefile";
346
347   my $old_latex = '';
348   if ( $format eq 'latex' && grep { /^%%Detail/ } @invoice_template ) {
349     #change this to a die when the old code is removed
350     warn "old-style invoice template $templatefile; ".
351          "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
352     $old_latex = 'true';
353     @invoice_template = _translate_old_latex_format(@invoice_template);
354   } 
355
356   warn "$me print_generic creating T:T object\n"
357     if $DEBUG > 1;
358
359   my $text_template = new Text::Template(
360     TYPE => 'ARRAY',
361     SOURCE => \@invoice_template,
362     DELIMITERS => $delimiters{$format},
363   );
364
365   warn "$me print_generic compiling T:T object\n"
366     if $DEBUG > 1;
367
368   $text_template->compile()
369     or die "Can't compile $templatefile: $Text::Template::ERROR\n";
370
371
372   # additional substitution could possibly cause breakage in existing templates
373   my %convert_maps = ( 
374     'latex' => {
375                  'notes'         => sub { map "$_", @_ },
376                  'footer'        => sub { map "$_", @_ },
377                  'smallfooter'   => sub { map "$_", @_ },
378                  'returnaddress' => sub { map "$_", @_ },
379                  'coupon'        => sub { map "$_", @_ },
380                  'summary'       => sub { map "$_", @_ },
381                },
382     'html'  => {
383                  'notes' =>
384                    sub {
385                      map { 
386                        s/%%(.*)$/<!-- $1 -->/g;
387                        s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
388                        s/\\begin\{enumerate\}/<ol>/g;
389                        s/\\item /  <li>/g;
390                        s/\\end\{enumerate\}/<\/ol>/g;
391                        s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
392                        s/\\\\\*/<br>/g;
393                        s/\\dollar ?/\$/g;
394                        s/\\#/#/g;
395                        s/~/&nbsp;/g;
396                        $_;
397                      }  @_
398                    },
399                  'footer' =>
400                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
401                  'smallfooter' =>
402                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
403                  'returnaddress' =>
404                    sub {
405                      map { 
406                        s/~/&nbsp;/g;
407                        s/\\\\\*?\s*$/<BR>/;
408                        s/\\hyphenation\{[\w\s\-]+}//;
409                        s/\\([&])/$1/g;
410                        $_;
411                      }  @_
412                    },
413                  'coupon'        => sub { "" },
414                  'summary'       => sub { "" },
415                },
416     'template' => {
417                  'notes' =>
418                    sub {
419                      map { 
420                        s/%%.*$//g;
421                        s/\\section\*\{\\textsc\{(.*)\}\}/\U$1/g;
422                        s/\\begin\{enumerate\}//g;
423                        s/\\item /  * /g;
424                        s/\\end\{enumerate\}//g;
425                        s/\\textbf\{(.*)\}/$1/g;
426                        s/\\\\\*/ /;
427                        s/\\dollar ?/\$/g;
428                        $_;
429                      }  @_
430                    },
431                  'footer' =>
432                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
433                  'smallfooter' =>
434                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
435                  'returnaddress' =>
436                    sub {
437                      map { 
438                        s/~/ /g;
439                        s/\\\\\*?\s*$/\n/;             # dubious
440                        s/\\hyphenation\{[\w\s\-]+}//;
441                        $_;
442                      }  @_
443                    },
444                  'coupon'        => sub { "" },
445                  'summary'       => sub { "" },
446                },
447   );
448
449
450   # hashes for differing output formats
451   my %nbsps = ( 'latex'    => '~',
452                 'html'     => '',    # '&nbps;' would be nice
453                 'template' => '',    # not used
454               );
455   my $nbsp = $nbsps{$format};
456
457   my %escape_functions = ( 'latex'    => \&_latex_escape,
458                            'html'     => \&_html_escape_nbsp,#\&encode_entities,
459                            'template' => sub { shift },
460                          );
461   my $escape_function = $escape_functions{$format};
462   my $escape_function_nonbsp = ($format eq 'html')
463                                  ? \&_html_escape : $escape_function;
464
465   my %newline_tokens = (  'latex'     => '\\\\',
466                           'html'      => '<br>',
467                           'template'  => "\n",
468                         );
469   my $newline_token = $newline_tokens{$format};
470
471   warn "$me generating template variables\n"
472     if $DEBUG > 1;
473
474   # generate template variables
475   my $returnaddress;
476
477   if (
478          defined( $conf->config_orbase( "invoice_${format}returnaddress",
479                                         $template
480                                       )
481                 )
482        && length( $conf->config_orbase( "invoice_${format}returnaddress",
483                                         $template
484                                       )
485                 )
486   ) {
487
488     $returnaddress = join("\n",
489       $conf->config_orbase("invoice_${format}returnaddress", $template)
490     );
491
492   } elsif ( grep /\S/,
493             $conf->config_orbase('invoice_latexreturnaddress', $template) ) {
494
495     my $convert_map = $convert_maps{$format}{'returnaddress'};
496     $returnaddress =
497       join( "\n",
498             &$convert_map( $conf->config_orbase( "invoice_latexreturnaddress",
499                                                  $template
500                                                )
501                          )
502           );
503   } elsif ( grep /\S/, $conf->config('company_address', $cust_main->agentnum) ) {
504
505     my $convert_map = $convert_maps{$format}{'returnaddress'};
506     $returnaddress = join( "\n", &$convert_map(
507                                    map { s/( {2,})/'~' x length($1)/eg;
508                                          s/$/\\\\\*/;
509                                          $_
510                                        }
511                                      ( $conf->config('company_name', $cust_main->agentnum),
512                                        $conf->config('company_address', $cust_main->agentnum),
513                                      )
514                                  )
515                      );
516
517   } else {
518
519     my $warning = "Couldn't find a return address; ".
520                   "do you need to set the company_address configuration value?";
521     warn "$warning\n";
522     $returnaddress = $nbsp;
523     #$returnaddress = $warning;
524
525   }
526
527   warn "$me generating invoice data\n"
528     if $DEBUG > 1;
529
530   my $agentnum = $cust_main->agentnum;
531
532   my %invoice_data = (
533
534     #invoice from info
535     'company_name'    => scalar( $conf->config('company_name', $agentnum) ),
536     'company_address' => join("\n", $conf->config('company_address', $agentnum) ). "\n",
537     'company_phonenum'=> scalar( $conf->config('company_phonenum', $agentnum) ),
538     'returnaddress'   => $returnaddress,
539     'agent'           => &$escape_function($cust_main->agent->agent),
540
541     #invoice/quotation info
542     'no_number'       => $params{'no_number'},
543     'invnum'          => ( $params{'no_number'} ? '' : $self->invnum ),
544     'quotationnum'    => $self->quotationnum,
545     'no_date'         => $params{'no_date'},
546     '_date'           => ( $params{'no_date'} ? '' : $self->_date ),
547       # workaround for inconsistent behavior in the early plain text 
548       # templates; see RT#28271
549     'date'            => ( $params{'no_date'}
550                              ? ''
551                              : ($format eq 'template'
552                                ? $self->_date
553                                : $self->time2str_local('long', $self->_date, $format)
554                                )
555                          ),
556     'today'           => $self->time2str_local('long', $today, $format),
557     'terms'           => $self->terms,
558     'template'        => $template, #params{'template'},
559     'notice_name'     => $notice_name, # escape?
560     'current_charges' => sprintf("%.2f", $self->charged),
561     'duedate'         => $self->due_date2str('rdate'), #date_format?
562
563     #customer info
564     'custnum'         => $cust_main->display_custnum,
565     'prospectnum'     => $cust_main->prospectnum,
566     'agent_custid'    => &$escape_function($cust_main->agent_custid),
567     ( map { $_ => &$escape_function($cust_main->$_()) } qw(
568       payname company address1 address2 city state zip fax
569     )),
570
571     #global config
572     'ship_enable'     => $conf->exists('invoice-ship_address'),
573     'unitprices'      => $conf->exists('invoice-unitprice'),
574     'smallernotes'    => $conf->exists('invoice-smallernotes'),
575     'smallerfooter'   => $conf->exists('invoice-smallerfooter'),
576     'balance_due_below_line' => $conf->exists('balance_due_below_line'),
577    
578     #layout info -- would be fancy to calc some of this and bury the template
579     #               here in the code
580     'topmargin'             => scalar($conf->config('invoice_latextopmargin', $agentnum)),
581     'headsep'               => scalar($conf->config('invoice_latexheadsep', $agentnum)),
582     'textheight'            => scalar($conf->config('invoice_latextextheight', $agentnum)),
583     'extracouponspace'      => scalar($conf->config('invoice_latexextracouponspace', $agentnum)),
584     'couponfootsep'         => scalar($conf->config('invoice_latexcouponfootsep', $agentnum)),
585     'verticalreturnaddress' => $conf->exists('invoice_latexverticalreturnaddress', $agentnum),
586     'addresssep'            => scalar($conf->config('invoice_latexaddresssep', $agentnum)),
587     'amountenclosedsep'     => scalar($conf->config('invoice_latexcouponamountenclosedsep', $agentnum)),
588     'coupontoaddresssep'    => scalar($conf->config('invoice_latexcoupontoaddresssep', $agentnum)),
589     'addcompanytoaddress'   => $conf->exists('invoice_latexcouponaddcompanytoaddress', $agentnum),
590
591     # better hang on to conf_dir for a while (for old templates)
592     'conf_dir'        => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
593
594     #these are only used when doing paged plaintext
595     'page'            => 1,
596     'total_pages'     => 1,
597
598   );
599  
600   #localization
601   $invoice_data{'emt'} = sub { &$escape_function($self->mt(@_)) };
602   # prototype here to silence warnings
603   $invoice_data{'time2str'} = sub ($;$$) { $self->time2str_local(@_, $format) };
604
605   my $min_sdate = 999999999999;
606   my $max_edate = 0;
607   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
608     next unless $cust_bill_pkg->pkgnum > 0;
609     $min_sdate = $cust_bill_pkg->sdate
610       if length($cust_bill_pkg->sdate) && $cust_bill_pkg->sdate < $min_sdate;
611     $max_edate = $cust_bill_pkg->edate
612       if length($cust_bill_pkg->edate) && $cust_bill_pkg->edate > $max_edate;
613   }
614
615   $invoice_data{'bill_period'} = '';
616   $invoice_data{'bill_period'} =
617       $self->time2str_local('%e %h', $min_sdate, $format) 
618       . " to " .
619       $self->time2str_local('%e %h', $max_edate, $format)
620     if ($max_edate != 0 && $min_sdate != 999999999999);
621
622   $invoice_data{finance_section} = '';
623   if ( $conf->config('finance_pkgclass') ) {
624     my $pkg_class =
625       qsearchs('pkg_class', { classnum => $conf->config('finance_pkgclass') });
626     $invoice_data{finance_section} = $pkg_class->categoryname;
627   } 
628   $invoice_data{finance_amount} = '0.00';
629   $invoice_data{finance_section} ||= 'Finance Charges'; #avoid config confusion
630
631   my $countrydefault = $conf->config('countrydefault') || 'US';
632   foreach ( qw( address1 address2 city state zip country fax) ){
633     my $method = 'ship_'.$_;
634     $invoice_data{"ship_$_"} = $escape_function->($cust_main->$method);
635   }
636   if ( length($cust_main->ship_company) ) {
637     $invoice_data{'ship_company'} = $escape_function->($cust_main->ship_company);
638   } else {
639     $invoice_data{'ship_company'} = $escape_function->($cust_main->company);
640   }
641   $invoice_data{'ship_contact'} = $escape_function->($cust_main->contact);
642   $invoice_data{'ship_country'} = ''
643     if ( $invoice_data{'ship_country'} eq $countrydefault );
644   
645   $invoice_data{'cid'} = $params{'cid'}
646     if $params{'cid'};
647
648   if ( $cust_main->country eq $countrydefault ) {
649     $invoice_data{'country'} = '';
650   } else {
651     $invoice_data{'country'} = &$escape_function(code2country($cust_main->country));
652   }
653
654   my @address = ();
655   $invoice_data{'address'} = \@address;
656   push @address,
657     $cust_main->payname.
658       ( ( $cust_main->payby eq 'BILL' ) && $cust_main->payinfo
659         ? " (P.O. #". $cust_main->payinfo. ")"
660         : ''
661       )
662   ;
663   push @address, $cust_main->company
664     if $cust_main->company;
665   push @address, $cust_main->address1;
666   push @address, $cust_main->address2
667     if $cust_main->address2;
668   push @address,
669     $cust_main->city. ", ". $cust_main->state. "  ".  $cust_main->zip;
670   push @address, $invoice_data{'country'}
671     if $invoice_data{'country'};
672   push @address, ''
673     while (scalar(@address) < 5);
674
675   $invoice_data{'logo_file'} = $params{'logo_file'}
676     if $params{'logo_file'};
677   $invoice_data{'barcode_file'} = $params{'barcode_file'}
678     if $params{'barcode_file'};
679   $invoice_data{'barcode_img'} = $params{'barcode_img'}
680     if $params{'barcode_img'};
681   $invoice_data{'barcode_cid'} = $params{'barcode_cid'}
682     if $params{'barcode_cid'};
683
684   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
685 #  my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
686   #my $balance_due = $self->owed + $pr_total - $cr_total;
687   my $balance_due = $self->owed + $pr_total;
688
689   # the sum of amount owed on all invoices
690   # (this is used in the summary & on the payment coupon)
691   $invoice_data{'balance'} = sprintf("%.2f", $balance_due);
692
693   # info from customer's last invoice before this one, for some 
694   # summary formats
695   $invoice_data{'last_bill'} = {};
696
697   if ( $self->custnum && $self->invnum ) {
698
699     my $last_bill = $self->previous_bill;
700     if ( $last_bill ) {
701
702       # "balance_date_range" unfortunately is unsuitable for this, since it
703       # cares about application dates.  We want to know the sum of all 
704       # _top-level transactions_ dated before the last invoice.
705       my @sql = (
706         'SELECT SUM(charged) FROM cust_bill WHERE _date <= ? AND custnum = ?',
707         'SELECT -1*SUM(amount) FROM cust_credit WHERE _date <= ? AND custnum = ?',
708         'SELECT -1*SUM(paid) FROM cust_pay  WHERE _date <= ? AND custnum = ?',
709         'SELECT SUM(refund) FROM cust_refund WHERE _date <= ? AND custnum = ?',
710       );
711
712       # the customer's current balance immediately after generating the last 
713       # bill
714
715       my $last_bill_balance = $last_bill->charged;
716       foreach (@sql) {
717         #warn "$_\n";
718         my $delta = FS::Record->scalar_sql(
719           $_,
720           $last_bill->_date - 1,
721           $self->custnum,
722         );
723         #warn "$delta\n";
724         $last_bill_balance += $delta;
725       }
726
727       $last_bill_balance = sprintf("%.2f", $last_bill_balance);
728
729       warn sprintf("LAST BILL: INVNUM %d, DATE %s, BALANCE %.2f\n\n",
730         $last_bill->invnum,
731         $self->time2str_local('%D', $last_bill->_date),
732         $last_bill_balance
733       ) if $DEBUG > 0;
734       # ("true_previous_balance" is a terrible name, but at least it's no
735       # longer stored in the database)
736       $invoice_data{'true_previous_balance'} = $last_bill_balance;
737
738       # the change in balance from immediately after that invoice
739       # to immediately before this one
740       my $before_this_bill_balance = 0;
741       foreach (@sql) {
742         #warn "$_\n";
743         my $delta = FS::Record->scalar_sql(
744           $_,
745           $self->_date - 1,
746           $self->custnum,
747         );
748         #warn "$delta\n";
749         $before_this_bill_balance += $delta;
750       }
751       $invoice_data{'balance_adjustments'} =
752         sprintf("%.2f", $last_bill_balance - $before_this_bill_balance);
753
754       warn sprintf("BALANCE ADJUSTMENTS: %.2f\n\n",
755                    $invoice_data{'balance_adjustments'}
756       ) if $DEBUG > 0;
757
758       # the sum of amount owed on all previous invoices
759       # ($pr_total is used elsewhere but not as $previous_balance)
760       $invoice_data{'previous_balance'} = sprintf("%.2f", $pr_total);
761
762       $invoice_data{'last_bill'} = {
763         '_date'     => $last_bill->_date, #unformatted
764       };
765       my (@payments, @credits);
766       # for formats that itemize previous payments
767       foreach my $cust_pay ( qsearch('cust_pay', {
768                               'custnum' => $self->custnum,
769                               '_date'   => { op => '>=',
770                                              value => $last_bill->_date }
771                              } ) )
772       {
773         next if $cust_pay->_date > $self->_date;
774         push @payments, {
775             '_date'       => $cust_pay->_date,
776             'date'        => $self->time2str_local('long', $cust_pay->_date, $format),
777             'payinfo'     => $cust_pay->payby_payinfo_pretty,
778             'amount'      => sprintf('%.2f', $cust_pay->paid),
779         };
780         # not concerned about applications
781       }
782       foreach my $cust_credit ( qsearch('cust_credit', {
783                               'custnum' => $self->custnum,
784                               '_date'   => { op => '>=',
785                                              value => $last_bill->_date }
786                              } ) )
787       {
788         next if $cust_credit->_date > $self->_date;
789         push @credits, {
790             '_date'       => $cust_credit->_date,
791             'date'        => $self->time2str_local('long', $cust_credit->_date, $format),
792             'creditreason'=> $cust_credit->reason,
793             'amount'      => sprintf('%.2f', $cust_credit->amount),
794         };
795       }
796       $invoice_data{'previous_payments'} = \@payments;
797       $invoice_data{'previous_credits'}  = \@credits;
798     } else {
799       # there is no $last_bill
800       $invoice_data{'true_previous_balance'} =
801       $invoice_data{'balance_adjustments'}   =
802       $invoice_data{'previous_balance'}      = '0.00';
803       $invoice_data{'previous_payments'} = [];
804       $invoice_data{'previous_credits'} = [];
805     }
806   } # if this is an invoice
807
808   my $summarypage = '';
809   if ( $conf->exists('invoice_usesummary', $agentnum) ) {
810     $summarypage = 1;
811   }
812   $invoice_data{'summarypage'} = $summarypage;
813
814   warn "$me substituting variables in notes, footer, smallfooter\n"
815     if $DEBUG > 1;
816
817   my $tc = $self->template_conf;
818   my @include = ( [ $tc,        'notes' ],
819                   [ 'invoice_', 'footer' ],
820                   [ 'invoice_', 'smallfooter', ],
821                 );
822   push @include, [ $tc,        'coupon', ]
823     unless $params{'no_coupon'};
824
825   foreach my $i (@include) {
826
827     my($base, $include) = @$i;
828
829     my $inc_file = $conf->key_orbase("$base$format$include", $template);
830     my @inc_src;
831
832     if ( $conf->exists($inc_file, $agentnum)
833          && length( $conf->config($inc_file, $agentnum) ) ) {
834
835       @inc_src = $conf->config($inc_file, $agentnum);
836
837     } else {
838
839       $inc_file = $conf->key_orbase("${base}latex$include", $template);
840
841       my $convert_map = $convert_maps{$format}{$include};
842
843       @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
844                        s/--\@\]/$delimiters{$format}[1]/g;
845                        $_;
846                      } 
847                  &$convert_map( $conf->config($inc_file, $agentnum) );
848
849     }
850
851     my $inc_tt = new Text::Template (
852       TYPE       => 'ARRAY',
853       SOURCE     => [ map "$_\n", @inc_src ],
854       DELIMITERS => $delimiters{$format},
855     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
856
857     unless ( $inc_tt->compile() ) {
858       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
859       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
860       die $error;
861     }
862
863     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
864
865     $invoice_data{$include} =~ s/\n+$//
866       if ($format eq 'latex');
867   }
868
869   # let invoices use either of these as needed
870   $invoice_data{'po_num'} = ($cust_main->payby eq 'BILL') 
871     ? $cust_main->payinfo : '';
872   $invoice_data{'po_line'} = 
873     (  $cust_main->payby eq 'BILL' && $cust_main->payinfo )
874       ? &$escape_function($self->mt("Purchase Order #").$cust_main->payinfo)
875       : $nbsp;
876
877   my %money_chars = ( 'latex'    => '',
878                       'html'     => $conf->config('money_char') || '$',
879                       'template' => '',
880                     );
881   my $money_char = $money_chars{$format};
882
883   my %other_money_chars = ( 'latex'    => '\dollar ',#XXX should be a config too
884                             'html'     => $conf->config('money_char') || '$',
885                             'template' => '',
886                           );
887   my $other_money_char = $other_money_chars{$format};
888   $invoice_data{'dollar'} = $other_money_char;
889
890   my %minus_signs = ( 'latex'    => '$-$',
891                       'html'     => '&minus;',
892                       'template' => '- ' );
893   my $minus = $minus_signs{$format};
894
895   my @detail_items = ();
896   my @total_items = ();
897   my @buf = ();
898   my @sections = ();
899
900   $invoice_data{'detail_items'} = \@detail_items;
901   $invoice_data{'total_items'} = \@total_items;
902   $invoice_data{'buf'} = \@buf;
903   $invoice_data{'sections'} = \@sections;
904
905   warn "$me generating sections\n"
906     if $DEBUG > 1;
907
908   my $taxtotal = 0;
909   my $tax_section = { 'description' => $self->mt('Taxes, Surcharges, and Fees'),
910                       'subtotal'    => $taxtotal,   # adjusted below
911                       'tax_section' => 1,
912                     };
913   my $tax_weight = _pkg_category($tax_section->{description})
914                         ? _pkg_category($tax_section->{description})->weight
915                         : 0;
916   $tax_section->{'summarized'} = ''; #why? $summarypage && !$tax_weight ? 'Y' : '';
917   $tax_section->{'sort_weight'} = $tax_weight;
918
919   my $adjusttotal = 0;
920   my $adjust_section = {
921     'description'    => $self->mt('Credits, Payments, and Adjustments'),
922     'adjust_section' => 1,
923     'subtotal'       => 0,   # adjusted below
924   };
925   my $adjust_weight = _pkg_category($adjust_section->{description})
926                         ? _pkg_category($adjust_section->{description})->weight
927                         : 0;
928   $adjust_section->{'summarized'} = ''; #why? $summarypage && !$adjust_weight ? 'Y' : '';
929   $adjust_section->{'sort_weight'} = $adjust_weight;
930
931   my $unsquelched = $params{unsquelch_cdr} || $cust_main->squelch_cdr ne 'Y';
932   my $multisection = $conf->exists($tc.'sections', $cust_main->agentnum) ||
933                      $conf->exists($tc.'sections_by_location', $cust_main->agentnum);
934   $invoice_data{'multisection'} = $multisection;
935   my $late_sections;
936   my $extra_sections = [];
937   my $extra_lines = ();
938
939   # default section ('Charges')
940   my $default_section = { 'description' => '',
941                           'subtotal'    => '', 
942                           'no_subtotal' => 1,
943                         };
944
945   # Previous Charges section
946   # subtotal is the first return value from $self->previous
947   my $previous_section;
948   # if the invoice has major sections, or if we're summarizing previous 
949   # charges with a single line, or if we've been specifically told to put them
950   # in a section, create a section for previous charges:
951   if ( $multisection or
952        $conf->exists('previous_balance-summary_only') or
953        $conf->exists('previous_balance-section') ) {
954     
955     $previous_section =  { 'description' => $self->mt('Previous Charges'),
956                            'subtotal'    => $other_money_char.
957                                             sprintf('%.2f', $pr_total),
958                            'summarized'  => '', #why? $summarypage ? 'Y' : '',
959                          };
960     $previous_section->{posttotal} = '0 / 30 / 60 / 90 days overdue '. 
961       join(' / ', map { $cust_main->balance_date_range(@$_) }
962                   $self->_prior_month30s
963           )
964       if $conf->exists('invoice_include_aging');
965
966   } else {
967     # otherwise put them in the main section
968     $previous_section = $default_section;
969   }
970
971   if ( $multisection ) {
972     ($extra_sections, $extra_lines) =
973       $self->_items_extra_usage_sections($escape_function_nonbsp, $format)
974       if $conf->exists('usage_class_as_a_section', $cust_main->agentnum)
975       && $self->can('_items_extra_usage_sections');
976
977     push @$extra_sections, $adjust_section if $adjust_section->{sort_weight};
978
979     push @detail_items, @$extra_lines if $extra_lines;
980
981     # the code is written so that both methods can be used together, but
982     # we haven't yet changed the template to take advantage of that, so for 
983     # now, treat them as mutually exclusive.
984     my %section_method = ( by_category => 1 );
985     if ( $conf->config($tc.'sections_method') eq 'location' ) {
986       %section_method = ( by_location => 1 );
987     }
988     my ($early, $late) =
989       $self->_items_sections( 'summary' => $summarypage,
990                               'escape'  => $escape_function_nonbsp,
991                               'extra_sections' => $extra_sections,
992                               'format'  => $format,
993                               %section_method
994                             );
995     push @sections, @$early;
996     $late_sections = $late;
997
998     if (    $conf->exists('svc_phone_sections')
999          && $self->can('_items_svc_phone_sections')
1000        )
1001     {
1002       my ($phone_sections, $phone_lines) =
1003         $self->_items_svc_phone_sections($escape_function_nonbsp, $format);
1004       push @{$late_sections}, @$phone_sections;
1005       push @detail_items, @$phone_lines;
1006     }
1007     if ( $conf->exists('voip-cust_accountcode_cdr')
1008          && $cust_main->accountcode_cdr
1009          && $self->can('_items_accountcode_cdr')
1010        )
1011     {
1012       my ($accountcode_section, $accountcode_lines) =
1013         $self->_items_accountcode_cdr($escape_function_nonbsp,$format);
1014       if ( scalar(@$accountcode_lines) ) {
1015           push @{$late_sections}, $accountcode_section;
1016           push @detail_items, @$accountcode_lines;
1017       }
1018     }
1019   } else {# not multisection
1020     # make a default section
1021     push @sections, $default_section;
1022     # and calculate the finance charge total, since it won't get done otherwise.
1023     # and the default section total
1024     # XXX possibly finance_pkgclass should not be used in this manner?
1025     my @finance_charges;
1026     my @charges;
1027     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1028       if ( $invoice_data{finance_section} and 
1029         grep { $_->section eq $invoice_data{finance_section} }
1030            $cust_bill_pkg->cust_bill_pkg_display ) {
1031         # I think these are always setup fees, but just to be sure...
1032         push @finance_charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1033       } else {
1034         push @charges, $cust_bill_pkg->recur + $cust_bill_pkg->setup;
1035       }
1036     }
1037     $invoice_data{finance_amount} = 
1038       sprintf('%.2f', sum( @finance_charges ) || 0);
1039     $default_section->{subtotal} = $other_money_char.
1040                                     sprintf('%.2f', sum( @charges ) || 0);
1041   }
1042
1043   # start setting up summary subtotals
1044   my @summary_subtotals;
1045   my $method = $conf->config('summary_subtotals_method');
1046   if ( $method and $method ne $conf->config($tc.'sections_method') ) {
1047     # then re-section them by the correct method
1048     my %section_method = ( by_category => 1 );
1049     if ( $conf->config('summary_subtotals_method') eq 'location' ) {
1050       %section_method = ( by_location => 1 );
1051     }
1052     my ($early, $late) =
1053       $self->_items_sections( 'summary' => $summarypage,
1054                               'escape'  => $escape_function_nonbsp,
1055                               'extra_sections' => $extra_sections,
1056                               'format'  => $format,
1057                               %section_method
1058                             );
1059     foreach ( @$early ) {
1060       next if $_->{subtotal} == 0;
1061       $_->{subtotal} = $other_money_char.sprintf('%.2f', $_->{subtotal});
1062       push @summary_subtotals, $_;
1063     }
1064   } else {
1065     # subtotal sectioning is the same as for the actual invoice sections
1066     @summary_subtotals = @sections;
1067   }
1068
1069   # Hereafter, push sections to both @sections and @summary_subtotals
1070   # if they belong in both places (e.g. tax section).  Late sections are
1071   # never in @summary_subtotals.
1072
1073   # previous invoice balances in the Previous Charges section if there
1074   # is one, otherwise in the main detail section
1075   # (except if summary_only is enabled, don't show them at all)
1076   if ( $self->can('_items_previous') &&
1077        $self->enable_previous &&
1078        ! $conf->exists('previous_balance-summary_only') ) {
1079
1080     warn "$me adding previous balances\n"
1081       if $DEBUG > 1;
1082
1083     foreach my $line_item ( $self->_items_previous ) {
1084
1085       my $detail = {
1086         ref             => $line_item->{'pkgnum'},
1087         pkgpart         => $line_item->{'pkgpart'},
1088         #quantity        => 1, # not really correct
1089         section         => $previous_section, # which might be $default_section
1090         description     => &$escape_function($line_item->{'description'}),
1091         ext_description => [ map { &$escape_function($_) } 
1092                              @{ $line_item->{'ext_description'} || [] }
1093                            ],
1094         amount          => ( $old_latex ? '' : $money_char).
1095                             $line_item->{'amount'},
1096         product_code    => $line_item->{'pkgpart'} || 'N/A',
1097       };
1098
1099       push @detail_items, $detail;
1100       push @buf, [ $detail->{'description'},
1101                    $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1102                  ];
1103     }
1104
1105   }
1106
1107   if ( @pr_cust_bill && $self->enable_previous ) {
1108     push @buf, ['','-----------'];
1109     push @buf, [ $self->mt('Total Previous Balance'),
1110                  $money_char. sprintf("%10.2f", $pr_total) ];
1111     push @buf, ['',''];
1112   }
1113  
1114   if ( $conf->exists('svc_phone-did-summary') && $self->can('_did_summary') ) {
1115       warn "$me adding DID summary\n"
1116         if $DEBUG > 1;
1117
1118       my ($didsummary,$minutes) = $self->_did_summary;
1119       my $didsummary_desc = 'DID Activity Summary (since last invoice)';
1120       push @detail_items, 
1121        { 'description' => $didsummary_desc,
1122            'ext_description' => [ $didsummary, $minutes ],
1123        };
1124   }
1125
1126   foreach my $section (@sections, @$late_sections) {
1127
1128     # begin some normalization
1129     $section->{'subtotal'} = $section->{'amount'}
1130       if $multisection
1131          && !exists($section->{subtotal})
1132          && exists($section->{amount});
1133
1134     $invoice_data{finance_amount} = sprintf('%.2f', $section->{'subtotal'} )
1135       if ( $invoice_data{finance_section} &&
1136            $section->{'description'} eq $invoice_data{finance_section} );
1137
1138     $section->{'subtotal'} = $other_money_char.
1139                              sprintf('%.2f', $section->{'subtotal'})
1140       if $multisection;
1141
1142     # continue some normalization
1143     $section->{'amount'}   = $section->{'subtotal'}
1144       if $multisection;
1145
1146
1147     if ( $section->{'description'} ) {
1148       push @buf, ( [ &$escape_function($section->{'description'}), '' ],
1149                    [ '', '' ],
1150                  );
1151     }
1152
1153     warn "$me   setting options\n"
1154       if $DEBUG > 1;
1155
1156     my %options = ();
1157     $options{'section'} = $section if $multisection;
1158     $options{'format'} = $format;
1159     $options{'escape_function'} = $escape_function;
1160     $options{'no_usage'} = 1 unless $unsquelched;
1161     $options{'unsquelched'} = $unsquelched;
1162     $options{'summary_page'} = $summarypage;
1163     $options{'skip_usage'} =
1164       scalar(@$extra_sections) && !grep{$section == $_} @$extra_sections;
1165     $options{'preref_callback'} = $params{'preref_callback'};
1166
1167     warn "$me   searching for line items\n"
1168       if $DEBUG > 1;
1169
1170     foreach my $line_item ( $self->_items_pkg(%options),
1171                             $self->_items_fee(%options) ) {
1172
1173       warn "$me     adding line item ".
1174            join(', ', map "$_=>".$line_item->{$_}, keys %$line_item). "\n"
1175         if $DEBUG > 1;
1176
1177       $line_item->{'ref'} = $line_item->{'pkgnum'};
1178       $line_item->{'product_code'} = $line_item->{'pkgpart'} || 'N/A'; # mt()?
1179       $line_item->{'section'} = $section;
1180       $line_item->{'description'} = &$escape_function($line_item->{'description'});
1181       if (!$old_latex) { # dubious; templates should provide this
1182         $line_item->{'amount'} = $money_char.$line_item->{'amount'};
1183         $line_item->{'unit_amount'} = $money_char.$line_item->{'unit_amount'};
1184       }
1185       $line_item->{'ext_description'} ||= [];
1186  
1187       push @detail_items, $line_item;
1188       push @buf, ( [ $line_item->{'description'},
1189                      $money_char. sprintf("%10.2f", $line_item->{'amount'}),
1190                    ],
1191                    map { [ " ". $_, '' ] } @{$line_item->{'ext_description'}},
1192                  );
1193     }
1194
1195     if ( $section->{'description'} ) {
1196       push @buf, ( ['','-----------'],
1197                    [ $section->{'description'}. ' sub-total',
1198                       $section->{'subtotal'} # already formatted this 
1199                    ],
1200                    [ '', '' ],
1201                    [ '', '' ],
1202                  );
1203     }
1204   
1205   }
1206
1207   $invoice_data{current_less_finance} =
1208     sprintf('%.2f', $self->charged - $invoice_data{finance_amount} );
1209
1210   # if there's anything in the Previous Charges section, prepend it to the list
1211   if ( $pr_total and $previous_section ne $default_section ) {
1212     unshift @sections, $previous_section;
1213     # but not @summary_subtotals
1214   }
1215
1216   warn "$me adding taxes\n"
1217     if $DEBUG > 1;
1218
1219   my @items_tax = $self->_items_tax;
1220   foreach my $tax ( @items_tax ) {
1221
1222     $taxtotal += $tax->{'amount'};
1223
1224     my $description = &$escape_function( $tax->{'description'} );
1225     my $amount      = sprintf( '%.2f', $tax->{'amount'} );
1226
1227     if ( $multisection ) {
1228
1229       my $money = $old_latex ? '' : $money_char;
1230       push @detail_items, {
1231         ext_description => [],
1232         ref          => '',
1233         quantity     => '',
1234         description  => $description,
1235         amount       => $money. $amount,
1236         product_code => '',
1237         section      => $tax_section,
1238       };
1239
1240     } else {
1241
1242       push @total_items, {
1243         'total_item'   => $description,
1244         'total_amount' => $other_money_char. $amount,
1245       };
1246
1247     }
1248
1249     push @buf,[ $description,
1250                 $money_char. $amount,
1251               ];
1252
1253   }
1254   
1255   if ( @items_tax ) {
1256     my $total = {};
1257     $total->{'total_item'} = $self->mt('Sub-total');
1258     $total->{'total_amount'} =
1259       $other_money_char. sprintf('%.2f', $self->charged - $taxtotal );
1260
1261     if ( $multisection ) {
1262       $tax_section->{'subtotal'} = $other_money_char.
1263                                    sprintf('%.2f', $taxtotal);
1264       $tax_section->{'pretotal'} = 'New charges sub-total '.
1265                                    $total->{'total_amount'};
1266       if ( $taxtotal ) {
1267         push @sections, $tax_section;
1268         push @summary_subtotals, $tax_section;
1269       }
1270     } else {
1271       unshift @total_items, $total;
1272     }
1273   }
1274   $invoice_data{'taxtotal'} = sprintf('%.2f', $taxtotal);
1275
1276   push @buf,['','-----------'];
1277   push @buf,[$self->mt( 
1278               (!$self->enable_previous)
1279                ? 'Total Charges'
1280                : 'Total New Charges'
1281              ),
1282              $money_char. sprintf("%10.2f",$self->charged) ];
1283   push @buf,['',''];
1284
1285
1286   ###
1287   # Totals
1288   ###
1289
1290   my %embolden_functions = (
1291     'latex'    => sub { return '\textbf{'. shift(). '}' },
1292     'html'     => sub { return '<b>'. shift(). '</b>' },
1293     'template' => sub { shift },
1294   );
1295   my $embolden_function = $embolden_functions{$format};
1296
1297   if ( $self->can('_items_total') ) { # quotations
1298
1299     $self->_items_total(\@total_items);
1300
1301     foreach ( @total_items ) {
1302       $_->{'total_item'}   = &$embolden_function( $_->{'total_item'} );
1303       $_->{'total_amount'} = &$embolden_function( $other_money_char.
1304                                                    $_->{'total_amount'}
1305                                                 );
1306     }
1307
1308   } else { #normal invoice case
1309
1310     # calculate total, possibly including total owed on previous
1311     # invoices
1312     my $total = {};
1313     my $item = 'Total';
1314     $item = $conf->config('previous_balance-exclude_from_total')
1315          || 'Total New Charges'
1316       if $conf->exists('previous_balance-exclude_from_total');
1317     my $amount = $self->charged;
1318     if ( $self->enable_previous and !$conf->exists('previous_balance-exclude_from_total') ) {
1319       $amount += $pr_total;
1320     }
1321
1322     $total->{'total_item'} = &$embolden_function($self->mt($item));
1323     $total->{'total_amount'} =
1324       &$embolden_function( $other_money_char.  sprintf( '%.2f', $amount ) );
1325     if ( $multisection ) {
1326       if ( $adjust_section->{'sort_weight'} ) {
1327         $adjust_section->{'posttotal'} = $self->mt('Balance Forward').' '.
1328           $other_money_char.  sprintf("%.2f", ($self->billing_balance || 0) );
1329       } else {
1330         $adjust_section->{'pretotal'} = $self->mt('New charges total').' '.
1331           $other_money_char.  sprintf('%.2f', $self->charged );
1332       } 
1333     } else {
1334       push @total_items, $total;
1335     }
1336     push @buf,['','-----------'];
1337     push @buf,[$item,
1338                $money_char.
1339                sprintf( '%10.2f', $amount )
1340               ];
1341     push @buf,['',''];
1342
1343     # if we're showing previous invoices, also show previous
1344     # credits and payments 
1345     if ( $self->enable_previous 
1346           and $self->can('_items_credits')
1347           and $self->can('_items_payments') )
1348       {
1349       #foreach my $thing ( sort { $a->_date <=> $b->_date } $self->_items_credits, $self->_items_payments
1350     
1351       # credits
1352       my $credittotal = 0;
1353       foreach my $credit (
1354         $self->_items_credits( 'template' => $template, 'trim_len' => 60 )
1355       ) {
1356
1357         my $total;
1358         $total->{'total_item'} = &$escape_function($credit->{'description'});
1359         $credittotal += $credit->{'amount'};
1360         $total->{'total_amount'} = $minus.$other_money_char.$credit->{'amount'};
1361         $adjusttotal += $credit->{'amount'};
1362         if ( $multisection ) {
1363           my $money = $old_latex ? '' : $money_char;
1364           push @detail_items, {
1365             ext_description => [],
1366             ref          => '',
1367             quantity     => '',
1368             description  => &$escape_function($credit->{'description'}),
1369             amount       => $money. $credit->{'amount'},
1370             product_code => '',
1371             section      => $adjust_section,
1372           };
1373         } else {
1374           push @total_items, $total;
1375         }
1376
1377       }
1378       $invoice_data{'credittotal'} = sprintf('%.2f', $credittotal);
1379
1380       #credits (again)
1381       foreach my $credit (
1382         $self->_items_credits( 'template' => $template, 'trim_len'=>32 )
1383       ) {
1384         push @buf, [ $credit->{'description'}, $money_char.$credit->{'amount'} ];
1385       }
1386
1387       # payments
1388       my $paymenttotal = 0;
1389       foreach my $payment (
1390         $self->_items_payments( 'template' => $template )
1391       ) {
1392         my $total = {};
1393         $total->{'total_item'} = &$escape_function($payment->{'description'});
1394         $paymenttotal += $payment->{'amount'};
1395         $total->{'total_amount'} = $minus.$other_money_char.$payment->{'amount'};
1396         $adjusttotal += $payment->{'amount'};
1397         if ( $multisection ) {
1398           my $money = $old_latex ? '' : $money_char;
1399           push @detail_items, {
1400             ext_description => [],
1401             ref          => '',
1402             quantity     => '',
1403             description  => &$escape_function($payment->{'description'}),
1404             amount       => $money. $payment->{'amount'},
1405             product_code => '',
1406             section      => $adjust_section,
1407           };
1408         }else{
1409           push @total_items, $total;
1410         }
1411         push @buf, [ $payment->{'description'},
1412                      $money_char. sprintf("%10.2f", $payment->{'amount'}),
1413                    ];
1414       }
1415       $invoice_data{'paymenttotal'} = sprintf('%.2f', $paymenttotal);
1416     
1417       if ( $multisection ) {
1418         $adjust_section->{'subtotal'} = $other_money_char.
1419                                         sprintf('%.2f', $adjusttotal);
1420         push @sections, $adjust_section
1421           unless $adjust_section->{sort_weight};
1422         # do not summarize; adjustments there are shown according to 
1423         # different rules
1424       }
1425
1426       # create Balance Due message
1427       { 
1428         my $total;
1429         $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1430         $total->{'total_amount'} =
1431           &$embolden_function(
1432             $other_money_char. sprintf('%.2f', #why? $summarypage 
1433                                                #  ? $self->charged +
1434                                                #    $self->billing_balance
1435                                                #  :
1436                                                    $self->owed + $pr_total
1437                                       )
1438           );
1439         if ( $multisection && !$adjust_section->{sort_weight} ) {
1440           $adjust_section->{'posttotal'} = $total->{'total_item'}. ' '.
1441                                            $total->{'total_amount'};
1442         }else{
1443           push @total_items, $total;
1444         }
1445         push @buf,['','-----------'];
1446         push @buf,[$self->balance_due_msg, $money_char. 
1447           sprintf("%10.2f", $balance_due ) ];
1448       }
1449
1450       if ( $conf->exists('previous_balance-show_credit')
1451           and $cust_main->balance < 0 ) {
1452         my $credit_total = {
1453           'total_item'    => &$embolden_function($self->credit_balance_msg),
1454           'total_amount'  => &$embolden_function(
1455             $other_money_char. sprintf('%.2f', -$cust_main->balance)
1456           ),
1457         };
1458         if ( $multisection ) {
1459           $adjust_section->{'posttotal'} .= $newline_token .
1460             $credit_total->{'total_item'} . ' ' . $credit_total->{'total_amount'};
1461         }
1462         else {
1463           push @total_items, $credit_total;
1464         }
1465         push @buf,['','-----------'];
1466         push @buf,[$self->credit_balance_msg, $money_char. 
1467           sprintf("%10.2f", -$cust_main->balance ) ];
1468       }
1469     }
1470
1471   } #end of default total adding ! can('_items_total')
1472
1473   if ( $multisection ) {
1474     if (    $conf->exists('svc_phone_sections')
1475          && $self->can('_items_svc_phone_sections')
1476        )
1477     {
1478       my $total;
1479       $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
1480       $total->{'total_amount'} =
1481         &$embolden_function(
1482           $other_money_char. sprintf('%.2f', $self->owed + $pr_total)
1483         );
1484       my $last_section = pop @sections;
1485       $last_section->{'posttotal'} = $total->{'total_item'}. ' '.
1486                                      $total->{'total_amount'};
1487       push @sections, $last_section;
1488     }
1489     push @sections, @$late_sections
1490       if $unsquelched;
1491   }
1492
1493   # make a discounts-available section, even without multisection
1494   if ( $conf->exists('discount-show_available') 
1495        and my @discounts_avail = $self->_items_discounts_avail ) {
1496     my $discount_section = {
1497       'description' => $self->mt('Discounts Available'),
1498       'subtotal'    => '',
1499       'no_subtotal' => 1,
1500     };
1501
1502     push @sections, $discount_section; # do not summarize
1503     push @detail_items, map { +{
1504         'ref'         => '', #should this be something else?
1505         'section'     => $discount_section,
1506         'description' => &$escape_function( $_->{description} ),
1507         'amount'      => $money_char . &$escape_function( $_->{amount} ),
1508         'ext_description' => [ &$escape_function($_->{ext_description}) || () ],
1509     } } @discounts_avail;
1510   }
1511
1512   # not adding any more sections after this
1513   $invoice_data{summary_subtotals} = \@summary_subtotals;
1514
1515   # usage subtotals
1516   if ( $conf->exists('usage_class_summary')
1517        and $self->can('_items_usage_class_summary') ) {
1518     my @usage_subtotals = $self->_items_usage_class_summary(escape => $escape_function);
1519     if ( @usage_subtotals ) {
1520       unshift @sections, $usage_subtotals[0]->{section}; # do not summarize
1521       unshift @detail_items, @usage_subtotals;
1522     }
1523   }
1524
1525   # invoice history "section" (not really a section)
1526   # not to be included in any subtotals, completely independent of 
1527   # everything...
1528   if ( $conf->exists('previous_invoice_history') ) {
1529     my %history;
1530     my %monthorder;
1531     foreach my $cust_bill ( $cust_main->cust_bill ) {
1532       # XXX hardcoded format, and currently only 'charged'; add other fields
1533       # if they become necessary
1534       my $date = $self->time2str_local('%b %Y', $cust_bill->_date);
1535       $history{$date} ||= 0;
1536       $history{$date} += $cust_bill->charged;
1537       # just so we have a numeric sort key
1538       $monthorder{$date} ||= $cust_bill->_date;
1539     }
1540     my @sorted_months = sort { $monthorder{$a} <=> $monthorder{$b} }
1541                         keys %history;
1542     my @sorted_amounts = map { sprintf('%.2f', $history{$_}) } @sorted_months;
1543     $invoice_data{monthly_history} = [ \@sorted_months, \@sorted_amounts ];
1544   }
1545
1546   # service locations: another option for template customization
1547   my %location_info;
1548   foreach my $item (@detail_items) {
1549     if ( $item->{locationnum} ) {
1550       $location_info{ $item->{locationnum} } ||= {
1551         FS::cust_location->by_key( $item->{locationnum} )->location_hash
1552       };
1553     }
1554   }
1555   $invoice_data{location_info} = \%location_info;
1556
1557   # debugging hook: call this with 'diag' => 1 to just get a hash of 
1558   # the invoice variables
1559   return \%invoice_data if ( $params{'diag'} );
1560
1561   # All sections and items are built; now fill in templates.
1562   my @includelist = ();
1563   push @includelist, 'summary' if $summarypage;
1564   foreach my $include ( @includelist ) {
1565
1566     my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
1567     my @inc_src;
1568
1569     if ( length( $conf->config($inc_file, $agentnum) ) ) {
1570
1571       @inc_src = $conf->config($inc_file, $agentnum);
1572
1573     } else {
1574
1575       $inc_file = $conf->key_orbase("invoice_latex$include", $template);
1576
1577       my $convert_map = $convert_maps{$format}{$include};
1578
1579       @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
1580                        s/--\@\]/$delimiters{$format}[1]/g;
1581                        $_;
1582                      } 
1583                  &$convert_map( $conf->config($inc_file, $agentnum) );
1584
1585     }
1586
1587     my $inc_tt = new Text::Template (
1588       TYPE       => 'ARRAY',
1589       SOURCE     => [ map "$_\n", @inc_src ],
1590       DELIMITERS => $delimiters{$format},
1591     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
1592
1593     unless ( $inc_tt->compile() ) {
1594       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
1595       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
1596       die $error;
1597     }
1598
1599     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
1600
1601     $invoice_data{$include} =~ s/\n+$//
1602       if ($format eq 'latex');
1603   }
1604
1605   $invoice_lines = 0;
1606   my $wasfunc = 0;
1607   foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
1608     /invoice_lines\((\d*)\)/;
1609     $invoice_lines += $1 || scalar(@buf);
1610     $wasfunc=1;
1611   }
1612   die "no invoice_lines() functions in template?"
1613     if ( $format eq 'template' && !$wasfunc );
1614
1615   if ($format eq 'template') {
1616
1617     if ( $invoice_lines ) {
1618       $invoice_data{'total_pages'} = int( scalar(@buf) / $invoice_lines );
1619       $invoice_data{'total_pages'}++
1620         if scalar(@buf) % $invoice_lines;
1621     }
1622
1623     #setup subroutine for the template
1624     $invoice_data{invoice_lines} = sub {
1625       my $lines = shift || scalar(@buf);
1626       map { 
1627         scalar(@buf)
1628           ? shift @buf
1629           : [ '', '' ];
1630       }
1631       ( 1 .. $lines );
1632     };
1633
1634     my $lines;
1635     my @collect;
1636     while (@buf) {
1637       push @collect, split("\n",
1638         $text_template->fill_in( HASH => \%invoice_data )
1639       );
1640       $invoice_data{'page'}++;
1641     }
1642     map "$_\n", @collect;
1643
1644   } else { # this is where we actually create the invoice
1645
1646     warn "filling in template for invoice ". $self->invnum. "\n"
1647       if $DEBUG;
1648     warn join("\n", map " $_ => ". $invoice_data{$_}, keys %invoice_data). "\n"
1649       if $DEBUG > 1;
1650
1651     $text_template->fill_in(HASH => \%invoice_data);
1652   }
1653 }
1654
1655 sub notice_name { '('.shift->table.')'; }
1656
1657 sub template_conf { 'invoice_'; }
1658
1659 # helper routine for generating date ranges
1660 sub _prior_month30s {
1661   my $self = shift;
1662   my @ranges = (
1663    [ 1,       2592000 ], # 0-30 days ago
1664    [ 2592000, 5184000 ], # 30-60 days ago
1665    [ 5184000, 7776000 ], # 60-90 days ago
1666    [ 7776000, 0       ], # 90+   days ago
1667   );
1668
1669   map { [ $_->[0] ? $self->_date - $_->[0] - 1 : '',
1670           $_->[1] ? $self->_date - $_->[1] - 1 : '',
1671       ] }
1672   @ranges;
1673 }
1674
1675 =item print_ps HASHREF | [ TIME [ , TEMPLATE ] ]
1676
1677 Returns an postscript invoice, as a scalar.
1678
1679 Options can be passed as a hashref (recommended) or as a list of time, template
1680 and then any key/value pairs for any other options.
1681
1682 I<time> an optional value used to control the printing of overdue messages.  The
1683 default is now.  It isn't the date of the invoice; that's the `_date' field.
1684 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1685 L<Time::Local> and L<Date::Parse> for conversion functions.
1686
1687 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1688
1689 =cut
1690
1691 sub print_ps {
1692   my $self = shift;
1693
1694   my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1695   my $ps = generate_ps($file);
1696   unlink($logofile);
1697   unlink($barcodefile) if $barcodefile;
1698
1699   $ps;
1700 }
1701
1702 =item print_pdf HASHREF | [ TIME [ , TEMPLATE ] ]
1703
1704 Returns an PDF invoice, as a scalar.
1705
1706 Options can be passed as a hashref (recommended) or as a list of time, template
1707 and then any key/value pairs for any other options.
1708
1709 I<time> an optional value used to control the printing of overdue messages.  The
1710 default is now.  It isn't the date of the invoice; that's the `_date' field.
1711 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1712 L<Time::Local> and L<Date::Parse> for conversion functions.
1713
1714 I<template>, if specified, is the name of a suffix for alternate invoices.
1715
1716 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1717
1718 =cut
1719
1720 sub print_pdf {
1721   my $self = shift;
1722
1723   my ($file, $logofile, $barcodefile) = $self->print_latex(@_);
1724   my $pdf = generate_pdf($file);
1725   unlink($logofile);
1726   unlink($barcodefile) if $barcodefile;
1727
1728   $pdf;
1729 }
1730
1731 =item print_html HASHREF | [ TIME [ , TEMPLATE [ , CID ] ] ]
1732
1733 Returns an HTML invoice, as a scalar.
1734
1735 I<time> an optional value used to control the printing of overdue messages.  The
1736 default is now.  It isn't the date of the invoice; that's the `_date' field.
1737 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1738 L<Time::Local> and L<Date::Parse> for conversion functions.
1739
1740 I<template>, if specified, is the name of a suffix for alternate invoices.
1741
1742 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1743
1744 I<cid> is a MIME Content-ID used to create a "cid:" URL for the logo image, used
1745 when emailing the invoice as part of a multipart/related MIME email.
1746
1747 =cut
1748
1749 sub print_html {
1750   my $self = shift;
1751   my %params;
1752   if ( ref($_[0]) ) {
1753     %params = %{ shift() }; 
1754   } else {
1755     %params = @_;
1756   }
1757   $params{'format'} = 'html';
1758   
1759   $self->print_generic( %params );
1760 }
1761
1762 # quick subroutine for print_latex
1763 #
1764 # There are ten characters that LaTeX treats as special characters, which
1765 # means that they do not simply typeset themselves: 
1766 #      # $ % & ~ _ ^ \ { }
1767 #
1768 # TeX ignores blanks following an escaped character; if you want a blank (as
1769 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ..."). 
1770
1771 sub _latex_escape {
1772   my $value = shift;
1773   $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
1774   $value =~ s/([<>])/\$$1\$/g;
1775   $value;
1776 }
1777
1778 sub _html_escape {
1779   my $value = shift;
1780   encode_entities($value);
1781   $value;
1782 }
1783
1784 sub _html_escape_nbsp {
1785   my $value = _html_escape(shift);
1786   $value =~ s/ +/&nbsp;/g;
1787   $value;
1788 }
1789
1790 #utility methods for print_*
1791
1792 sub _translate_old_latex_format {
1793   warn "_translate_old_latex_format called\n"
1794     if $DEBUG; 
1795
1796   my @template = ();
1797   while ( @_ ) {
1798     my $line = shift;
1799   
1800     if ( $line =~ /^%%Detail\s*$/ ) {
1801   
1802       push @template, q![@--!,
1803                       q!  foreach my $_tr_line (@detail_items) {!,
1804                       q!    if ( scalar ($_tr_item->{'ext_description'} ) ) {!,
1805                       q!      $_tr_line->{'description'} .= !, 
1806                       q!        "\\tabularnewline\n~~".!,
1807                       q!        join( "\\tabularnewline\n~~",!,
1808                       q!          @{$_tr_line->{'ext_description'}}!,
1809                       q!        );!,
1810                       q!    }!;
1811
1812       while ( ( my $line_item_line = shift )
1813               !~ /^%%EndDetail\s*$/                            ) {
1814         $line_item_line =~ s/'/\\'/g;    # nice LTS
1815         $line_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
1816         $line_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1817         push @template, "    \$OUT .= '$line_item_line';";
1818       }
1819
1820       push @template, '}',
1821                       '--@]';
1822       #' doh, gvim
1823     } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
1824
1825       push @template, '[@--',
1826                       '  foreach my $_tr_line (@total_items) {';
1827
1828       while ( ( my $total_item_line = shift )
1829               !~ /^%%EndTotalDetails\s*$/                      ) {
1830         $total_item_line =~ s/'/\\'/g;    # nice LTS
1831         $total_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
1832         $total_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
1833         push @template, "    \$OUT .= '$total_item_line';";
1834       }
1835
1836       push @template, '}',
1837                       '--@]';
1838
1839     } else {
1840       $line =~ s/\$(\w+)/[\@-- \$$1 --\@]/g;
1841       push @template, $line;  
1842     }
1843   
1844   }
1845
1846   if ($DEBUG) {
1847     warn "$_\n" foreach @template;
1848   }
1849
1850   (@template);
1851 }
1852
1853 sub terms {
1854   my $self = shift;
1855   my $conf = $self->conf;
1856
1857   #check for an invoice-specific override
1858   return $self->invoice_terms if $self->invoice_terms;
1859   
1860   #check for a customer- specific override
1861   my $cust_main = $self->cust_main;
1862   return $cust_main->invoice_terms if $cust_main && $cust_main->invoice_terms;
1863
1864   #use configured default
1865   $conf->config('invoice_default_terms') || '';
1866 }
1867
1868 sub due_date {
1869   my $self = shift;
1870   my $duedate = '';
1871   if ( $self->terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
1872     $duedate = $self->_date() + ( $1 * 86400 );
1873   }
1874   $duedate;
1875 }
1876
1877 sub due_date2str {
1878   my $self = shift;
1879   $self->due_date ? $self->time2str_local(shift, $self->due_date) : '';
1880 }
1881
1882 sub balance_due_msg {
1883   my $self = shift;
1884   my $msg = $self->mt('Balance Due');
1885   return $msg unless $self->terms;
1886   if ( $self->due_date ) {
1887     $msg .= ' - ' . $self->mt('Please pay by'). ' '.
1888       $self->due_date2str('short');
1889   } elsif ( $self->terms ) {
1890     $msg .= ' - '. $self->terms;
1891   }
1892   $msg;
1893 }
1894
1895 sub balance_due_date {
1896   my $self = shift;
1897   my $conf = $self->conf;
1898   my $duedate = '';
1899   if (    $conf->exists('invoice_default_terms') 
1900        && $conf->config('invoice_default_terms')=~ /^\s*Net\s*(\d+)\s*$/ ) {
1901     $duedate = $self->time2str_local('rdate', $self->_date + ($1*86400) );
1902   }
1903   $duedate;
1904 }
1905
1906 sub credit_balance_msg { 
1907   my $self = shift;
1908   $self->mt('Credit Balance Remaining')
1909 }
1910
1911 =item _date_pretty
1912
1913 Returns a string with the date, for example: "3/20/2008", localized for the
1914 customer.  Use _date_pretty_unlocalized for non-end-customer display use.
1915
1916 =cut
1917
1918 sub _date_pretty {
1919   my $self = shift;
1920   $self->time2str_local('short', $self->_date);
1921 }
1922
1923 =item _date_pretty_unlocalized
1924
1925 Returns a string with the date, for example: "3/20/2008", in the format
1926 configured for the back-office.  Use _date_pretty for end-customer display use.
1927
1928 =cut
1929
1930 sub _date_pretty_unlocalized {
1931   my $self = shift;
1932   time2str($date_format, $self->_date);
1933 }
1934
1935 =item _items_sections OPTIONS
1936
1937 Generate section information for all items appearing on this invoice.
1938 This will only be called for multi-section invoices.
1939
1940 For each line item (L<FS::cust_bill_pkg> record), this will fetch all 
1941 related display records (L<FS::cust_bill_pkg_display>) and organize 
1942 them into two groups ("early" and "late" according to whether they come 
1943 before or after the total), then into sections.  A subtotal is calculated 
1944 for each section.
1945
1946 Section descriptions are returned in sort weight order.  Each consists 
1947 of a hash containing:
1948
1949 description: the package category name, escaped
1950 subtotal: the total charges in that section
1951 tax_section: a flag indicating that the section contains only tax charges
1952 summarized: same as tax_section, for some reason
1953 sort_weight: the package category's sort weight
1954
1955 If 'condense' is set on the display record, it also contains everything 
1956 returned from C<_condense_section()>, i.e. C<_condensed_foo_generator>
1957 coderefs to generate parts of the invoice.  This is not advised.
1958
1959 The method returns two arrayrefs, one of "early" sections and one of "late"
1960 sections.
1961
1962 OPTIONS may include:
1963
1964 by_location: a flag to divide the invoice into sections by location.  
1965 Each section hash will have a 'location' element containing a hashref of 
1966 the location fields (see L<FS::cust_location>).  The section description
1967 will be the location label, but the template can use any of the location 
1968 fields to create a suitable label.
1969
1970 by_category: a flag to divide the invoice into sections using display 
1971 records (see L<FS::cust_bill_pkg_display>).  This is the "traditional" 
1972 behavior.  Each section hash will have a 'category' element containing
1973 the section name from the display record (which probably equals the 
1974 category name of the package, but may not in some cases).
1975
1976 summary: a flag indicating that this is a summary-format invoice.
1977 Turning this on has the following effects:
1978 - Ignores display items with the 'summary' flag.
1979 - Places all sections in the "early" group even if they have post_total.
1980 - Creates sections for all non-disabled package categories, even if they 
1981 have no charges on this invoice, as well as a section with no name.
1982
1983 escape: an escape function to use for section titles.
1984
1985 extra_sections: an arrayref of additional sections to return after the 
1986 sorted list.  If there are any of these, section subtotals exclude 
1987 usage charges.
1988
1989 format: 'latex', 'html', or 'template' (i.e. text).  Not used, but 
1990 passed through to C<_condense_section()>.
1991
1992 =cut
1993
1994 use vars qw(%pkg_category_cache);
1995 sub _items_sections {
1996   my $self = shift;
1997   my %opt = @_;
1998   
1999   my $escape = $opt{escape};
2000   my @extra_sections = @{ $opt{extra_sections} || [] };
2001
2002   # $subtotal{$locationnum}{$categoryname} = amount.
2003   # if we're not using by_location, $locationnum is undef.
2004   # if we're not using by_category, you guessed it, $categoryname is undef.
2005   # if we're not using either one, we shouldn't be here in the first place...
2006   my %subtotal = ();
2007   my %late_subtotal = ();
2008   my %not_tax = ();
2009
2010   # About tax items + multisection invoices:
2011   # If either invoice_*summary option is enabled, AND there is a 
2012   # package category with the name of the tax, then there will be 
2013   # a display record assigning the tax item to that category.
2014   #
2015   # However, the taxes are always placed in the "Taxes, Surcharges,
2016   # and Fees" section regardless of that.  The only effect of the 
2017   # display record is to create a subtotal for the summary page.
2018
2019   # cache these
2020   my $pkg_hash = $self->cust_pkg_hash;
2021
2022   foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2023   {
2024
2025       my $usage = $cust_bill_pkg->usage;
2026
2027       my $locationnum;
2028       if ( $opt{by_location} ) {
2029         if ( $cust_bill_pkg->pkgnum ) {
2030           $locationnum = $pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum;
2031         } else {
2032           $locationnum = '';
2033         }
2034       } else {
2035         $locationnum = undef;
2036       }
2037
2038       # as in _items_cust_pkg, if a line item has no display records,
2039       # cust_bill_pkg_display() returns a default record for it
2040
2041       foreach my $display ($cust_bill_pkg->cust_bill_pkg_display) {
2042         next if ( $display->summary && $opt{summary} );
2043
2044         my $section = $display->section;
2045         my $type    = $display->type;
2046         # Set $section = undef if we're sectioning by location and this
2047         # line item _has_ a location (i.e. isn't a fee).
2048         $section = undef if $locationnum;
2049
2050         # set this flag if the section is not tax-only
2051         $not_tax{$locationnum}{$section} = 1
2052           if $cust_bill_pkg->pkgnum  or $cust_bill_pkg->feepart;
2053
2054         # there's actually a very important piece of logic buried in here:
2055         # incrementing $late_subtotal{$section} CREATES 
2056         # $late_subtotal{$section}.  keys(%late_subtotal) is later used 
2057         # to define the list of late sections, and likewise keys(%subtotal).
2058         # When _items_cust_bill_pkg is called to generate line items for 
2059         # real, it will be called with 'section' => $section for each 
2060         # of these.
2061         if ( $display->post_total && !$opt{summary} ) {
2062           if (! $type || $type eq 'S') {
2063             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2064               if $cust_bill_pkg->setup != 0
2065               || $cust_bill_pkg->setup_show_zero;
2066           }
2067
2068           if (! $type) {
2069             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur
2070               if $cust_bill_pkg->recur != 0
2071               || $cust_bill_pkg->recur_show_zero;
2072           }
2073
2074           if ($type && $type eq 'R') {
2075             $late_subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2076               if $cust_bill_pkg->recur != 0
2077               || $cust_bill_pkg->recur_show_zero;
2078           }
2079           
2080           if ($type && $type eq 'U') {
2081             $late_subtotal{$locationnum}{$section} += $usage
2082               unless scalar(@extra_sections);
2083           }
2084
2085         } else { # it's a pre-total (normal) section
2086
2087           # skip tax items unless they're explicitly included in a section
2088           next if $cust_bill_pkg->pkgnum == 0 and
2089                   ! $cust_bill_pkg->feepart   and
2090                   ! $section;
2091
2092           if ( $type eq 'S' ) {
2093             $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2094               if $cust_bill_pkg->setup != 0
2095               || $cust_bill_pkg->setup_show_zero;
2096           } elsif ( $type eq 'R' ) {
2097             $subtotal{$locationnum}{$section} += $cust_bill_pkg->recur - $usage
2098               if $cust_bill_pkg->recur != 0
2099               || $cust_bill_pkg->recur_show_zero;
2100           } elsif ( $type eq 'U' ) {
2101             $subtotal{$locationnum}{$section} += $usage
2102               unless scalar(@extra_sections);
2103           } elsif ( !$type ) {
2104             $subtotal{$locationnum}{$section} += $cust_bill_pkg->setup
2105                                                + $cust_bill_pkg->recur;
2106           }
2107
2108         }
2109
2110       }
2111
2112   }
2113
2114   %pkg_category_cache = ();
2115
2116   # summary invoices need subtotals for all non-disabled package categories,
2117   # even if they're zero
2118   # but currently assume that there are no location sections, or at least
2119   # that the summary page doesn't care about them
2120   if ( $opt{summary} ) {
2121     foreach my $category (qsearch('pkg_category', {disabled => ''})) {
2122       $subtotal{''}{$category->categoryname} ||= 0;
2123     }
2124     $subtotal{''}{''} ||= 0;
2125   }
2126
2127   my @sections;
2128   foreach my $post_total (0,1) {
2129     my @these;
2130     my $s = $post_total ? \%late_subtotal : \%subtotal;
2131     foreach my $locationnum (keys %$s) {
2132       foreach my $sectionname (keys %{ $s->{$locationnum} }) {
2133         my $section = {
2134                         'subtotal'    => $s->{$locationnum}{$sectionname},
2135                         'post_total'  => $post_total,
2136                         'sort_weight' => 0,
2137                       };
2138         if ( $locationnum ) {
2139           $section->{'locationnum'} = $locationnum;
2140           my $location = FS::cust_location->by_key($locationnum);
2141           $section->{'description'} = &{ $escape }($location->location_label);
2142           # Better ideas? This will roughly group them by proximity, 
2143           # which alpha sorting on any of the address fields won't.
2144           # Sorting by locationnum is meaningless.
2145           # We have to sort on _something_ or the order may change 
2146           # randomly from one invoice to the next, which will confuse
2147           # people.
2148           $section->{'sort_weight'} = sprintf('%012s',$location->zip) .
2149                                       $locationnum;
2150           $section->{'location'} = {
2151             label_prefix => &{ $escape }($location->label_prefix),
2152             map { $_ => &{ $escape }($location->get($_)) }
2153               $location->fields
2154           };
2155         } else {
2156           $section->{'category'} = $sectionname;
2157           $section->{'description'} = &{ $escape }($sectionname);
2158           if ( _pkg_category($_) ) {
2159             $section->{'sort_weight'} = _pkg_category($_)->weight;
2160             if ( _pkg_category($_)->condense ) {
2161               $section = { %$section, $self->_condense_section($opt{format}) };
2162             }
2163           }
2164         }
2165         if ( !$post_total and !$not_tax{$locationnum}{$sectionname} ) {
2166           # then it's a tax-only section
2167           $section->{'summarized'} = 'Y';
2168           $section->{'tax_section'} = 'Y';
2169         }
2170         push @these, $section;
2171       } # foreach $sectionname
2172     } #foreach $locationnum
2173     push @these, @extra_sections if $post_total == 0;
2174     # need an alpha sort for location sections, because postal codes can 
2175     # be non-numeric
2176     $sections[ $post_total ] = [ sort {
2177       $opt{'by_location'} ? 
2178         ($a->{sort_weight} cmp $b->{sort_weight}) :
2179         ($a->{sort_weight} <=> $b->{sort_weight})
2180       } @these ];
2181   } #foreach $post_total
2182
2183   return @sections; # early, late
2184 }
2185
2186 #helper subs for above
2187
2188 sub cust_pkg_hash {
2189   my $self = shift;
2190   $self->{cust_pkg} ||= { map { $_->pkgnum => $_ } $self->cust_pkg };
2191 }
2192
2193 sub _pkg_category {
2194   my $categoryname = shift;
2195   $pkg_category_cache{$categoryname} ||=
2196     qsearchs( 'pkg_category', { 'categoryname' => $categoryname } );
2197 }
2198
2199 my %condensed_format = (
2200   'label' => [ qw( Description Qty Amount ) ],
2201   'fields' => [
2202                 sub { shift->{description} },
2203                 sub { shift->{quantity} },
2204                 sub { my($href, %opt) = @_;
2205                       ($opt{dollar} || ''). $href->{amount};
2206                     },
2207               ],
2208   'align'  => [ qw( l r r ) ],
2209   'span'   => [ qw( 5 1 1 ) ],            # unitprices?
2210   'width'  => [ qw( 10.7cm 1.4cm 1.6cm ) ],   # don't like this
2211 );
2212
2213 sub _condense_section {
2214   my ( $self, $format ) = ( shift, shift );
2215   ( 'condensed' => 1,
2216     map { my $method = "_condensed_$_"; $_ => $self->$method($format) }
2217       qw( description_generator
2218           header_generator
2219           total_generator
2220           total_line_generator
2221         )
2222   );
2223 }
2224
2225 sub _condensed_generator_defaults {
2226   my ( $self, $format ) = ( shift, shift );
2227   return ( \%condensed_format, ' ', ' ', ' ', sub { shift } );
2228 }
2229
2230 my %html_align = (
2231   'c' => 'center',
2232   'l' => 'left',
2233   'r' => 'right',
2234 );
2235
2236 sub _condensed_header_generator {
2237   my ( $self, $format ) = ( shift, shift );
2238
2239   my ( $f, $prefix, $suffix, $separator, $column ) =
2240     _condensed_generator_defaults($format);
2241
2242   if ($format eq 'latex') {
2243     $prefix = "\\hline\n\\rule{0pt}{2.5ex}\n\\makebox[1.4cm]{}&\n";
2244     $suffix = "\\\\\n\\hline";
2245     $separator = "&\n";
2246     $column =
2247       sub { my ($d,$a,$s,$w) = @_;
2248             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2249           };
2250   } elsif ( $format eq 'html' ) {
2251     $prefix = '<th></th>';
2252     $suffix = '';
2253     $separator = '';
2254     $column =
2255       sub { my ($d,$a,$s,$w) = @_;
2256             return qq!<th align="$html_align{$a}">$d</th>!;
2257       };
2258   }
2259
2260   sub {
2261     my @args = @_;
2262     my @result = ();
2263
2264     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2265       push @result,
2266         &{$column}( map { $f->{$_}->[$i] } qw(label align span width) );
2267     }
2268
2269     $prefix. join($separator, @result). $suffix;
2270   };
2271
2272 }
2273
2274 sub _condensed_description_generator {
2275   my ( $self, $format ) = ( shift, shift );
2276
2277   my ( $f, $prefix, $suffix, $separator, $column ) =
2278     _condensed_generator_defaults($format);
2279
2280   my $money_char = '$';
2281   if ($format eq 'latex') {
2282     $prefix = "\\hline\n\\multicolumn{1}{c}{\\rule{0pt}{2.5ex}~} &\n";
2283     $suffix = '\\\\';
2284     $separator = " & \n";
2285     $column =
2286       sub { my ($d,$a,$s,$w) = @_;
2287             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
2288           };
2289     $money_char = '\\dollar';
2290   }elsif ( $format eq 'html' ) {
2291     $prefix = '"><td align="center"></td>';
2292     $suffix = '';
2293     $separator = '';
2294     $column =
2295       sub { my ($d,$a,$s,$w) = @_;
2296             return qq!<td align="$html_align{$a}">$d</td>!;
2297       };
2298     #$money_char = $conf->config('money_char') || '$';
2299     $money_char = '';  # this is madness
2300   }
2301
2302   sub {
2303     #my @args = @_;
2304     my $href = shift;
2305     my @result = ();
2306
2307     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2308       my $dollar = '';
2309       $dollar = $money_char if $i == scalar(@{$f->{label}})-1;
2310       push @result,
2311         &{$column}( &{$f->{fields}->[$i]}($href, 'dollar' => $dollar),
2312                     map { $f->{$_}->[$i] } qw(align span width)
2313                   );
2314     }
2315
2316     $prefix. join( $separator, @result ). $suffix;
2317   };
2318
2319 }
2320
2321 sub _condensed_total_generator {
2322   my ( $self, $format ) = ( shift, shift );
2323
2324   my ( $f, $prefix, $suffix, $separator, $column ) =
2325     _condensed_generator_defaults($format);
2326   my $style = '';
2327
2328   if ($format eq 'latex') {
2329     $prefix = "& ";
2330     $suffix = "\\\\\n";
2331     $separator = " & \n";
2332     $column =
2333       sub { my ($d,$a,$s,$w) = @_;
2334             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
2335           };
2336   }elsif ( $format eq 'html' ) {
2337     $prefix = '';
2338     $suffix = '';
2339     $separator = '';
2340     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
2341     $column =
2342       sub { my ($d,$a,$s,$w) = @_;
2343             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
2344       };
2345   }
2346
2347
2348   sub {
2349     my @args = @_;
2350     my @result = ();
2351
2352     #  my $r = &{$f->{fields}->[$i]}(@args);
2353     #  $r .= ' Total' unless $i;
2354
2355     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2356       push @result,
2357         &{$column}( &{$f->{fields}->[$i]}(@args). ($i ? '' : ' Total'),
2358                     map { $f->{$_}->[$i] } qw(align span width)
2359                   );
2360     }
2361
2362     $prefix. join( $separator, @result ). $suffix;
2363   };
2364
2365 }
2366
2367 =item total_line_generator FORMAT
2368
2369 Returns a coderef used for generation of invoice total line items for this
2370 usage_class.  FORMAT is either html or latex
2371
2372 =cut
2373
2374 # should not be used: will have issues with hash element names (description vs
2375 # total_item and amount vs total_amount -- another array of functions?
2376
2377 sub _condensed_total_line_generator {
2378   my ( $self, $format ) = ( shift, shift );
2379
2380   my ( $f, $prefix, $suffix, $separator, $column ) =
2381     _condensed_generator_defaults($format);
2382   my $style = '';
2383
2384   if ($format eq 'latex') {
2385     $prefix = "& ";
2386     $suffix = "\\\\\n";
2387     $separator = " & \n";
2388     $column =
2389       sub { my ($d,$a,$s,$w) = @_;
2390             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
2391           };
2392   }elsif ( $format eq 'html' ) {
2393     $prefix = '';
2394     $suffix = '';
2395     $separator = '';
2396     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
2397     $column =
2398       sub { my ($d,$a,$s,$w) = @_;
2399             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
2400       };
2401   }
2402
2403
2404   sub {
2405     my @args = @_;
2406     my @result = ();
2407
2408     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
2409       push @result,
2410         &{$column}( &{$f->{fields}->[$i]}(@args),
2411                     map { $f->{$_}->[$i] } qw(align span width)
2412                   );
2413     }
2414
2415     $prefix. join( $separator, @result ). $suffix;
2416   };
2417
2418 }
2419
2420 =item _items_pkg [ OPTIONS ]
2421
2422 Return line item hashes for each package item on this invoice. Nearly 
2423 equivalent to 
2424
2425 $self->_items_cust_bill_pkg([ $self->cust_bill_pkg ])
2426
2427 The only OPTIONS accepted is 'section', which may point to a hashref 
2428 with a key named 'condensed', which may have a true value.  If it 
2429 does, this method tries to merge identical items into items with 
2430 'quantity' equal to the number of items (not the sum of their 
2431 separate quantities, for some reason).
2432
2433 =cut
2434
2435 sub _items_nontax {
2436   my $self = shift;
2437   # The order of these is important.  Bundled line items will be merged into
2438   # the most recent non-hidden item, so it needs to be the one with:
2439   # - the same pkgnum
2440   # - the same start date
2441   # - no pkgpart_override
2442   #
2443   # So: sort by pkgnum,
2444   # then by sdate
2445   # then sort the base line item before any overrides
2446   # then sort hidden before non-hidden add-ons
2447   # then sort by override pkgpart (for consistency)
2448   sort { $a->pkgnum <=> $b->pkgnum        or
2449          $a->sdate  <=> $b->sdate         or
2450          ($a->pkgpart_override ? 0 : -1)  or
2451          ($b->pkgpart_override ? 0 : 1)   or
2452          $b->hidden cmp $a->hidden        or
2453          $a->pkgpart_override <=> $b->pkgpart_override
2454        }
2455   # and of course exclude taxes and fees
2456   grep { $_->pkgnum > 0 } $self->cust_bill_pkg;
2457 }
2458
2459 sub _items_fee {
2460   my $self = shift;
2461   my %options = @_;
2462   my @cust_bill_pkg = grep { $_->feepart } $self->cust_bill_pkg;
2463   my @items;
2464   foreach my $cust_bill_pkg (@cust_bill_pkg) {
2465     # cache this, so we don't look it up again in every section
2466     my $part_fee = $cust_bill_pkg->get('part_fee')
2467        || $cust_bill_pkg->part_fee;
2468     $cust_bill_pkg->set('part_fee', $part_fee);
2469     if (!$part_fee) {
2470       #die "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n"; # might make more sense
2471       warn "fee definition not found for line item #".$cust_bill_pkg->billpkgnum."\n";
2472       next;
2473     }
2474     if ( exists($options{section}) and exists($options{section}{category}) )
2475     {
2476       my $categoryname = $options{section}{category};
2477       # then filter for items that have that section
2478       if ( $part_fee->categoryname ne $categoryname ) {
2479         warn "skipping fee '".$part_fee->itemdesc."'--not in section $categoryname\n" if $DEBUG;
2480         next;
2481       }
2482     } # otherwise include them all in the main section
2483     # XXX what to do when sectioning by location?
2484     
2485     my @ext_desc;
2486     my %base_invnums; # invnum => invoice date
2487     foreach ($cust_bill_pkg->cust_bill_pkg_fee) {
2488       if ($_->base_invnum) {
2489         my $base_bill = FS::cust_bill->by_key($_->base_invnum);
2490         my $base_date = $self->time2str_local('short', $base_bill->_date)
2491           if $base_bill;
2492         $base_invnums{$_->base_invnum} = $base_date || '';
2493       }
2494     }
2495     foreach (sort keys(%base_invnums)) {
2496       next if $_ == $self->invnum;
2497       push @ext_desc,
2498         $self->mt('from invoice \\#[_1] on [_2]', $_, $base_invnums{$_});
2499     }
2500     push @items,
2501       { feepart     => $cust_bill_pkg->feepart,
2502         amount      => sprintf('%.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2503         description => $part_fee->itemdesc_locale($self->cust_main->locale),
2504         ext_description => \@ext_desc
2505         # sdate/edate?
2506       };
2507   }
2508   @items;
2509 }
2510
2511 sub _items_pkg {
2512   my $self = shift;
2513   my %options = @_;
2514
2515   warn "$me _items_pkg searching for all package line items\n"
2516     if $DEBUG > 1;
2517
2518   my @cust_bill_pkg = $self->_items_nontax;
2519
2520   warn "$me _items_pkg filtering line items\n"
2521     if $DEBUG > 1;
2522   my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
2523
2524   if ($options{section} && $options{section}->{condensed}) {
2525
2526     warn "$me _items_pkg condensing section\n"
2527       if $DEBUG > 1;
2528
2529     my %itemshash = ();
2530     local $Storable::canonical = 1;
2531     foreach ( @items ) {
2532       my $item = { %$_ };
2533       delete $item->{ref};
2534       delete $item->{ext_description};
2535       my $key = freeze($item);
2536       $itemshash{$key} ||= 0;
2537       $itemshash{$key} ++; # += $item->{quantity};
2538     }
2539     @items = sort { $a->{description} cmp $b->{description} }
2540              map { my $i = thaw($_);
2541                    $i->{quantity} = $itemshash{$_};
2542                    $i->{amount} =
2543                      sprintf( "%.2f", $i->{quantity} * $i->{amount} );#unit_amount
2544                    $i;
2545                  }
2546              keys %itemshash;
2547   }
2548
2549   warn "$me _items_pkg returning ". scalar(@items). " items\n"
2550     if $DEBUG > 1;
2551
2552   @items;
2553 }
2554
2555 sub _taxsort {
2556   return 0 unless $a->itemdesc cmp $b->itemdesc;
2557   return -1 if $b->itemdesc eq 'Tax';
2558   return 1 if $a->itemdesc eq 'Tax';
2559   return -1 if $b->itemdesc eq 'Other surcharges';
2560   return 1 if $a->itemdesc eq 'Other surcharges';
2561   $a->itemdesc cmp $b->itemdesc;
2562 }
2563
2564 sub _items_tax {
2565   my $self = shift;
2566   my @cust_bill_pkg = sort _taxsort grep { ! $_->pkgnum and ! $_->feepart } 
2567     $self->cust_bill_pkg;
2568   my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
2569
2570   if ( $self->conf->exists('always_show_tax') ) {
2571     my $itemdesc = $self->conf->config('always_show_tax') || 'Tax';
2572     if (0 == grep { $_->{description} eq $itemdesc } @items) {
2573       push @items,
2574         { 'description' => $itemdesc,
2575           'amount'      => 0.00 };
2576     }
2577   }
2578   @items;
2579 }
2580
2581 =item _items_cust_bill_pkg CUST_BILL_PKGS OPTIONS
2582
2583 Takes an arrayref of L<FS::cust_bill_pkg> objects, and returns a
2584 list of hashrefs describing the line items they generate on the invoice.
2585
2586 OPTIONS may include:
2587
2588 format: the invoice format.
2589
2590 escape_function: the function used to escape strings.
2591
2592 DEPRECATED? (expensive, mostly unused?)
2593 format_function: the function used to format CDRs.
2594
2595 section: a hashref containing 'category' and/or 'locationnum'; if this 
2596 is present, only returns line items that belong to that category and/or
2597 location (whichever is defined).
2598
2599 multisection: a flag indicating that this is a multisection invoice,
2600 which does something complicated.
2601
2602 preref_callback: coderef run for each line item, code should return HTML to be
2603 displayed before that line item (quotations only)
2604
2605 Returns a list of hashrefs, each of which may contain:
2606
2607 pkgnum, description, amount, unit_amount, quantity, pkgpart, _is_setup, and 
2608 ext_description, which is an arrayref of detail lines to show below 
2609 the package line.
2610
2611 =cut
2612
2613 sub _items_cust_bill_pkg {
2614   my $self = shift;
2615   my $conf = $self->conf;
2616   my $cust_bill_pkgs = shift;
2617   my %opt = @_;
2618
2619   my $format = $opt{format} || '';
2620   my $escape_function = $opt{escape_function} || sub { shift };
2621   my $format_function = $opt{format_function} || '';
2622   my $no_usage = $opt{no_usage} || '';
2623   my $unsquelched = $opt{unsquelched} || ''; #unused
2624   my ($section, $locationnum, $category);
2625   if ( $opt{section} ) {
2626     $category = $opt{section}->{category};
2627     $locationnum = $opt{section}->{locationnum};
2628   }
2629   my $summary_page = $opt{summary_page} || ''; #unused
2630   my $multisection = defined($category) || defined($locationnum);
2631   my $discount_show_always = 0;
2632
2633   my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2634
2635   my $cust_main = $self->cust_main;#for per-agent cust_bill-line_item-ate_style
2636                                    # and location labels
2637
2638   my @b = ();
2639   my ($s, $r, $u) = ( undef, undef, undef );
2640   foreach my $cust_bill_pkg ( @$cust_bill_pkgs )
2641   {
2642
2643     foreach ( $s, $r, ($opt{skip_usage} ? () : $u ) ) {
2644       if ( $_ && !$cust_bill_pkg->hidden ) {
2645         $_->{amount}      = sprintf( "%.2f", $_->{amount} ),
2646         $_->{amount}      =~ s/^\-0\.00$/0.00/;
2647         $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} ),
2648         push @b, { %$_ }
2649           if $_->{amount} != 0
2650           || $discount_show_always
2651           || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
2652           || (   $_->{_is_setup} && $_->{setup_show_zero} )
2653         ;
2654         $_ = undef;
2655       }
2656     }
2657
2658     if ( $locationnum ) {
2659       # this is a location section; skip packages that aren't at this
2660       # service location.
2661       next if $cust_bill_pkg->pkgnum == 0; # skips fees...
2662       next if $self->cust_pkg_hash->{ $cust_bill_pkg->pkgnum }->locationnum 
2663               != $locationnum;
2664     }
2665
2666     # Consider display records for this item to determine if it belongs
2667     # in this section.  Note that if there are no display records, there
2668     # will be a default pseudo-record that includes all charge types 
2669     # and has no section name.
2670     my @cust_bill_pkg_display = $cust_bill_pkg->can('cust_bill_pkg_display')
2671                                   ? $cust_bill_pkg->cust_bill_pkg_display
2672                                   : ( $cust_bill_pkg );
2673
2674     warn "$me _items_cust_bill_pkg considering cust_bill_pkg ".
2675          $cust_bill_pkg->billpkgnum. ", pkgnum ". $cust_bill_pkg->pkgnum. "\n"
2676       if $DEBUG > 1;
2677
2678     if ( defined($category) ) {
2679       # then this is a package category section; process all display records
2680       # that belong to this section.
2681       @cust_bill_pkg_display = grep { $_->section eq $category }
2682                                 @cust_bill_pkg_display;
2683     } else {
2684       # otherwise, process all display records that aren't usage summaries
2685       # (I don't think there should be usage summaries if you aren't using 
2686       # category sections, but this is the historical behavior)
2687       @cust_bill_pkg_display = grep { !$_->summary }
2688                                 @cust_bill_pkg_display;
2689     }
2690
2691     my $classname = ''; # package class name, will fill in later
2692
2693     foreach my $display (@cust_bill_pkg_display) {
2694
2695       warn "$me _items_cust_bill_pkg considering cust_bill_pkg_display ".
2696            $display->billpkgdisplaynum. "\n"
2697         if $DEBUG > 1;
2698
2699       my $type = $display->type;
2700
2701       my $desc = $cust_bill_pkg->desc( $cust_main ? $cust_main->locale : '' );
2702       $desc = substr($desc, 0, $maxlength). '...'
2703         if $format eq 'latex' && length($desc) > $maxlength;
2704
2705       my %details_opt = ( 'format'          => $format,
2706                           'escape_function' => $escape_function,
2707                           'format_function' => $format_function,
2708                           'no_usage'        => $opt{'no_usage'},
2709                         );
2710
2711       if ( ref($cust_bill_pkg) eq 'FS::quotation_pkg' ) {
2712
2713         warn "$me _items_cust_bill_pkg cust_bill_pkg is quotation_pkg\n"
2714           if $DEBUG > 1;
2715         # quotation_pkgs are never fees, so don't worry about the case where
2716         # part_pkg is undefined
2717
2718         if ( $cust_bill_pkg->setup != 0 ) {
2719           my $description = $desc;
2720           $description .= ' Setup'
2721             if $cust_bill_pkg->recur != 0
2722             || $discount_show_always
2723             || $cust_bill_pkg->recur_show_zero;
2724           push @b, {
2725             'pkgnum'      => $cust_bill_pkg->pkgpart, #so it displays in Ref
2726             'description' => $description,
2727             'amount'      => sprintf("%.2f", $cust_bill_pkg->setup),
2728             'preref_html' => ( $opt{preref_callback}
2729                                  ? &{ $opt{preref_callback} }( $cust_bill_pkg )
2730                                  : ''
2731                              ),
2732           };
2733         }
2734         if ( $cust_bill_pkg->recur != 0 ) {
2735           push @b, {
2736             'pkgnum'      => $cust_bill_pkg->pkgpart, #so it displays in Ref
2737             'description' => "$desc (". $cust_bill_pkg->part_pkg->freq_pretty.")",
2738             'amount'      => sprintf("%.2f", $cust_bill_pkg->recur),
2739           };
2740         }
2741
2742       } elsif ( $cust_bill_pkg->pkgnum > 0 ) { # and it's not a quotation_pkg
2743
2744         warn "$me _items_cust_bill_pkg cust_bill_pkg is non-tax\n"
2745           if $DEBUG > 1;
2746  
2747         my $cust_pkg = $cust_bill_pkg->cust_pkg;
2748         my $part_pkg = $cust_pkg->part_pkg;
2749
2750         # which pkgpart to show for display purposes?
2751         my $pkgpart = $cust_bill_pkg->pkgpart_override || $cust_pkg->pkgpart;
2752
2753         # start/end dates for invoice formats that do nonstandard 
2754         # things with them
2755         my %item_dates = ();
2756         %item_dates = map { $_ => $cust_bill_pkg->$_ } ('sdate', 'edate')
2757           unless $part_pkg->option('disable_line_item_date_ranges',1);
2758
2759         # not normally used, but pass this to the template anyway
2760         $classname = $part_pkg->classname;
2761
2762         if (    (!$type || $type eq 'S')
2763              && (    $cust_bill_pkg->setup != 0
2764                   || $cust_bill_pkg->setup_show_zero
2765                 )
2766            )
2767          {
2768
2769           warn "$me _items_cust_bill_pkg adding setup\n"
2770             if $DEBUG > 1;
2771
2772           my $description = $desc;
2773           $description .= ' Setup'
2774             if $cust_bill_pkg->recur != 0
2775             || $discount_show_always
2776             || $cust_bill_pkg->recur_show_zero;
2777
2778           $description .= $cust_bill_pkg->time_period_pretty( $part_pkg,
2779                                                               $self->agentnum )
2780             if $part_pkg->is_prepaid #for prepaid, "display the validity period
2781                                      # triggered by the recurring charge freq
2782                                      # (RT#26274)
2783             && $cust_bill_pkg->recur == 0
2784             && ! $cust_bill_pkg->recur_show_zero;
2785
2786           my @d = ();
2787           my $svc_label;
2788
2789           # always pass the svc_label through to the template, even if 
2790           # not displaying it as an ext_description
2791           my @svc_labels = map &{$escape_function}($_),
2792                       $cust_pkg->h_labels_short($self->_date, undef, 'I');
2793
2794           $svc_label = $svc_labels[0];
2795
2796           unless ( $cust_pkg->part_pkg->hide_svc_detail
2797                 || $cust_bill_pkg->hidden )
2798           {
2799
2800             push @d, @svc_labels
2801               unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
2802             my $lnum = $cust_main ? $cust_main->ship_locationnum
2803                                   : $self->prospect_main->locationnum;
2804             # show the location label if it's not the customer's default
2805             # location, and we're not grouping items by location already
2806             if ( $cust_pkg->locationnum != $lnum and !defined($locationnum) ) {
2807               my $loc = $cust_pkg->location_label;
2808               $loc = substr($loc, 0, $maxlength). '...'
2809                 if $format eq 'latex' && length($loc) > $maxlength;
2810               push @d, &{$escape_function}($loc);
2811             }
2812
2813           } #unless hiding service details
2814
2815           push @d, $cust_bill_pkg->details(%details_opt)
2816             if $cust_bill_pkg->recur == 0;
2817
2818           if ( $cust_bill_pkg->hidden ) {
2819             $s->{amount}      += $cust_bill_pkg->setup;
2820             $s->{unit_amount} += $cust_bill_pkg->unitsetup;
2821             push @{ $s->{ext_description} }, @d;
2822           } else {
2823             $s = {
2824               _is_setup       => 1,
2825               description     => $description,
2826               pkgpart         => $pkgpart,
2827               pkgnum          => $cust_bill_pkg->pkgnum,
2828               amount          => $cust_bill_pkg->setup,
2829               setup_show_zero => $cust_bill_pkg->setup_show_zero,
2830               unit_amount     => $cust_bill_pkg->unitsetup,
2831               quantity        => $cust_bill_pkg->quantity,
2832               ext_description => \@d,
2833               svc_label       => ($svc_label || ''),
2834               locationnum     => $cust_pkg->locationnum, # sure, why not?
2835             };
2836           };
2837
2838         }
2839
2840         if (    ( !$type || $type eq 'R' || $type eq 'U' )
2841              && (
2842                      $cust_bill_pkg->recur != 0
2843                   || $cust_bill_pkg->setup == 0
2844                   || $discount_show_always
2845                   || $cust_bill_pkg->recur_show_zero
2846                 )
2847            )
2848         {
2849
2850           warn "$me _items_cust_bill_pkg adding recur/usage\n"
2851             if $DEBUG > 1;
2852
2853           my $is_summary = $display->summary;
2854           my $description = $desc;
2855           if ( $type eq 'U' and defined($r) ) {
2856             # don't just show the same description as the recur line
2857             $description = $self->mt('Usage charges');
2858           }
2859
2860           my $part_pkg = $cust_pkg->part_pkg;
2861
2862           $description .= $cust_bill_pkg->time_period_pretty( $part_pkg,
2863                                                               $self->agentnum );
2864
2865           my @d = ();
2866           my @seconds = (); # for display of usage info
2867           my $svc_label = '';
2868
2869           #at least until cust_bill_pkg has "past" ranges in addition to
2870           #the "future" sdate/edate ones... see #3032
2871           my @dates = ( $self->_date );
2872           my $prev = $cust_bill_pkg->previous_cust_bill_pkg;
2873           push @dates, $prev->sdate if $prev;
2874           push @dates, undef if !$prev;
2875
2876           my @svc_labels = map &{$escape_function}($_),
2877                       $cust_pkg->h_labels_short(@dates, 'I');
2878           $svc_label = $svc_labels[0];
2879
2880           # show service labels, unless...
2881                     # the package is set not to display them
2882           unless ( $part_pkg->hide_svc_detail
2883                     # or this is a tax-like line item
2884                 || $cust_bill_pkg->itemdesc
2885                     # or this is a hidden (bundled) line item
2886                 || $cust_bill_pkg->hidden
2887                     # or this is a usage summary line
2888                 || $is_summary && $type && $type eq 'U'
2889                     # or this is a usage line and there's a recurring line
2890                     # for the package in the same section (which will 
2891                     # have service labels already)
2892                 || ($type eq 'U' and defined($r))
2893               )
2894           {
2895
2896             warn "$me _items_cust_bill_pkg adding service details\n"
2897               if $DEBUG > 1;
2898
2899             push @d, @svc_labels
2900               unless $cust_bill_pkg->pkgpart_override; #don't redisplay services
2901             warn "$me _items_cust_bill_pkg done adding service details\n"
2902               if $DEBUG > 1;
2903
2904             my $lnum = $cust_main ? $cust_main->ship_locationnum
2905                                   : $self->prospect_main->locationnum;
2906             # show the location label if it's not the customer's default
2907             # location, and we're not grouping items by location already
2908             if ( $cust_pkg->locationnum != $lnum and !defined($locationnum) ) {
2909               my $loc = $cust_pkg->location_label;
2910               $loc = substr($loc, 0, $maxlength). '...'
2911                 if $format eq 'latex' && length($loc) > $maxlength;
2912               push @d, &{$escape_function}($loc);
2913             }
2914
2915             # Display of seconds_since_sqlradacct:
2916             # On the invoice, when processing @detail_items, look for a field
2917             # named 'seconds'.  This will contain total seconds for each 
2918             # service, in the same order as @ext_description.  For services 
2919             # that don't support this it will show undef.
2920             if ( $conf->exists('svc_acct-usage_seconds') 
2921                  and ! $cust_bill_pkg->pkgpart_override ) {
2922               foreach my $cust_svc ( 
2923                   $cust_pkg->h_cust_svc(@dates, 'I') 
2924                 ) {
2925
2926                 # eval because not having any part_export_usage exports 
2927                 # is a fatal error, last_bill/_date because that's how 
2928                 # sqlradius_hour billing does it
2929                 my $sec = eval {
2930                   $cust_svc->seconds_since_sqlradacct($dates[1] || 0, $dates[0]);
2931                 };
2932                 push @seconds, $sec;
2933               }
2934             } #if svc_acct-usage_seconds
2935
2936           } # if we are showing service labels
2937
2938           unless ( $is_summary ) {
2939             warn "$me _items_cust_bill_pkg adding details\n"
2940               if $DEBUG > 1;
2941
2942             #instead of omitting details entirely in this case (unwanted side
2943             # effects), just omit CDRs
2944             $details_opt{'no_usage'} = 1
2945               if $type && $type eq 'R';
2946
2947             push @d, $cust_bill_pkg->details(%details_opt);
2948           }
2949
2950           warn "$me _items_cust_bill_pkg calculating amount\n"
2951             if $DEBUG > 1;
2952   
2953           my $amount = 0;
2954           if (!$type) {
2955             $amount = $cust_bill_pkg->recur;
2956           } elsif ($type eq 'R') {
2957             $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
2958           } elsif ($type eq 'U') {
2959             $amount = $cust_bill_pkg->usage;
2960           }
2961   
2962           if ( !$type || $type eq 'R' ) {
2963
2964             warn "$me _items_cust_bill_pkg adding recur\n"
2965               if $DEBUG > 1;
2966
2967             my $unit_amount =
2968               ( $cust_bill_pkg->unitrecur > 0 ) ? $cust_bill_pkg->unitrecur
2969                                                 : $amount;
2970
2971             if ( $cust_bill_pkg->hidden ) {
2972               $r->{amount}      += $amount;
2973               $r->{unit_amount} += $unit_amount;
2974               push @{ $r->{ext_description} }, @d;
2975             } else {
2976               $r = {
2977                 description     => $description,
2978                 pkgpart         => $pkgpart,
2979                 pkgnum          => $cust_bill_pkg->pkgnum,
2980                 amount          => $amount,
2981                 recur_show_zero => $cust_bill_pkg->recur_show_zero,
2982                 unit_amount     => $unit_amount,
2983                 quantity        => $cust_bill_pkg->quantity,
2984                 %item_dates,
2985                 ext_description => \@d,
2986                 svc_label       => ($svc_label || ''),
2987                 locationnum     => $cust_pkg->locationnum,
2988               };
2989               $r->{'seconds'} = \@seconds if grep {defined $_} @seconds;
2990             }
2991
2992           } else {  # $type eq 'U'
2993
2994             warn "$me _items_cust_bill_pkg adding usage\n"
2995               if $DEBUG > 1;
2996
2997             if ( $cust_bill_pkg->hidden and defined($u) ) {
2998               # if this is a hidden package and there's already a usage
2999               # line for the bundle, add this package's total amount and
3000               # usage details to it
3001               $u->{amount}      += $amount;
3002               push @{ $u->{ext_description} }, @d;
3003             } elsif ( $amount ) {
3004               # create a new usage line
3005               $u = {
3006                 description     => $description,
3007                 pkgpart         => $pkgpart,
3008                 pkgnum          => $cust_bill_pkg->pkgnum,
3009                 amount          => $amount,
3010                 usage_item      => 1,
3011                 recur_show_zero => $cust_bill_pkg->recur_show_zero,
3012                 %item_dates,
3013                 ext_description => \@d,
3014                 locationnum     => $cust_pkg->locationnum,
3015               };
3016             } # else this has no usage, so don't create a usage section
3017           }
3018
3019         } # recurring or usage with recurring charge
3020
3021       } else { # taxes and fees
3022
3023         warn "$me _items_cust_bill_pkg cust_bill_pkg is tax\n"
3024           if $DEBUG > 1;
3025
3026         # items of this kind should normally not have sdate/edate.
3027         push @b, {
3028           'description' => $desc,
3029           'amount'      => sprintf('%.2f', $cust_bill_pkg->setup 
3030                                            + $cust_bill_pkg->recur)
3031         };
3032
3033       } # if quotation / package line item / other line item
3034
3035     } # foreach $display
3036
3037     $discount_show_always = ($cust_bill_pkg->cust_bill_pkg_discount
3038                                 && $conf->exists('discount-show-always'));
3039
3040   }
3041
3042   foreach ( $s, $r, ($opt{skip_usage} ? () : $u ) ) {
3043     if ( $_  ) {
3044       $_->{amount}      = sprintf( "%.2f", $_->{amount} ),
3045         if exists($_->{amount});
3046       $_->{amount}      =~ s/^\-0\.00$/0.00/;
3047       $_->{unit_amount} = sprintf('%.2f', $_->{unit_amount})
3048         if exists($_->{unit_amount});
3049
3050       push @b, { %$_ }
3051         if $_->{amount} != 0
3052         || $discount_show_always
3053         || ( ! $_->{_is_setup} && $_->{recur_show_zero} )
3054         || (   $_->{_is_setup} && $_->{setup_show_zero} )
3055     }
3056   }
3057
3058   warn "$me _items_cust_bill_pkg done considering cust_bill_pkgs\n"
3059     if $DEBUG > 1;
3060
3061   @b;
3062
3063 }
3064
3065 =item _items_discounts_avail
3066
3067 Returns an array of line item hashrefs representing available term discounts
3068 for this invoice.  This makes the same assumptions that apply to term 
3069 discounts in general: that the package is billed monthly, at a flat rate, 
3070 with no usage charges.  A prorated first month will be handled, as will 
3071 a setup fee if the discount is allowed to apply to setup fees.
3072
3073 =cut
3074
3075 sub _items_discounts_avail {
3076   my $self = shift;
3077
3078   #maybe move this method from cust_bill when quotations support discount_plans 
3079   return () unless $self->can('discount_plans');
3080   my %plans = $self->discount_plans;
3081
3082   my $list_pkgnums = 0; # if any packages are not eligible for all discounts
3083   $list_pkgnums = grep { $_->list_pkgnums } values %plans;
3084
3085   map {
3086     my $months = $_;
3087     my $plan = $plans{$months};
3088
3089     my $term_total = sprintf('%.2f', $plan->discounted_total);
3090     my $percent = sprintf('%.0f', 
3091                           100 * (1 - $term_total / $plan->base_total) );
3092     my $permonth = sprintf('%.2f', $term_total / $months);
3093     my $detail = $self->mt('discount on item'). ' '.
3094                  join(', ', map { "#$_" } $plan->pkgnums)
3095       if $list_pkgnums;
3096
3097     # discounts for non-integer months don't work anyway
3098     $months = sprintf("%d", $months);
3099
3100     +{
3101       description => $self->mt('Save [_1]% by paying for [_2] months',
3102                                 $percent, $months),
3103       amount      => $self->mt('[_1] ([_2] per month)', 
3104                                 $term_total, $money_char.$permonth),
3105       ext_description => ($detail || ''),
3106     }
3107   } #map
3108   sort { $b <=> $a } keys %plans;
3109
3110 }
3111
3112 1;