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