add logo_file support to welcome_letter and fix leaving temp files around for invoice...
[freeside.git] / FS / FS / cust_bill.pm
1 package FS::cust_bill;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me $conf $money_char $date_format $rdate_format );
5 use vars qw( $invoice_lines @buf ); #yuck
6 use Fcntl qw(:flock); #for spool_csv
7 use List::Util qw(min max);
8 use Date::Format;
9 use Text::Template 1.20;
10 use File::Temp 0.14;
11 use String::ShellQuote;
12 use HTML::Entities;
13 use Locale::Country;
14 use Storable qw( freeze thaw );
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax generate_ps generate_pdf do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
18 use FS::cust_main_Mixin;
19 use FS::cust_main;
20 use FS::cust_statement;
21 use FS::cust_bill_pkg;
22 use FS::cust_bill_pkg_display;
23 use FS::cust_bill_pkg_detail;
24 use FS::cust_credit;
25 use FS::cust_pay;
26 use FS::cust_pkg;
27 use FS::cust_credit_bill;
28 use FS::pay_batch;
29 use FS::cust_pay_batch;
30 use FS::cust_bill_event;
31 use FS::cust_event;
32 use FS::part_pkg;
33 use FS::cust_bill_pay;
34 use FS::cust_bill_pay_batch;
35 use FS::part_bill_event;
36 use FS::payby;
37 use FS::bill_batch;
38 use FS::cust_bill_batch;
39
40 @ISA = qw( FS::cust_main_Mixin FS::Record );
41
42 $DEBUG = 0;
43 $me = '[FS::cust_bill]';
44
45 #ask FS::UID to run this stuff for us later
46 FS::UID->install_callback( sub { 
47   $conf = new FS::Conf;
48   $money_char   = $conf->config('money_char')  || '$';  
49   $date_format  = $conf->config('date_format') || '%x';  
50   $rdate_format = $conf->config('date_format') || '%m/%d/%Y';  
51 } );
52
53 =head1 NAME
54
55 FS::cust_bill - Object methods for cust_bill records
56
57 =head1 SYNOPSIS
58
59   use FS::cust_bill;
60
61   $record = new FS::cust_bill \%hash;
62   $record = new FS::cust_bill { 'column' => 'value' };
63
64   $error = $record->insert;
65
66   $error = $new_record->replace($old_record);
67
68   $error = $record->delete;
69
70   $error = $record->check;
71
72   ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
73
74   @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
75
76   ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
77
78   @cust_pay_objects = $cust_bill->cust_pay;
79
80   $tax_amount = $record->tax;
81
82   @lines = $cust_bill->print_text;
83   @lines = $cust_bill->print_text $time;
84
85 =head1 DESCRIPTION
86
87 An FS::cust_bill object represents an invoice; a declaration that a customer
88 owes you money.  The specific charges are itemized as B<cust_bill_pkg> records
89 (see L<FS::cust_bill_pkg>).  FS::cust_bill inherits from FS::Record.  The
90 following fields are currently supported:
91
92 Regular fields
93
94 =over 4
95
96 =item invnum - primary key (assigned automatically for new invoices)
97
98 =item custnum - customer (see L<FS::cust_main>)
99
100 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
101 L<Time::Local> and L<Date::Parse> for conversion functions.
102
103 =item charged - amount of this invoice
104
105 =item invoice_terms - optional terms override for this specific invoice
106
107 =back
108
109 Customer info at invoice generation time
110
111 =over 4
112
113 =item previous_balance
114
115 =item billing_balance
116
117 =back
118
119 Deprecated
120
121 =over 4
122
123 =item printed - deprecated
124
125 =back
126
127 Specific use cases
128
129 =over 4
130
131 =item closed - books closed flag, empty or `Y'
132
133 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
134
135 =item agent_invid - legacy invoice number
136
137 =back
138
139 =head1 METHODS
140
141 =over 4
142
143 =item new HASHREF
144
145 Creates a new invoice.  To add the invoice to the database, see L<"insert">.
146 Invoices are normally created by calling the bill method of a customer object
147 (see L<FS::cust_main>).
148
149 =cut
150
151 sub table { 'cust_bill'; }
152
153 sub cust_linked { $_[0]->cust_main_custnum; } 
154 sub cust_unlinked_msg {
155   my $self = shift;
156   "WARNING: can't find cust_main.custnum ". $self->custnum.
157   ' (cust_bill.invnum '. $self->invnum. ')';
158 }
159
160 =item insert
161
162 Adds this invoice to the database ("Posts" the invoice).  If there is an error,
163 returns the error, otherwise returns false.
164
165 =item delete
166
167 This method now works but you probably shouldn't use it.  Instead, apply a
168 credit against the invoice.
169
170 Using this method to delete invoices outright is really, really bad.  There
171 would be no record you ever posted this invoice, and there are no check to
172 make sure charged = 0 or that there are no associated cust_bill_pkg records.
173
174 Really, don't use it.
175
176 =cut
177
178 sub delete {
179   my $self = shift;
180   return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
181
182   local $SIG{HUP} = 'IGNORE';
183   local $SIG{INT} = 'IGNORE';
184   local $SIG{QUIT} = 'IGNORE';
185   local $SIG{TERM} = 'IGNORE';
186   local $SIG{TSTP} = 'IGNORE';
187   local $SIG{PIPE} = 'IGNORE';
188
189   my $oldAutoCommit = $FS::UID::AutoCommit;
190   local $FS::UID::AutoCommit = 0;
191   my $dbh = dbh;
192
193   foreach my $table (qw(
194     cust_bill_event
195     cust_event
196     cust_credit_bill
197     cust_bill_pay
198     cust_bill_pay
199     cust_credit_bill
200     cust_pay_batch
201     cust_bill_pay_batch
202     cust_bill_pkg
203   )) {
204
205     foreach my $linked ( $self->$table() ) {
206       my $error = $linked->delete;
207       if ( $error ) {
208         $dbh->rollback if $oldAutoCommit;
209         return $error;
210       }
211     }
212
213   }
214
215   my $error = $self->SUPER::delete(@_);
216   if ( $error ) {
217     $dbh->rollback if $oldAutoCommit;
218     return $error;
219   }
220
221   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
222
223   '';
224
225 }
226
227 =item replace OLD_RECORD
228
229 Replaces the OLD_RECORD with this one in the database.  If there is an error,
230 returns the error, otherwise returns false.
231
232 Only printed may be changed.  printed is normally updated by calling the
233 collect method of a customer object (see L<FS::cust_main>).
234
235 =cut
236
237 #replace can be inherited from Record.pm
238
239 # replace_check is now the preferred way to #implement replace data checks
240 # (so $object->replace() works without an argument)
241
242 sub replace_check {
243   my( $new, $old ) = ( shift, shift );
244   return "Can't change custnum!" unless $old->custnum == $new->custnum;
245   #return "Can't change _date!" unless $old->_date eq $new->_date;
246   return "Can't change _date!" unless $old->_date == $new->_date;
247   return "Can't change charged!" unless $old->charged == $new->charged
248                                      || $old->charged == 0;
249
250   '';
251 }
252
253 =item check
254
255 Checks all fields to make sure this is a valid invoice.  If there is an error,
256 returns the error, otherwise returns false.  Called by the insert and replace
257 methods.
258
259 =cut
260
261 sub check {
262   my $self = shift;
263
264   my $error =
265     $self->ut_numbern('invnum')
266     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
267     || $self->ut_numbern('_date')
268     || $self->ut_money('charged')
269     || $self->ut_numbern('printed')
270     || $self->ut_enum('closed', [ '', 'Y' ])
271     || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
272     || $self->ut_numbern('agent_invid') #varchar?
273   ;
274   return $error if $error;
275
276   $self->_date(time) unless $self->_date;
277
278   $self->printed(0) if $self->printed eq '';
279
280   $self->SUPER::check;
281 }
282
283 =item display_invnum
284
285 Returns the displayed invoice number for this invoice: agent_invid if
286 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
287
288 =cut
289
290 sub display_invnum {
291   my $self = shift;
292   if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
293     return $self->agent_invid;
294   } else {
295     return $self->invnum;
296   }
297 }
298
299 =item previous
300
301 Returns a list consisting of the total previous balance for this customer, 
302 followed by the previous outstanding invoices (as FS::cust_bill objects also).
303
304 =cut
305
306 sub previous {
307   my $self = shift;
308   my $total = 0;
309   my @cust_bill = sort { $a->_date <=> $b->_date }
310     grep { $_->owed != 0 && $_->_date < $self->_date }
311       qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) 
312   ;
313   foreach ( @cust_bill ) { $total += $_->owed; }
314   $total, @cust_bill;
315 }
316
317 =item cust_bill_pkg
318
319 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
320
321 =cut
322
323 sub cust_bill_pkg {
324   my $self = shift;
325   qsearch(
326     { 'table'    => 'cust_bill_pkg',
327       'hashref'  => { 'invnum' => $self->invnum },
328       'order_by' => 'ORDER BY billpkgnum',
329     }
330   );
331 }
332
333 =item cust_bill_pkg_pkgnum PKGNUM
334
335 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
336 specified pkgnum.
337
338 =cut
339
340 sub cust_bill_pkg_pkgnum {
341   my( $self, $pkgnum ) = @_;
342   qsearch(
343     { 'table'    => 'cust_bill_pkg',
344       'hashref'  => { 'invnum' => $self->invnum,
345                       'pkgnum' => $pkgnum,
346                     },
347       'order_by' => 'ORDER BY billpkgnum',
348     }
349   );
350 }
351
352 =item cust_pkg
353
354 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
355 this invoice.
356
357 =cut
358
359 sub cust_pkg {
360   my $self = shift;
361   my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
362                      $self->cust_bill_pkg;
363   my %saw = ();
364   grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
365 }
366
367 =item no_auto
368
369 Returns true if any of the packages (or their definitions) corresponding to the
370 line items for this invoice have the no_auto flag set.
371
372 =cut
373
374 sub no_auto {
375   my $self = shift;
376   grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
377 }
378
379 =item open_cust_bill_pkg
380
381 Returns the open line items for this invoice.
382
383 Note that cust_bill_pkg with both setup and recur fees are returned as two
384 separate line items, each with only one fee.
385
386 =cut
387
388 # modeled after cust_main::open_cust_bill
389 sub open_cust_bill_pkg {
390   my $self = shift;
391
392   # grep { $_->owed > 0 } $self->cust_bill_pkg
393
394   my %other = ( 'recur' => 'setup',
395                 'setup' => 'recur', );
396   my @open = ();
397   foreach my $field ( qw( recur setup )) {
398     push @open, map  { $_->set( $other{$field}, 0 ); $_; }
399                 grep { $_->owed($field) > 0 }
400                 $self->cust_bill_pkg;
401   }
402
403   @open;
404 }
405
406 =item cust_bill_event
407
408 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
409
410 =cut
411
412 sub cust_bill_event {
413   my $self = shift;
414   qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
415 }
416
417 =item num_cust_bill_event
418
419 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
420
421 =cut
422
423 sub num_cust_bill_event {
424   my $self = shift;
425   my $sql =
426     "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
427   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
428   $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
429   $sth->fetchrow_arrayref->[0];
430 }
431
432 =item cust_event
433
434 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
435
436 =cut
437
438 #false laziness w/cust_pkg.pm
439 sub cust_event {
440   my $self = shift;
441   qsearch({
442     'table'     => 'cust_event',
443     'addl_from' => 'JOIN part_event USING ( eventpart )',
444     'hashref'   => { 'tablenum' => $self->invnum },
445     'extra_sql' => " AND eventtable = 'cust_bill' ",
446   });
447 }
448
449 =item num_cust_event
450
451 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
452
453 =cut
454
455 #false laziness w/cust_pkg.pm
456 sub num_cust_event {
457   my $self = shift;
458   my $sql =
459     "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
460     "  WHERE tablenum = ? AND eventtable = 'cust_bill'";
461   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
462   $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
463   $sth->fetchrow_arrayref->[0];
464 }
465
466 =item cust_main
467
468 Returns the customer (see L<FS::cust_main>) for this invoice.
469
470 =cut
471
472 sub cust_main {
473   my $self = shift;
474   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
475 }
476
477 =item cust_suspend_if_balance_over AMOUNT
478
479 Suspends the customer associated with this invoice if the total amount owed on
480 this invoice and all older invoices is greater than the specified amount.
481
482 Returns a list: an empty list on success or a list of errors.
483
484 =cut
485
486 sub cust_suspend_if_balance_over {
487   my( $self, $amount ) = ( shift, shift );
488   my $cust_main = $self->cust_main;
489   if ( $cust_main->total_owed_date($self->_date) < $amount ) {
490     return ();
491   } else {
492     $cust_main->suspend(@_);
493   }
494 }
495
496 =item cust_credit
497
498 Depreciated.  See the cust_credited method.
499
500  #Returns a list consisting of the total previous credited (see
501  #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
502  #outstanding credits (FS::cust_credit objects).
503
504 =cut
505
506 sub cust_credit {
507   use Carp;
508   croak "FS::cust_bill->cust_credit depreciated; see ".
509         "FS::cust_bill->cust_credit_bill";
510   #my $self = shift;
511   #my $total = 0;
512   #my @cust_credit = sort { $a->_date <=> $b->_date }
513   #  grep { $_->credited != 0 && $_->_date < $self->_date }
514   #    qsearch('cust_credit', { 'custnum' => $self->custnum } )
515   #;
516   #foreach (@cust_credit) { $total += $_->credited; }
517   #$total, @cust_credit;
518 }
519
520 =item cust_pay
521
522 Depreciated.  See the cust_bill_pay method.
523
524 #Returns all payments (see L<FS::cust_pay>) for this invoice.
525
526 =cut
527
528 sub cust_pay {
529   use Carp;
530   croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
531   #my $self = shift;
532   #sort { $a->_date <=> $b->_date }
533   #  qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
534   #;
535 }
536
537 sub cust_pay_batch {
538   my $self = shift;
539   qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
540 }
541
542 sub cust_bill_pay_batch {
543   my $self = shift;
544   qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
545 }
546
547 =item cust_bill_pay
548
549 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
550
551 =cut
552
553 sub cust_bill_pay {
554   my $self = shift;
555   map { $_ } #return $self->num_cust_bill_pay unless wantarray;
556   sort { $a->_date <=> $b->_date }
557     qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
558 }
559
560 =item cust_credited
561
562 =item cust_credit_bill
563
564 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
565
566 =cut
567
568 sub cust_credited {
569   my $self = shift;
570   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
571   sort { $a->_date <=> $b->_date }
572     qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
573   ;
574 }
575
576 sub cust_credit_bill {
577   shift->cust_credited(@_);
578 }
579
580 =item cust_bill_pay_pkgnum PKGNUM
581
582 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
583 with matching pkgnum.
584
585 =cut
586
587 sub cust_bill_pay_pkgnum {
588   my( $self, $pkgnum ) = @_;
589   map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
590   sort { $a->_date <=> $b->_date }
591     qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
592                                 'pkgnum' => $pkgnum,
593                               }
594            );
595 }
596
597 =item cust_credited_pkgnum PKGNUM
598
599 =item cust_credit_bill_pkgnum PKGNUM
600
601 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
602 with matching pkgnum.
603
604 =cut
605
606 sub cust_credited_pkgnum {
607   my( $self, $pkgnum ) = @_;
608   map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
609   sort { $a->_date <=> $b->_date }
610     qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
611                                    'pkgnum' => $pkgnum,
612                                  }
613            );
614 }
615
616 sub cust_credit_bill_pkgnum {
617   shift->cust_credited_pkgnum(@_);
618 }
619
620 =item tax
621
622 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
623
624 =cut
625
626 sub tax {
627   my $self = shift;
628   my $total = 0;
629   my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
630                                              'pkgnum' => 0 } );
631   foreach (@taxlines) { $total += $_->setup; }
632   $total;
633 }
634
635 =item owed
636
637 Returns the amount owed (still outstanding) on this invoice, which is charged
638 minus all payment applications (see L<FS::cust_bill_pay>) and credit
639 applications (see L<FS::cust_credit_bill>).
640
641 =cut
642
643 sub owed {
644   my $self = shift;
645   my $balance = $self->charged;
646   $balance -= $_->amount foreach ( $self->cust_bill_pay );
647   $balance -= $_->amount foreach ( $self->cust_credited );
648   $balance = sprintf( "%.2f", $balance);
649   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
650   $balance;
651 }
652
653 sub owed_pkgnum {
654   my( $self, $pkgnum ) = @_;
655
656   #my $balance = $self->charged;
657   my $balance = 0;
658   $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
659
660   $balance -= $_->amount            for $self->cust_bill_pay_pkgnum($pkgnum);
661   $balance -= $_->amount            for $self->cust_credited_pkgnum($pkgnum);
662
663   $balance = sprintf( "%.2f", $balance);
664   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
665   $balance;
666 }
667
668 =item apply_payments_and_credits [ OPTION => VALUE ... ]
669
670 Applies unapplied payments and credits to this invoice.
671
672 A hash of optional arguments may be passed.  Currently "manual" is supported.
673 If true, a payment receipt is sent instead of a statement when
674 'payment_receipt_email' configuration option is set.
675
676 If there is an error, returns the error, otherwise returns false.
677
678 =cut
679
680 sub apply_payments_and_credits {
681   my( $self, %options ) = @_;
682
683   local $SIG{HUP} = 'IGNORE';
684   local $SIG{INT} = 'IGNORE';
685   local $SIG{QUIT} = 'IGNORE';
686   local $SIG{TERM} = 'IGNORE';
687   local $SIG{TSTP} = 'IGNORE';
688   local $SIG{PIPE} = 'IGNORE';
689
690   my $oldAutoCommit = $FS::UID::AutoCommit;
691   local $FS::UID::AutoCommit = 0;
692   my $dbh = dbh;
693
694   $self->select_for_update; #mutex
695
696   my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
697   my @credits  = grep { $_->credited > 0 } $self->cust_main->cust_credit;
698
699   if ( $conf->exists('pkg-balances') ) {
700     # limit @payments & @credits to those w/ a pkgnum grepped from $self
701     my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
702     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
703     @credits  = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
704   }
705
706   while ( $self->owed > 0 and ( @payments || @credits ) ) {
707
708     my $app = '';
709     if ( @payments && @credits ) {
710
711       #decide which goes first by weight of top (unapplied) line item
712
713       my @open_lineitems = $self->open_cust_bill_pkg;
714
715       my $max_pay_weight =
716         max( map  { $_->part_pkg->pay_weight || 0 }
717              grep { $_ }
718              map  { $_->cust_pkg }
719                   @open_lineitems
720            );
721       my $max_credit_weight =
722         max( map  { $_->part_pkg->credit_weight || 0 }
723              grep { $_ } 
724              map  { $_->cust_pkg }
725                   @open_lineitems
726            );
727
728       #if both are the same... payments first?  it has to be something
729       if ( $max_pay_weight >= $max_credit_weight ) {
730         $app = 'pay';
731       } else {
732         $app = 'credit';
733       }
734     
735     } elsif ( @payments ) {
736       $app = 'pay';
737     } elsif ( @credits ) {
738       $app = 'credit';
739     } else {
740       die "guru meditation #12 and 35";
741     }
742
743     my $unapp_amount;
744     if ( $app eq 'pay' ) {
745
746       my $payment = shift @payments;
747       $unapp_amount = $payment->unapplied;
748       $app = new FS::cust_bill_pay { 'paynum'  => $payment->paynum };
749       $app->pkgnum( $payment->pkgnum )
750         if $conf->exists('pkg-balances') && $payment->pkgnum;
751
752     } elsif ( $app eq 'credit' ) {
753
754       my $credit = shift @credits;
755       $unapp_amount = $credit->credited;
756       $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
757       $app->pkgnum( $credit->pkgnum )
758         if $conf->exists('pkg-balances') && $credit->pkgnum;
759
760     } else {
761       die "guru meditation #12 and 35";
762     }
763
764     my $owed;
765     if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
766       warn "owed_pkgnum ". $app->pkgnum;
767       $owed = $self->owed_pkgnum($app->pkgnum);
768     } else {
769       $owed = $self->owed;
770     }
771     next unless $owed > 0;
772
773     warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
774     $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
775
776     $app->invnum( $self->invnum );
777
778     my $error = $app->insert(%options);
779     if ( $error ) {
780       $dbh->rollback if $oldAutoCommit;
781       return "Error inserting ". $app->table. " record: $error";
782     }
783     die $error if $error;
784
785   }
786
787   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
788   ''; #no error
789
790 }
791
792 =item generate_email OPTION => VALUE ...
793
794 Options:
795
796 =over 4
797
798 =item from
799
800 sender address, required
801
802 =item tempate
803
804 alternate template name, optional
805
806 =item print_text
807
808 text attachment arrayref, optional
809
810 =item subject
811
812 email subject, optional
813
814 =item notice_name
815
816 notice name instead of "Invoice", optional
817
818 =back
819
820 Returns an argument list to be passed to L<FS::Misc::send_email>.
821
822 =cut
823
824 use MIME::Entity;
825
826 sub generate_email {
827
828   my $self = shift;
829   my %args = @_;
830
831   my $me = '[FS::cust_bill::generate_email]';
832
833   my %return = (
834     'from'      => $args{'from'},
835     'subject'   => (($args{'subject'}) ? $args{'subject'} : 'Invoice'),
836   );
837
838   my %opt = (
839     'unsquelch_cdr' => $conf->exists('voip-cdr_email'),
840     'template'      => $args{'template'},
841     'notice_name'   => ( $args{'notice_name'} || 'Invoice' ),
842   );
843
844   my $cust_main = $self->cust_main;
845
846   if (ref($args{'to'}) eq 'ARRAY') {
847     $return{'to'} = $args{'to'};
848   } else {
849     $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
850                            $cust_main->invoicing_list
851                     ];
852   }
853
854   if ( $conf->exists('invoice_html') ) {
855
856     warn "$me creating HTML/text multipart message"
857       if $DEBUG;
858
859     $return{'nobody'} = 1;
860
861     my $alternative = build MIME::Entity
862       'Type'        => 'multipart/alternative',
863       'Encoding'    => '7bit',
864       'Disposition' => 'inline'
865     ;
866
867     my $data;
868     if ( $conf->exists('invoice_email_pdf')
869          and scalar($conf->config('invoice_email_pdf_note')) ) {
870
871       warn "$me using 'invoice_email_pdf_note' in multipart message"
872         if $DEBUG;
873       $data = [ map { $_ . "\n" }
874                     $conf->config('invoice_email_pdf_note')
875               ];
876
877     } else {
878
879       warn "$me not using 'invoice_email_pdf_note' in multipart message"
880         if $DEBUG;
881       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
882         $data = $args{'print_text'};
883       } else {
884         $data = [ $self->print_text(\%opt) ];
885       }
886
887     }
888
889     $alternative->attach(
890       'Type'        => 'text/plain',
891       #'Encoding'    => 'quoted-printable',
892       'Encoding'    => '7bit',
893       'Data'        => $data,
894       'Disposition' => 'inline',
895     );
896
897     $args{'from'} =~ /\@([\w\.\-]+)/;
898     my $from = $1 || 'example.com';
899     my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
900
901     my $logo;
902     my $agentnum = $cust_main->agentnum;
903     if ( defined($args{'template'}) && length($args{'template'})
904          && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
905        )
906     {
907       $logo = 'logo_'. $args{'template'}. '.png';
908     } else {
909       $logo = "logo.png";
910     }
911     my $image_data = $conf->config_binary( $logo, $agentnum);
912
913     my $image = build MIME::Entity
914       'Type'       => 'image/png',
915       'Encoding'   => 'base64',
916       'Data'       => $image_data,
917       'Filename'   => 'logo.png',
918       'Content-ID' => "<$content_id>",
919     ;
920
921     $alternative->attach(
922       'Type'        => 'text/html',
923       'Encoding'    => 'quoted-printable',
924       'Data'        => [ '<html>',
925                          '  <head>',
926                          '    <title>',
927                          '      '. encode_entities($return{'subject'}), 
928                          '    </title>',
929                          '  </head>',
930                          '  <body bgcolor="#e8e8e8">',
931                          $self->print_html({ 'cid'=>$content_id, %opt }),
932                          '  </body>',
933                          '</html>',
934                        ],
935       'Disposition' => 'inline',
936       #'Filename'    => 'invoice.pdf',
937     );
938
939     my @otherparts = ();
940     if ( $cust_main->email_csv_cdr ) {
941
942       push @otherparts, build MIME::Entity
943         'Type'        => 'text/csv',
944         'Encoding'    => '7bit',
945         'Data'        => [ map { "$_\n" }
946                              $self->call_details('prepend_billed_number' => 1)
947                          ],
948         'Disposition' => 'attachment',
949         'Filename'    => 'usage-'. $self->invnum. '.csv',
950       ;
951
952     }
953
954     if ( $conf->exists('invoice_email_pdf') ) {
955
956       #attaching pdf too:
957       # multipart/mixed
958       #   multipart/related
959       #     multipart/alternative
960       #       text/plain
961       #       text/html
962       #     image/png
963       #   application/pdf
964
965       my $related = build MIME::Entity 'Type'     => 'multipart/related',
966                                        'Encoding' => '7bit';
967
968       #false laziness w/Misc::send_email
969       $related->head->replace('Content-type',
970         $related->mime_type.
971         '; boundary="'. $related->head->multipart_boundary. '"'.
972         '; type=multipart/alternative'
973       );
974
975       $related->add_part($alternative);
976
977       $related->add_part($image);
978
979       my $pdf = build MIME::Entity $self->mimebuild_pdf(\%opt);
980
981       $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
982
983     } else {
984
985       #no other attachment:
986       # multipart/related
987       #   multipart/alternative
988       #     text/plain
989       #     text/html
990       #   image/png
991
992       $return{'content-type'} = 'multipart/related';
993       $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
994       $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
995       #$return{'disposition'} = 'inline';
996
997     }
998   
999   } else {
1000
1001     if ( $conf->exists('invoice_email_pdf') ) {
1002       warn "$me creating PDF attachment"
1003         if $DEBUG;
1004
1005       #mime parts arguments a la MIME::Entity->build().
1006       $return{'mimeparts'} = [
1007         { $self->mimebuild_pdf(\%opt) }
1008       ];
1009     }
1010   
1011     if ( $conf->exists('invoice_email_pdf')
1012          and scalar($conf->config('invoice_email_pdf_note')) ) {
1013
1014       warn "$me using 'invoice_email_pdf_note'"
1015         if $DEBUG;
1016       $return{'body'} = [ map { $_ . "\n" }
1017                               $conf->config('invoice_email_pdf_note')
1018                         ];
1019
1020     } else {
1021
1022       warn "$me not using 'invoice_email_pdf_note'"
1023         if $DEBUG;
1024       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1025         $return{'body'} = $args{'print_text'};
1026       } else {
1027         $return{'body'} = [ $self->print_text(\%opt) ];
1028       }
1029
1030     }
1031
1032   }
1033
1034   %return;
1035
1036 }
1037
1038 =item mimebuild_pdf
1039
1040 Returns a list suitable for passing to MIME::Entity->build(), representing
1041 this invoice as PDF attachment.
1042
1043 =cut
1044
1045 sub mimebuild_pdf {
1046   my $self = shift;
1047   (
1048     'Type'        => 'application/pdf',
1049     'Encoding'    => 'base64',
1050     'Data'        => [ $self->print_pdf(@_) ],
1051     'Disposition' => 'attachment',
1052     'Filename'    => 'invoice-'. $self->invnum. '.pdf',
1053   );
1054 }
1055
1056 =item send HASHREF | [ TEMPLATE [ , AGENTNUM [ , INVOICE_FROM [ , AMOUNT ] ] ] ]
1057
1058 Sends this invoice to the destinations configured for this customer: sends
1059 email, prints and/or faxes.  See L<FS::cust_main_invoice>.
1060
1061 Options can be passed as a hashref (recommended) or as a list of up to 
1062 four values for templatename, agentnum, invoice_from and amount.
1063
1064 I<template>, if specified, is the name of a suffix for alternate invoices.
1065
1066 I<agentnum>, if specified, means that this invoice will only be sent for customers
1067 of the specified agent or agent(s).  AGENTNUM can be a scalar agentnum (for a
1068 single agent) or an arrayref of agentnums.
1069
1070 I<invoice_from>, if specified, overrides the default email invoice From: address.
1071
1072 I<amount>, if specified, only sends the invoice if the total amount owed on this
1073 invoice and all older invoices is greater than the specified amount.
1074
1075 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1076
1077 =cut
1078
1079 sub queueable_send {
1080   my %opt = @_;
1081
1082   my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1083     or die "invalid invoice number: " . $opt{invnum};
1084
1085   my @args = ( $opt{template}, $opt{agentnum} );
1086   push @args, $opt{invoice_from}
1087     if exists($opt{invoice_from}) && $opt{invoice_from};
1088
1089   my $error = $self->send( @args );
1090   die $error if $error;
1091
1092 }
1093
1094 sub send {
1095   my $self = shift;
1096
1097   my( $template, $invoice_from, $notice_name );
1098   my $agentnums = '';
1099   my $balance_over = 0;
1100
1101   if ( ref($_[0]) ) {
1102     my $opt = shift;
1103     $template = $opt->{'template'} || '';
1104     if ( $agentnums = $opt->{'agentnum'} ) {
1105       $agentnums = [ $agentnums ] unless ref($agentnums);
1106     }
1107     $invoice_from = $opt->{'invoice_from'};
1108     $balance_over = $opt->{'balance_over'} if $opt->{'balance_over'};
1109     $notice_name = $opt->{'notice_name'};
1110   } else {
1111     $template = scalar(@_) ? shift : '';
1112     if ( scalar(@_) && $_[0]  ) {
1113       $agentnums = ref($_[0]) ? shift : [ shift ];
1114     }
1115     $invoice_from = shift if scalar(@_);
1116     $balance_over = shift if scalar(@_) && $_[0] !~ /^\s*$/;
1117   }
1118
1119   return 'N/A' unless ! $agentnums
1120                    or grep { $_ == $self->cust_main->agentnum } @$agentnums;
1121
1122   return ''
1123     unless $self->cust_main->total_owed_date($self->_date) > $balance_over;
1124
1125   $invoice_from ||= $self->_agent_invoice_from ||    #XXX should go away
1126                     $conf->config('invoice_from', $self->cust_main->agentnum );
1127
1128   my %opt = (
1129     'template'     => $template,
1130     'invoice_from' => $invoice_from,
1131     'notice_name'  => ( $notice_name || 'Invoice' ),
1132   );
1133
1134   my @invoicing_list = $self->cust_main->invoicing_list;
1135
1136   #$self->email_invoice(\%opt)
1137   $self->email(\%opt)
1138     if grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list;
1139
1140   #$self->print_invoice(\%opt)
1141   $self->print(\%opt)
1142     if grep { $_ eq 'POST' } @invoicing_list; #postal
1143
1144   $self->fax_invoice(\%opt)
1145     if grep { $_ eq 'FAX' } @invoicing_list; #fax
1146
1147   '';
1148
1149 }
1150
1151 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ] 
1152
1153 Emails this invoice.
1154
1155 Options can be passed as a hashref (recommended) or as a list of up to 
1156 two values for templatename and invoice_from.
1157
1158 I<template>, if specified, is the name of a suffix for alternate invoices.
1159
1160 I<invoice_from>, if specified, overrides the default email invoice From: address.
1161
1162 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1163
1164 =cut
1165
1166 sub queueable_email {
1167   my %opt = @_;
1168
1169   my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1170     or die "invalid invoice number: " . $opt{invnum};
1171
1172   my @args = ( $opt{template} );
1173   push @args, $opt{invoice_from}
1174     if exists($opt{invoice_from}) && $opt{invoice_from};
1175
1176   my $error = $self->email( @args );
1177   die $error if $error;
1178
1179 }
1180
1181 #sub email_invoice {
1182 sub email {
1183   my $self = shift;
1184
1185   my( $template, $invoice_from, $notice_name );
1186   if ( ref($_[0]) ) {
1187     my $opt = shift;
1188     $template = $opt->{'template'} || '';
1189     $invoice_from = $opt->{'invoice_from'};
1190     $notice_name = $opt->{'notice_name'} || 'Invoice';
1191   } else {
1192     $template = scalar(@_) ? shift : '';
1193     $invoice_from = shift if scalar(@_);
1194     $notice_name = 'Invoice';
1195   }
1196
1197   $invoice_from ||= $self->_agent_invoice_from ||    #XXX should go away
1198                     $conf->config('invoice_from', $self->cust_main->agentnum );
1199
1200   my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } 
1201                             $self->cust_main->invoicing_list;
1202
1203   #better to notify this person than silence
1204   @invoicing_list = ($invoice_from) unless @invoicing_list;
1205
1206   my $subject = $self->email_subject($template);
1207
1208   my $error = send_email(
1209     $self->generate_email(
1210       'from'        => $invoice_from,
1211       'to'          => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1212       'subject'     => $subject,
1213       'template'    => $template,
1214       'notice_name' => $notice_name,
1215     )
1216   );
1217   die "can't email invoice: $error\n" if $error;
1218   #die "$error\n" if $error;
1219
1220 }
1221
1222 sub email_subject {
1223   my $self = shift;
1224
1225   #my $template = scalar(@_) ? shift : '';
1226   #per-template?
1227
1228   my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1229                 || 'Invoice';
1230
1231   my $cust_main = $self->cust_main;
1232   my $name = $cust_main->name;
1233   my $name_short = $cust_main->name_short;
1234   my $invoice_number = $self->invnum;
1235   my $invoice_date = $self->_date_pretty;
1236
1237   eval qq("$subject");
1238 }
1239
1240 =item lpr_data HASHREF | [ TEMPLATE ]
1241
1242 Returns the postscript or plaintext for this invoice as an arrayref.
1243
1244 Options can be passed as a hashref (recommended) or as a single optional value
1245 for template.
1246
1247 I<template>, if specified, is the name of a suffix for alternate invoices.
1248
1249 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1250
1251 =cut
1252
1253 sub lpr_data {
1254   my $self = shift;
1255   my( $template, $notice_name );
1256   if ( ref($_[0]) ) {
1257     my $opt = shift;
1258     $template = $opt->{'template'} || '';
1259     $notice_name = $opt->{'notice_name'} || 'Invoice';
1260   } else {
1261     $template = scalar(@_) ? shift : '';
1262     $notice_name = 'Invoice';
1263   }
1264
1265   my %opt = (
1266     'template'    => $template,
1267     'notice_name' => $notice_name,
1268   );
1269
1270   my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1271   [ $self->$method( \%opt ) ];
1272 }
1273
1274 =item print HASHREF | [ TEMPLATE ]
1275
1276 Prints this invoice.
1277
1278 Options can be passed as a hashref (recommended) or as a single optional
1279 value for template.
1280
1281 I<template>, if specified, is the name of a suffix for alternate invoices.
1282
1283 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1284
1285 =cut
1286
1287 #sub print_invoice {
1288 sub print {
1289   my $self = shift;
1290   my( $template, $notice_name );
1291   if ( ref($_[0]) ) {
1292     my $opt = shift;
1293     $template = $opt->{'template'} || '';
1294     $notice_name = $opt->{'notice_name'} || 'Invoice';
1295   } else {
1296     $template = scalar(@_) ? shift : '';
1297     $notice_name = 'Invoice';
1298   }
1299
1300   my %opt = (
1301     'template'    => $template,
1302     'notice_name' => $notice_name,
1303   );
1304
1305   if($conf->exists('invoice_print_pdf')) {
1306     # Add the invoice to the current batch.
1307     $self->batch_invoice(\%opt);
1308   }
1309   else {
1310     do_print $self->lpr_data(\%opt);
1311   }
1312 }
1313
1314 =item fax_invoice HASHREF | [ TEMPLATE ] 
1315
1316 Faxes this invoice.
1317
1318 Options can be passed as a hashref (recommended) or as a single optional
1319 value for template.
1320
1321 I<template>, if specified, is the name of a suffix for alternate invoices.
1322
1323 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1324
1325 =cut
1326
1327 sub fax_invoice {
1328   my $self = shift;
1329   my( $template, $notice_name );
1330   if ( ref($_[0]) ) {
1331     my $opt = shift;
1332     $template = $opt->{'template'} || '';
1333     $notice_name = $opt->{'notice_name'} || 'Invoice';
1334   } else {
1335     $template = scalar(@_) ? shift : '';
1336     $notice_name = 'Invoice';
1337   }
1338
1339   die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1340     unless $conf->exists('invoice_latex');
1341
1342   my $dialstring = $self->cust_main->getfield('fax');
1343   #Check $dialstring?
1344
1345   my %opt = (
1346     'template'    => $template,
1347     'notice_name' => $notice_name,
1348   );
1349
1350   my $error = send_fax( 'docdata'    => $self->lpr_data(\%opt),
1351                         'dialstring' => $dialstring,
1352                       );
1353   die $error if $error;
1354
1355 }
1356
1357 =item batch_invoice [ HASHREF ]
1358
1359 Place this invoice into the open batch (see C<FS::bill_batch>).  If there 
1360 isn't an open batch, one will be created.
1361
1362 =cut
1363
1364 sub batch_invoice {
1365   my ($self, $opt) = @_;
1366   my $batch = FS::bill_batch->get_open_batch;
1367   my $cust_bill_batch = FS::cust_bill_batch->new({
1368       batchnum => $batch->batchnum,
1369       invnum   => $self->invnum,
1370   });
1371   return $cust_bill_batch->insert($opt);
1372 }
1373
1374 =item ftp_invoice [ TEMPLATENAME ] 
1375
1376 Sends this invoice data via FTP.
1377
1378 TEMPLATENAME is unused?
1379
1380 =cut
1381
1382 sub ftp_invoice {
1383   my $self = shift;
1384   my $template = scalar(@_) ? shift : '';
1385
1386   $self->send_csv(
1387     'protocol'   => 'ftp',
1388     'server'     => $conf->config('cust_bill-ftpserver'),
1389     'username'   => $conf->config('cust_bill-ftpusername'),
1390     'password'   => $conf->config('cust_bill-ftppassword'),
1391     'dir'        => $conf->config('cust_bill-ftpdir'),
1392     'format'     => $conf->config('cust_bill-ftpformat'),
1393   );
1394 }
1395
1396 =item spool_invoice [ TEMPLATENAME ] 
1397
1398 Spools this invoice data (see L<FS::spool_csv>)
1399
1400 TEMPLATENAME is unused?
1401
1402 =cut
1403
1404 sub spool_invoice {
1405   my $self = shift;
1406   my $template = scalar(@_) ? shift : '';
1407
1408   $self->spool_csv(
1409     'format'       => $conf->config('cust_bill-spoolformat'),
1410     'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1411   );
1412 }
1413
1414 =item send_if_newest [ TEMPLATENAME [ , AGENTNUM [ , INVOICE_FROM ] ] ]
1415
1416 Like B<send>, but only sends the invoice if it is the newest open invoice for
1417 this customer.
1418
1419 =cut
1420
1421 sub send_if_newest {
1422   my $self = shift;
1423
1424   return ''
1425     if scalar(
1426                grep { $_->owed > 0 } 
1427                     qsearch('cust_bill', {
1428                       'custnum' => $self->custnum,
1429                       #'_date'   => { op=>'>', value=>$self->_date },
1430                       'invnum'  => { op=>'>', value=>$self->invnum },
1431                     } )
1432              );
1433     
1434   $self->send(@_);
1435 }
1436
1437 =item send_csv OPTION => VALUE, ...
1438
1439 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1440
1441 Options are:
1442
1443 protocol - currently only "ftp"
1444 server
1445 username
1446 password
1447 dir
1448
1449 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1450 and YYMMDDHHMMSS is a timestamp.
1451
1452 See L</print_csv> for a description of the output format.
1453
1454 =cut
1455
1456 sub send_csv {
1457   my($self, %opt) = @_;
1458
1459   #create file(s)
1460
1461   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1462   mkdir $spooldir, 0700 unless -d $spooldir;
1463
1464   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1465   my $file = "$spooldir/$tracctnum.csv";
1466   
1467   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1468
1469   open(CSV, ">$file") or die "can't open $file: $!";
1470   print CSV $header;
1471
1472   print CSV $detail;
1473
1474   close CSV;
1475
1476   my $net;
1477   if ( $opt{protocol} eq 'ftp' ) {
1478     eval "use Net::FTP;";
1479     die $@ if $@;
1480     $net = Net::FTP->new($opt{server}) or die @$;
1481   } else {
1482     die "unknown protocol: $opt{protocol}";
1483   }
1484
1485   $net->login( $opt{username}, $opt{password} )
1486     or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1487
1488   $net->binary or die "can't set binary mode";
1489
1490   $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1491
1492   $net->put($file) or die "can't put $file: $!";
1493
1494   $net->quit;
1495
1496   unlink $file;
1497
1498 }
1499
1500 =item spool_csv
1501
1502 Spools CSV invoice data.
1503
1504 Options are:
1505
1506 =over 4
1507
1508 =item format - 'default' or 'billco'
1509
1510 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the customer has the corresponding invoice destinations set (see L<FS::cust_main_invoice>).
1511
1512 =item agent_spools - if set to a true value, will spool to per-agent files rather than a single global file
1513
1514 =item balanceover - if set, only spools the invoice if the total amount owed on this invoice and all older invoices is greater than the specified amount.
1515
1516 =back
1517
1518 =cut
1519
1520 sub spool_csv {
1521   my($self, %opt) = @_;
1522
1523   my $cust_main = $self->cust_main;
1524
1525   if ( $opt{'dest'} ) {
1526     my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1527                              $cust_main->invoicing_list;
1528     return 'N/A' unless $invoicing_list{$opt{'dest'}}
1529                      || ! keys %invoicing_list;
1530   }
1531
1532   if ( $opt{'balanceover'} ) {
1533     return 'N/A'
1534       if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1535   }
1536
1537   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1538   mkdir $spooldir, 0700 unless -d $spooldir;
1539
1540   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1541
1542   my $file =
1543     "$spooldir/".
1544     ( $opt{'agent_spools'} ? 'agentnum'.$cust_main->agentnum : 'spool' ).
1545     ( lc($opt{'format'}) eq 'billco' ? '-header' : '' ) .
1546     '.csv';
1547   
1548   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1549
1550   open(CSV, ">>$file") or die "can't open $file: $!";
1551   flock(CSV, LOCK_EX);
1552   seek(CSV, 0, 2);
1553
1554   print CSV $header;
1555
1556   if ( lc($opt{'format'}) eq 'billco' ) {
1557
1558     flock(CSV, LOCK_UN);
1559     close CSV;
1560
1561     $file =
1562       "$spooldir/".
1563       ( $opt{'agent_spools'} ? 'agentnum'.$cust_main->agentnum : 'spool' ).
1564       '-detail.csv';
1565
1566     open(CSV,">>$file") or die "can't open $file: $!";
1567     flock(CSV, LOCK_EX);
1568     seek(CSV, 0, 2);
1569   }
1570
1571   print CSV $detail;
1572
1573   flock(CSV, LOCK_UN);
1574   close CSV;
1575
1576   return '';
1577
1578 }
1579
1580 =item print_csv OPTION => VALUE, ...
1581
1582 Returns CSV data for this invoice.
1583
1584 Options are:
1585
1586 format - 'default' or 'billco'
1587
1588 Returns a list consisting of two scalars.  The first is a single line of CSV
1589 header information for this invoice.  The second is one or more lines of CSV
1590 detail information for this invoice.
1591
1592 If I<format> is not specified or "default", the fields of the CSV file are as
1593 follows:
1594
1595 record_type, invnum, custnum, _date, charged, first, last, company, address1, address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1596
1597 =over 4
1598
1599 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1600
1601 B<record_type> is C<cust_bill> for the initial header line only.  The
1602 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1603 fields are filled in.
1604
1605 B<record_type> is C<cust_bill_pkg> for detail lines.  Only the first two fields
1606 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1607 are filled in.
1608
1609 =item invnum - invoice number
1610
1611 =item custnum - customer number
1612
1613 =item _date - invoice date
1614
1615 =item charged - total invoice amount
1616
1617 =item first - customer first name
1618
1619 =item last - customer first name
1620
1621 =item company - company name
1622
1623 =item address1 - address line 1
1624
1625 =item address2 - address line 1
1626
1627 =item city
1628
1629 =item state
1630
1631 =item zip
1632
1633 =item country
1634
1635 =item pkg - line item description
1636
1637 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1638
1639 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1640
1641 =item sdate - start date for recurring fee
1642
1643 =item edate - end date for recurring fee
1644
1645 =back
1646
1647 If I<format> is "billco", the fields of the header CSV file are as follows:
1648
1649   +-------------------------------------------------------------------+
1650   |                        FORMAT HEADER FILE                         |
1651   |-------------------------------------------------------------------|
1652   | Field | Description                   | Name       | Type | Width |
1653   | 1     | N/A-Leave Empty               | RC         | CHAR |     2 |
1654   | 2     | N/A-Leave Empty               | CUSTID     | CHAR |    15 |
1655   | 3     | Transaction Account No        | TRACCTNUM  | CHAR |    15 |
1656   | 4     | Transaction Invoice No        | TRINVOICE  | CHAR |    15 |
1657   | 5     | Transaction Zip Code          | TRZIP      | CHAR |     5 |
1658   | 6     | Transaction Company Bill To   | TRCOMPANY  | CHAR |    30 |
1659   | 7     | Transaction Contact Bill To   | TRNAME     | CHAR |    30 |
1660   | 8     | Additional Address Unit Info  | TRADDR1    | CHAR |    30 |
1661   | 9     | Bill To Street Address        | TRADDR2    | CHAR |    30 |
1662   | 10    | Ancillary Billing Information | TRADDR3    | CHAR |    30 |
1663   | 11    | Transaction City Bill To      | TRCITY     | CHAR |    20 |
1664   | 12    | Transaction State Bill To     | TRSTATE    | CHAR |     2 |
1665   | 13    | Bill Cycle Close Date         | CLOSEDATE  | CHAR |    10 |
1666   | 14    | Bill Due Date                 | DUEDATE    | CHAR |    10 |
1667   | 15    | Previous Balance              | BALFWD     | NUM* |     9 |
1668   | 16    | Pmt/CR Applied                | CREDAPPLY  | NUM* |     9 |
1669   | 17    | Total Current Charges         | CURRENTCHG | NUM* |     9 |
1670   | 18    | Total Amt Due                 | TOTALDUE   | NUM* |     9 |
1671   | 19    | Total Amt Due                 | AMTDUE     | NUM* |     9 |
1672   | 20    | 30 Day Aging                  | AMT30      | NUM* |     9 |
1673   | 21    | 60 Day Aging                  | AMT60      | NUM* |     9 |
1674   | 22    | 90 Day Aging                  | AMT90      | NUM* |     9 |
1675   | 23    | Y/N                           | AGESWITCH  | CHAR |     1 |
1676   | 24    | Remittance automation         | SCANLINE   | CHAR |   100 |
1677   | 25    | Total Taxes & Fees            | TAXTOT     | NUM* |     9 |
1678   | 26    | Customer Reference Number     | CUSTREF    | CHAR |    15 |
1679   | 27    | Federal Tax***                | FEDTAX     | NUM* |     9 |
1680   | 28    | State Tax***                  | STATETAX   | NUM* |     9 |
1681   | 29    | Other Taxes & Fees***         | OTHERTAX   | NUM* |     9 |
1682   +-------+-------------------------------+------------+------+-------+
1683
1684 If I<format> is "billco", the fields of the detail CSV file are as follows:
1685
1686                                   FORMAT FOR DETAIL FILE
1687         |                            |           |      |
1688   Field | Description                | Name      | Type | Width
1689   1     | N/A-Leave Empty            | RC        | CHAR |     2
1690   2     | N/A-Leave Empty            | CUSTID    | CHAR |    15
1691   3     | Account Number             | TRACCTNUM | CHAR |    15
1692   4     | Invoice Number             | TRINVOICE | CHAR |    15
1693   5     | Line Sequence (sort order) | LINESEQ   | NUM  |     6
1694   6     | Transaction Detail         | DETAILS   | CHAR |   100
1695   7     | Amount                     | AMT       | NUM* |     9
1696   8     | Line Format Control**      | LNCTRL    | CHAR |     2
1697   9     | Grouping Code              | GROUP     | CHAR |     2
1698   10    | User Defined               | ACCT CODE | CHAR |    15
1699
1700 =cut
1701
1702 sub print_csv {
1703   my($self, %opt) = @_;
1704   
1705   eval "use Text::CSV_XS";
1706   die $@ if $@;
1707
1708   my $cust_main = $self->cust_main;
1709
1710   my $csv = Text::CSV_XS->new({'always_quote'=>1});
1711
1712   if ( lc($opt{'format'}) eq 'billco' ) {
1713
1714     my $taxtotal = 0;
1715     $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1716
1717     my $duedate = $self->due_date2str('%m/%d/%Y'); #date_format?
1718
1719     my( $previous_balance, @unused ) = $self->previous; #previous balance
1720
1721     my $pmt_cr_applied = 0;
1722     $pmt_cr_applied += $_->{'amount'}
1723       foreach ( $self->_items_payments, $self->_items_credits ) ;
1724
1725     my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1726
1727     $csv->combine(
1728       '',                         #  1 | N/A-Leave Empty               CHAR   2
1729       '',                         #  2 | N/A-Leave Empty               CHAR  15
1730       $opt{'tracctnum'},          #  3 | Transaction Account No        CHAR  15
1731       $self->invnum,              #  4 | Transaction Invoice No        CHAR  15
1732       $cust_main->zip,            #  5 | Transaction Zip Code          CHAR   5
1733       $cust_main->company,        #  6 | Transaction Company Bill To   CHAR  30
1734       #$cust_main->payname,        #  7 | Transaction Contact Bill To   CHAR  30
1735       $cust_main->contact,        #  7 | Transaction Contact Bill To   CHAR  30
1736       $cust_main->address2,       #  8 | Additional Address Unit Info  CHAR  30
1737       $cust_main->address1,       #  9 | Bill To Street Address        CHAR  30
1738       '',                         # 10 | Ancillary Billing Information CHAR  30
1739       $cust_main->city,           # 11 | Transaction City Bill To      CHAR  20
1740       $cust_main->state,          # 12 | Transaction State Bill To     CHAR   2
1741
1742       # XXX ?
1743       time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR  10
1744
1745       # XXX ?
1746       $duedate,                   # 14 | Bill Due Date                 CHAR  10
1747
1748       $previous_balance,          # 15 | Previous Balance              NUM*   9
1749       $pmt_cr_applied,            # 16 | Pmt/CR Applied                NUM*   9
1750       sprintf("%.2f", $self->charged), # 17 | Total Current Charges    NUM*   9
1751       $totaldue,                  # 18 | Total Amt Due                 NUM*   9
1752       $totaldue,                  # 19 | Total Amt Due                 NUM*   9
1753       '',                         # 20 | 30 Day Aging                  NUM*   9
1754       '',                         # 21 | 60 Day Aging                  NUM*   9
1755       '',                         # 22 | 90 Day Aging                  NUM*   9
1756       'N',                        # 23 | Y/N                           CHAR   1
1757       '',                         # 24 | Remittance automation         CHAR 100
1758       $taxtotal,                  # 25 | Total Taxes & Fees            NUM*   9
1759       $self->custnum,             # 26 | Customer Reference Number     CHAR  15
1760       '0',                        # 27 | Federal Tax***                NUM*   9
1761       sprintf("%.2f", $taxtotal), # 28 | State Tax***                  NUM*   9
1762       '0',                        # 29 | Other Taxes & Fees***         NUM*   9
1763     );
1764
1765   } else {
1766   
1767     $csv->combine(
1768       'cust_bill',
1769       $self->invnum,
1770       $self->custnum,
1771       time2str("%x", $self->_date),
1772       sprintf("%.2f", $self->charged),
1773       ( map { $cust_main->getfield($_) }
1774           qw( first last company address1 address2 city state zip country ) ),
1775       map { '' } (1..5),
1776     ) or die "can't create csv";
1777   }
1778
1779   my $header = $csv->string. "\n";
1780
1781   my $detail = '';
1782   if ( lc($opt{'format'}) eq 'billco' ) {
1783
1784     my $lineseq = 0;
1785     foreach my $item ( $self->_items_pkg ) {
1786
1787       $csv->combine(
1788         '',                     #  1 | N/A-Leave Empty            CHAR   2
1789         '',                     #  2 | N/A-Leave Empty            CHAR  15
1790         $opt{'tracctnum'},      #  3 | Account Number             CHAR  15
1791         $self->invnum,          #  4 | Invoice Number             CHAR  15
1792         $lineseq++,             #  5 | Line Sequence (sort order) NUM    6
1793         $item->{'description'}, #  6 | Transaction Detail         CHAR 100
1794         $item->{'amount'},      #  7 | Amount                     NUM*   9
1795         '',                     #  8 | Line Format Control**      CHAR   2
1796         '',                     #  9 | Grouping Code              CHAR   2
1797         '',                     # 10 | User Defined               CHAR  15
1798       );
1799
1800       $detail .= $csv->string. "\n";
1801
1802     }
1803
1804   } else {
1805
1806     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1807
1808       my($pkg, $setup, $recur, $sdate, $edate);
1809       if ( $cust_bill_pkg->pkgnum ) {
1810       
1811         ($pkg, $setup, $recur, $sdate, $edate) = (
1812           $cust_bill_pkg->part_pkg->pkg,
1813           ( $cust_bill_pkg->setup != 0
1814             ? sprintf("%.2f", $cust_bill_pkg->setup )
1815             : '' ),
1816           ( $cust_bill_pkg->recur != 0
1817             ? sprintf("%.2f", $cust_bill_pkg->recur )
1818             : '' ),
1819           ( $cust_bill_pkg->sdate 
1820             ? time2str("%x", $cust_bill_pkg->sdate)
1821             : '' ),
1822           ($cust_bill_pkg->edate 
1823             ?time2str("%x", $cust_bill_pkg->edate)
1824             : '' ),
1825         );
1826   
1827       } else { #pkgnum tax
1828         next unless $cust_bill_pkg->setup != 0;
1829         $pkg = $cust_bill_pkg->desc;
1830         $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
1831         ( $sdate, $edate ) = ( '', '' );
1832       }
1833   
1834       $csv->combine(
1835         'cust_bill_pkg',
1836         $self->invnum,
1837         ( map { '' } (1..11) ),
1838         ($pkg, $setup, $recur, $sdate, $edate)
1839       ) or die "can't create csv";
1840
1841       $detail .= $csv->string. "\n";
1842
1843     }
1844
1845   }
1846
1847   ( $header, $detail );
1848
1849 }
1850
1851 =item comp
1852
1853 Pays this invoice with a compliemntary payment.  If there is an error,
1854 returns the error, otherwise returns false.
1855
1856 =cut
1857
1858 sub comp {
1859   my $self = shift;
1860   my $cust_pay = new FS::cust_pay ( {
1861     'invnum'   => $self->invnum,
1862     'paid'     => $self->owed,
1863     '_date'    => '',
1864     'payby'    => 'COMP',
1865     'payinfo'  => $self->cust_main->payinfo,
1866     'paybatch' => '',
1867   } );
1868   $cust_pay->insert;
1869 }
1870
1871 =item realtime_card
1872
1873 Attempts to pay this invoice with a credit card payment via a
1874 Business::OnlinePayment realtime gateway.  See
1875 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1876 for supported processors.
1877
1878 =cut
1879
1880 sub realtime_card {
1881   my $self = shift;
1882   $self->realtime_bop( 'CC', @_ );
1883 }
1884
1885 =item realtime_ach
1886
1887 Attempts to pay this invoice with an electronic check (ACH) payment via a
1888 Business::OnlinePayment realtime gateway.  See
1889 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1890 for supported processors.
1891
1892 =cut
1893
1894 sub realtime_ach {
1895   my $self = shift;
1896   $self->realtime_bop( 'ECHECK', @_ );
1897 }
1898
1899 =item realtime_lec
1900
1901 Attempts to pay this invoice with phone bill (LEC) payment via a
1902 Business::OnlinePayment realtime gateway.  See
1903 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1904 for supported processors.
1905
1906 =cut
1907
1908 sub realtime_lec {
1909   my $self = shift;
1910   $self->realtime_bop( 'LEC', @_ );
1911 }
1912
1913 sub realtime_bop {
1914   my( $self, $method ) = @_;
1915
1916   my $cust_main = $self->cust_main;
1917   my $balance = $cust_main->balance;
1918   my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
1919   $amount = sprintf("%.2f", $amount);
1920   return "not run (balance $balance)" unless $amount > 0;
1921
1922   my $description = 'Internet Services';
1923   if ( $conf->exists('business-onlinepayment-description') ) {
1924     my $dtempl = $conf->config('business-onlinepayment-description');
1925
1926     my $agent_obj = $cust_main->agent
1927       or die "can't retreive agent for $cust_main (agentnum ".
1928              $cust_main->agentnum. ")";
1929     my $agent = $agent_obj->agent;
1930     my $pkgs = join(', ',
1931       map { $_->part_pkg->pkg }
1932         grep { $_->pkgnum } $self->cust_bill_pkg
1933     );
1934     $description = eval qq("$dtempl");
1935   }
1936
1937   $cust_main->realtime_bop($method, $amount,
1938     'description' => $description,
1939     'invnum'      => $self->invnum,
1940 #this didn't do what we want, it just calls apply_payments_and_credits
1941 #    'apply'       => 1,
1942     'apply_to_invoice' => 1,
1943  #what we want:
1944  #this changes application behavior: auto payments
1945                         #triggered against a specific invoice are now applied
1946                         #to that invoice instead of oldest open.
1947                         #seem okay to me...
1948   );
1949
1950 }
1951
1952 =item batch_card OPTION => VALUE...
1953
1954 Adds a payment for this invoice to the pending credit card batch (see
1955 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
1956 runs the payment using a realtime gateway.
1957
1958 =cut
1959
1960 sub batch_card {
1961   my ($self, %options) = @_;
1962   my $cust_main = $self->cust_main;
1963
1964   $options{invnum} = $self->invnum;
1965   
1966   $cust_main->batch_card(%options);
1967 }
1968
1969 sub _agent_template {
1970   my $self = shift;
1971   $self->cust_main->agent_template;
1972 }
1973
1974 sub _agent_invoice_from {
1975   my $self = shift;
1976   $self->cust_main->agent_invoice_from;
1977 }
1978
1979 =item print_text HASHREF | [ TIME [ , TEMPLATE [ , OPTION => VALUE ... ] ] ]
1980
1981 Returns an text invoice, as a list of lines.
1982
1983 Options can be passed as a hashref (recommended) or as a list of time, template
1984 and then any key/value pairs for any other options.
1985
1986 I<time>, if specified, is used to control the printing of overdue messages.  The
1987 default is now.  It isn't the date of the invoice; that's the `_date' field.
1988 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1989 L<Time::Local> and L<Date::Parse> for conversion functions.
1990
1991 I<template>, if specified, is the name of a suffix for alternate invoices.
1992
1993 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1994
1995 =cut
1996
1997 sub print_text {
1998   my $self = shift;
1999   my( $today, $template, %opt );
2000   if ( ref($_[0]) ) {
2001     %opt = %{ shift() };
2002     $today = delete($opt{'time'}) || '';
2003     $template = delete($opt{template}) || '';
2004   } else {
2005     ( $today, $template, %opt ) = @_;
2006   }
2007
2008   my %params = ( 'format' => 'template' );
2009   $params{'time'} = $today if $today;
2010   $params{'template'} = $template if $template;
2011   $params{$_} = $opt{$_} 
2012     foreach grep $opt{$_}, qw( unsquealch_cdr notice_name );
2013
2014   $self->print_generic( %params );
2015 }
2016
2017 =item print_latex HASHREF | [ TIME [ , TEMPLATE [ , OPTION => VALUE ... ] ] ]
2018
2019 Internal method - returns a filename of a filled-in LaTeX template for this
2020 invoice (Note: add ".tex" to get the actual filename), and a filename of
2021 an associated logo (with the .eps extension included).
2022
2023 See print_ps and print_pdf for methods that return PostScript and PDF output.
2024
2025 Options can be passed as a hashref (recommended) or as a list of time, template
2026 and then any key/value pairs for any other options.
2027
2028 I<time>, if specified, is used to control the printing of overdue messages.  The
2029 default is now.  It isn't the date of the invoice; that's the `_date' field.
2030 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2031 L<Time::Local> and L<Date::Parse> for conversion functions.
2032
2033 I<template>, if specified, is the name of a suffix for alternate invoices.
2034
2035 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
2036
2037 =cut
2038
2039 sub print_latex {
2040   my $self = shift;
2041   my( $today, $template, %opt );
2042   if ( ref($_[0]) ) {
2043     %opt = %{ shift() };
2044     $today = delete($opt{'time'}) || '';
2045     $template = delete($opt{template}) || '';
2046   } else {
2047     ( $today, $template, %opt ) = @_;
2048   }
2049
2050   my %params = ( 'format' => 'latex' );
2051   $params{'time'} = $today if $today;
2052   $params{'template'} = $template if $template;
2053   $params{$_} = $opt{$_} 
2054     foreach grep $opt{$_}, qw( unsquealch_cdr notice_name );
2055
2056   $template ||= $self->_agent_template;
2057
2058   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2059   my $lh = new File::Temp( TEMPLATE => 'invoice.'. $self->invnum. '.XXXXXXXX',
2060                            DIR      => $dir,
2061                            SUFFIX   => '.eps',
2062                            UNLINK   => 0,
2063                          ) or die "can't open temp file: $!\n";
2064
2065   my $agentnum = $self->cust_main->agentnum;
2066
2067   if ( $template && $conf->exists("logo_${template}.eps", $agentnum) ) {
2068     print $lh $conf->config_binary("logo_${template}.eps", $agentnum)
2069       or die "can't write temp file: $!\n";
2070   } else {
2071     print $lh $conf->config_binary('logo.eps', $agentnum)
2072       or die "can't write temp file: $!\n";
2073   }
2074   close $lh;
2075   $params{'logo_file'} = $lh->filename;
2076
2077   my @filled_in = $self->print_generic( %params );
2078   
2079   my $fh = new File::Temp( TEMPLATE => 'invoice.'. $self->invnum. '.XXXXXXXX',
2080                            DIR      => $dir,
2081                            SUFFIX   => '.tex',
2082                            UNLINK   => 0,
2083                          ) or die "can't open temp file: $!\n";
2084   print $fh join('', @filled_in );
2085   close $fh;
2086
2087   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
2088   return ($1, $params{'logo_file'});
2089
2090 }
2091
2092 =item print_generic OPTION => VALUE ...
2093
2094 Internal method - returns a filled-in template for this invoice as a scalar.
2095
2096 See print_ps and print_pdf for methods that return PostScript and PDF output.
2097
2098 Non optional options include 
2099   format - latex, html, template
2100
2101 Optional options include
2102
2103 template - a value used as a suffix for a configuration template
2104
2105 time - a value used to control the printing of overdue messages.  The
2106 default is now.  It isn't the date of the invoice; that's the `_date' field.
2107 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2108 L<Time::Local> and L<Date::Parse> for conversion functions.
2109
2110 cid - 
2111
2112 unsquelch_cdr - overrides any per customer cdr squelching when true
2113
2114 notice_name - overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
2115
2116 =cut
2117
2118 #what's with all the sprintf('%10.2f')'s in here?  will it cause any
2119 # (alignment in text invoice?) problems to change them all to '%.2f' ?
2120 # yes: fixed width (dot matrix) text printing will be borked
2121 sub print_generic {
2122
2123   my( $self, %params ) = @_;
2124   my $today = $params{today} ? $params{today} : time;
2125   warn "$me print_generic called on $self with suffix $params{template}\n"
2126     if $DEBUG;
2127
2128   my $format = $params{format};
2129   die "Unknown format: $format"
2130     unless $format =~ /^(latex|html|template)$/;
2131
2132   my $cust_main = $self->cust_main;
2133   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
2134     unless $cust_main->payname
2135         && $cust_main->payby !~ /^(CARD|DCRD|CHEK|DCHK)$/;
2136
2137   my %delimiters = ( 'latex'    => [ '[@--', '--@]' ],
2138                      'html'     => [ '<%=', '%>' ],
2139                      'template' => [ '{', '}' ],
2140                    );
2141
2142   #create the template
2143   my $template = $params{template} ? $params{template} : $self->_agent_template;
2144   my $templatefile = "invoice_$format";
2145   $templatefile .= "_$template"
2146     if length($template);
2147   my @invoice_template = map "$_\n", $conf->config($templatefile)
2148     or die "cannot load config data $templatefile";
2149
2150   my $old_latex = '';
2151   if ( $format eq 'latex' && grep { /^%%Detail/ } @invoice_template ) {
2152     #change this to a die when the old code is removed
2153     warn "old-style invoice template $templatefile; ".
2154          "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
2155     $old_latex = 'true';
2156     @invoice_template = _translate_old_latex_format(@invoice_template);
2157   } 
2158
2159   my $text_template = new Text::Template(
2160     TYPE => 'ARRAY',
2161     SOURCE => \@invoice_template,
2162     DELIMITERS => $delimiters{$format},
2163   );
2164
2165   $text_template->compile()
2166     or die "Can't compile $templatefile: $Text::Template::ERROR\n";
2167
2168
2169   # additional substitution could possibly cause breakage in existing templates
2170   my %convert_maps = ( 
2171     'latex' => {
2172                  'notes'         => sub { map "$_", @_ },
2173                  'footer'        => sub { map "$_", @_ },
2174                  'smallfooter'   => sub { map "$_", @_ },
2175                  'returnaddress' => sub { map "$_", @_ },
2176                  'coupon'        => sub { map "$_", @_ },
2177                  'summary'       => sub { map "$_", @_ },
2178                },
2179     'html'  => {
2180                  'notes' =>
2181                    sub {
2182                      map { 
2183                        s/%%(.*)$/<!-- $1 -->/g;
2184                        s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
2185                        s/\\begin\{enumerate\}/<ol>/g;
2186                        s/\\item /  <li>/g;
2187                        s/\\end\{enumerate\}/<\/ol>/g;
2188                        s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
2189                        s/\\\\\*/<br>/g;
2190                        s/\\dollar ?/\$/g;
2191                        s/\\#/#/g;
2192                        s/~/&nbsp;/g;
2193                        $_;
2194                      }  @_
2195                    },
2196                  'footer' =>
2197                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
2198                  'smallfooter' =>
2199                    sub { map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; } @_ },
2200                  'returnaddress' =>
2201                    sub {
2202                      map { 
2203                        s/~/&nbsp;/g;
2204                        s/\\\\\*?\s*$/<BR>/;
2205                        s/\\hyphenation\{[\w\s\-]+}//;
2206                        s/\\([&])/$1/g;
2207                        $_;
2208                      }  @_
2209                    },
2210                  'coupon'        => sub { "" },
2211                  'summary'       => sub { "" },
2212                },
2213     'template' => {
2214                  'notes' =>
2215                    sub {
2216                      map { 
2217                        s/%%.*$//g;
2218                        s/\\section\*\{\\textsc\{(.*)\}\}/\U$1/g;
2219                        s/\\begin\{enumerate\}//g;
2220                        s/\\item /  * /g;
2221                        s/\\end\{enumerate\}//g;
2222                        s/\\textbf\{(.*)\}/$1/g;
2223                        s/\\\\\*/ /;
2224                        s/\\dollar ?/\$/g;
2225                        $_;
2226                      }  @_
2227                    },
2228                  'footer' =>
2229                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
2230                  'smallfooter' =>
2231                    sub { map { s/~/ /g; s/\\\\\*?\s*$/\n/; $_; } @_ },
2232                  'returnaddress' =>
2233                    sub {
2234                      map { 
2235                        s/~/ /g;
2236                        s/\\\\\*?\s*$/\n/;             # dubious
2237                        s/\\hyphenation\{[\w\s\-]+}//;
2238                        $_;
2239                      }  @_
2240                    },
2241                  'coupon'        => sub { "" },
2242                  'summary'       => sub { "" },
2243                },
2244   );
2245
2246
2247   # hashes for differing output formats
2248   my %nbsps = ( 'latex'    => '~',
2249                 'html'     => '',    # '&nbps;' would be nice
2250                 'template' => '',    # not used
2251               );
2252   my $nbsp = $nbsps{$format};
2253
2254   my %escape_functions = ( 'latex'    => \&_latex_escape,
2255                            'html'     => \&encode_entities,
2256                            'template' => sub { shift },
2257                          );
2258   my $escape_function = $escape_functions{$format};
2259
2260   my %date_formats = ( 'latex'    => '%b %o, %Y',
2261                        'html'     => '%b&nbsp;%o,&nbsp;%Y',
2262                        'template' => '%s',
2263                      );
2264   my $date_format = $date_formats{$format};
2265
2266   my %embolden_functions = ( 'latex'    => sub { return '\textbf{'. shift(). '}'
2267                                                },
2268                              'html'     => sub { return '<b>'. shift(). '</b>'
2269                                                },
2270                              'template' => sub { shift },
2271                            );
2272   my $embolden_function = $embolden_functions{$format};
2273
2274
2275   # generate template variables
2276   my $returnaddress;
2277   if (
2278          defined( $conf->config_orbase( "invoice_${format}returnaddress",
2279                                         $template
2280                                       )
2281                 )
2282        && length( $conf->config_orbase( "invoice_${format}returnaddress",
2283                                         $template
2284                                       )
2285                 )
2286   ) {
2287
2288     $returnaddress = join("\n",
2289       $conf->config_orbase("invoice_${format}returnaddress", $template)
2290     );
2291
2292   } elsif ( grep /\S/,
2293             $conf->config_orbase('invoice_latexreturnaddress', $template) ) {
2294
2295     my $convert_map = $convert_maps{$format}{'returnaddress'};
2296     $returnaddress =
2297       join( "\n",
2298             &$convert_map( $conf->config_orbase( "invoice_latexreturnaddress",
2299                                                  $template
2300                                                )
2301                          )
2302           );
2303   } elsif ( grep /\S/, $conf->config('company_address', $self->cust_main->agentnum) ) {
2304
2305     my $convert_map = $convert_maps{$format}{'returnaddress'};
2306     $returnaddress = join( "\n", &$convert_map(
2307                                    map { s/( {2,})/'~' x length($1)/eg;
2308                                          s/$/\\\\\*/;
2309                                          $_
2310                                        }
2311                                      ( $conf->config('company_name', $self->cust_main->agentnum),
2312                                        $conf->config('company_address', $self->cust_main->agentnum),
2313                                      )
2314                                  )
2315                      );
2316
2317   } else {
2318
2319     my $warning = "Couldn't find a return address; ".
2320                   "do you need to set the company_address configuration value?";
2321     warn "$warning\n";
2322     $returnaddress = $nbsp;
2323     #$returnaddress = $warning;
2324
2325   }
2326
2327   my $agentnum = $self->cust_main->agentnum;
2328
2329   my %invoice_data = (
2330
2331     #invoice from info
2332     'company_name'    => scalar( $conf->config('company_name', $agentnum) ),
2333     'company_address' => join("\n", $conf->config('company_address', $agentnum) ). "\n",
2334     'returnaddress'   => $returnaddress,
2335     'agent'           => &$escape_function($cust_main->agent->agent),
2336
2337     #invoice info
2338     'invnum'          => $self->invnum,
2339     'date'            => time2str($date_format, $self->_date),
2340     'today'           => time2str('%b %o, %Y', $today),
2341     'terms'           => $self->terms,
2342     'template'        => $template, #params{'template'},
2343     'notice_name'     => ($params{'notice_name'} || 'Invoice'),#escape_function?
2344     'current_charges' => sprintf("%.2f", $self->charged),
2345     'duedate'         => $self->due_date2str($rdate_format), #date_format?
2346
2347     #customer info
2348     'custnum'         => $cust_main->display_custnum,
2349     'agent_custid'    => &$escape_function($cust_main->agent_custid),
2350     ( map { $_ => &$escape_function($cust_main->$_()) } qw(
2351       payname company address1 address2 city state zip fax
2352     )),
2353
2354     #global config
2355     'ship_enable'     => $conf->exists('invoice-ship_address'),
2356     'unitprices'      => $conf->exists('invoice-unitprice'),
2357     'smallernotes'    => $conf->exists('invoice-smallernotes'),
2358     'smallerfooter'   => $conf->exists('invoice-smallerfooter'),
2359     'balance_due_below_line' => $conf->exists('balance_due_below_line'),
2360    
2361     #layout info -- would be fancy to calc some of this and bury the template
2362     #               here in the code
2363     'topmargin'             => scalar($conf->config('invoice_latextopmargin', $agentnum)),
2364     'headsep'               => scalar($conf->config('invoice_latexheadsep', $agentnum)),
2365     'textheight'            => scalar($conf->config('invoice_latextextheight', $agentnum)),
2366     'extracouponspace'      => scalar($conf->config('invoice_latexextracouponspace', $agentnum)),
2367     'couponfootsep'         => scalar($conf->config('invoice_latexcouponfootsep', $agentnum)),
2368     'verticalreturnaddress' => $conf->exists('invoice_latexverticalreturnaddress', $agentnum),
2369     'addresssep'            => scalar($conf->config('invoice_latexaddresssep', $agentnum)),
2370     'amountenclosedsep'     => scalar($conf->config('invoice_latexcouponamountenclosedsep', $agentnum)),
2371     'coupontoaddresssep'    => scalar($conf->config('invoice_latexcoupontoaddresssep', $agentnum)),
2372     'addcompanytoaddress'   => $conf->exists('invoice_latexcouponaddcompanytoaddress', $agentnum),
2373
2374     # better hang on to conf_dir for a while (for old templates)
2375     'conf_dir'        => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
2376
2377     #these are only used when doing paged plaintext
2378     'page'            => 1,
2379     'total_pages'     => 1,
2380
2381   );
2382
2383   $invoice_data{finance_section} = '';
2384   if ( $conf->config('finance_pkgclass') ) {
2385     my $pkg_class =
2386       qsearchs('pkg_class', { classnum => $conf->config('finance_pkgclass') });
2387     $invoice_data{finance_section} = $pkg_class->categoryname;
2388   } 
2389  $invoice_data{finance_amount} = '0.00';
2390
2391   my $countrydefault = $conf->config('countrydefault') || 'US';
2392   my $prefix = $cust_main->has_ship_address ? 'ship_' : '';
2393   foreach ( qw( contact company address1 address2 city state zip country fax) ){
2394     my $method = $prefix.$_;
2395     $invoice_data{"ship_$_"} = _latex_escape($cust_main->$method);
2396   }
2397   $invoice_data{'ship_country'} = ''
2398     if ( $invoice_data{'ship_country'} eq $countrydefault );
2399   
2400   $invoice_data{'cid'} = $params{'cid'}
2401     if $params{'cid'};
2402
2403   if ( $cust_main->country eq $countrydefault ) {
2404     $invoice_data{'country'} = '';
2405   } else {
2406     $invoice_data{'country'} = &$escape_function(code2country($cust_main->country));
2407   }
2408
2409   my @address = ();
2410   $invoice_data{'address'} = \@address;
2411   push @address,
2412     $cust_main->payname.
2413       ( ( $cust_main->payby eq 'BILL' ) && $cust_main->payinfo
2414         ? " (P.O. #". $cust_main->payinfo. ")"
2415         : ''
2416       )
2417   ;
2418   push @address, $cust_main->company
2419     if $cust_main->company;
2420   push @address, $cust_main->address1;
2421   push @address, $cust_main->address2
2422     if $cust_main->address2;
2423   push @address,
2424     $cust_main->city. ", ". $cust_main->state. "  ".  $cust_main->zip;
2425   push @address, $invoice_data{'country'}
2426     if $invoice_data{'country'};
2427   push @address, ''
2428     while (scalar(@address) < 5);
2429
2430   $invoice_data{'logo_file'} = $params{'logo_file'}
2431     if $params{'logo_file'};
2432
2433   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2434 #  my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
2435   #my $balance_due = $self->owed + $pr_total - $cr_total;
2436   my $balance_due = $self->owed + $pr_total;
2437   $invoice_data{'true_previous_balance'} = sprintf("%.2f", ($self->previous_balance || 0) );
2438   $invoice_data{'balance_adjustments'} = sprintf("%.2f", ($self->previous_balance || 0) - ($self->billing_balance || 0) );
2439   $invoice_data{'previous_balance'} = sprintf("%.2f", $pr_total);
2440   $invoice_data{'balance'} = sprintf("%.2f", $balance_due);
2441
2442   my $summarypage = '';
2443   if ( $conf->exists('invoice_usesummary', $agentnum) ) {
2444     $summarypage = 1;
2445   }
2446   $invoice_data{'summarypage'} = $summarypage;
2447
2448   #do variable substitution in notes, footer, smallfooter
2449   foreach my $include (qw( notes footer smallfooter coupon )) {
2450
2451     my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
2452     my @inc_src;
2453
2454     if ( $conf->exists($inc_file, $agentnum)
2455          && length( $conf->config($inc_file, $agentnum) ) ) {
2456
2457       @inc_src = $conf->config($inc_file, $agentnum);
2458
2459     } else {
2460
2461       $inc_file = $conf->key_orbase("invoice_latex$include", $template);
2462
2463       my $convert_map = $convert_maps{$format}{$include};
2464
2465       @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
2466                        s/--\@\]/$delimiters{$format}[1]/g;
2467                        $_;
2468                      } 
2469                  &$convert_map( $conf->config($inc_file, $agentnum) );
2470
2471     }
2472
2473     my $inc_tt = new Text::Template (
2474       TYPE       => 'ARRAY',
2475       SOURCE     => [ map "$_\n", @inc_src ],
2476       DELIMITERS => $delimiters{$format},
2477     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
2478
2479     unless ( $inc_tt->compile() ) {
2480       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
2481       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
2482       die $error;
2483     }
2484
2485     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
2486
2487     $invoice_data{$include} =~ s/\n+$//
2488       if ($format eq 'latex');
2489   }
2490
2491   $invoice_data{'po_line'} =
2492     (  $cust_main->payby eq 'BILL' && $cust_main->payinfo )
2493       ? &$escape_function("Purchase Order #". $cust_main->payinfo)
2494       : $nbsp;
2495
2496   my %money_chars = ( 'latex'    => '',
2497                       'html'     => $conf->config('money_char') || '$',
2498                       'template' => '',
2499                     );
2500   my $money_char = $money_chars{$format};
2501
2502   my %other_money_chars = ( 'latex'    => '\dollar ',#XXX should be a config too
2503                             'html'     => $conf->config('money_char') || '$',
2504                             'template' => '',
2505                           );
2506   my $other_money_char = $other_money_chars{$format};
2507   $invoice_data{'dollar'} = $other_money_char;
2508
2509   my @detail_items = ();
2510   my @total_items = ();
2511   my @buf = ();
2512   my @sections = ();
2513
2514   $invoice_data{'detail_items'} = \@detail_items;
2515   $invoice_data{'total_items'} = \@total_items;
2516   $invoice_data{'buf'} = \@buf;
2517   $invoice_data{'sections'} = \@sections;
2518
2519   my $previous_section = { 'description' => 'Previous Charges',
2520                            'subtotal'    => $other_money_char.
2521                                             sprintf('%.2f', $pr_total),
2522                            'summarized'  => $summarypage ? 'Y' : '',
2523                          };
2524   $previous_section->{posttotal} = '0 / 30 / 60/ 90 days overdue '. 
2525     join(' / ', map { $cust_main->balance_date_range(@$_) }
2526                 $self->_prior_month30s
2527         )
2528     if $conf->exists('invoice_include_aging');
2529
2530   my $taxtotal = 0;
2531   my $tax_section = { 'description' => 'Taxes, Surcharges, and Fees',
2532                       'subtotal'    => $taxtotal,   # adjusted below
2533                       'summarized'  => $summarypage ? 'Y' : '',
2534                     };
2535   my $tax_weight = _pkg_category($tax_section->{description})
2536                         ? _pkg_category($tax_section->{description})->weight
2537                         : 0;
2538   $tax_section->{'summarized'} = $summarypage && !$tax_weight ? 'Y' : '';
2539   $tax_section->{'sort_weight'} = $tax_weight;
2540
2541
2542   my $adjusttotal = 0;
2543   my $adjust_section = { 'description' => 'Credits, Payments, and Adjustments',
2544                          'subtotal'    => 0,   # adjusted below
2545                          'summarized'  => $summarypage ? 'Y' : '',
2546                        };
2547   my $adjust_weight = _pkg_category($adjust_section->{description})
2548                         ? _pkg_category($adjust_section->{description})->weight
2549                         : 0;
2550   $adjust_section->{'summarized'} = $summarypage && !$adjust_weight ? 'Y' : '';
2551   $adjust_section->{'sort_weight'} = $adjust_weight;
2552
2553   my $unsquelched = $params{unsquelch_cdr} || $cust_main->squelch_cdr ne 'Y';
2554   my $multisection = $conf->exists('invoice_sections', $cust_main->agentnum);
2555   $invoice_data{'multisection'} = $multisection;
2556   my $late_sections = [];
2557   my $extra_sections = [];
2558   my $extra_lines = ();
2559   if ( $multisection ) {
2560     ($extra_sections, $extra_lines) =
2561       $self->_items_extra_usage_sections($escape_function, $format)
2562       if $conf->exists('usage_class_as_a_section', $cust_main->agentnum);
2563
2564     push @$extra_sections, $adjust_section if $adjust_section->{sort_weight};
2565
2566     push @detail_items, @$extra_lines if $extra_lines;
2567     push @sections,
2568       $self->_items_sections( $late_sections,      # this could stand a refactor
2569                               $summarypage,
2570                               $escape_function,
2571                               $extra_sections,
2572                               $format,             #bah
2573                             );
2574     if ($conf->exists('svc_phone_sections')) {
2575       my ($phone_sections, $phone_lines) =
2576         $self->_items_svc_phone_sections($escape_function, $format);
2577       push @{$late_sections}, @$phone_sections;
2578       push @detail_items, @$phone_lines;
2579     }
2580   }else{
2581     push @sections, { 'description' => '', 'subtotal' => '' };
2582   }
2583
2584   unless (    $conf->exists('disable_previous_balance')
2585            || $conf->exists('previous_balance-summary_only')
2586          )
2587   {
2588
2589     foreach my $line_item ( $self->_items_previous ) {
2590
2591       my $detail = {
2592         ext_description => [],
2593       };
2594       $detail->{'ref'} = $line_item->{'pkgnum'};
2595       $detail->{'quantity'} = 1;
2596       $detail->{'section'} = $previous_section;
2597       $detail->{'description'} = &$escape_function($line_item->{'description'});
2598       if ( exists $line_item->{'ext_description'} ) {
2599         @{$detail->{'ext_description'}} = map {
2600           &$escape_function($_);
2601         } @{$line_item->{'ext_description'}};
2602       }
2603       $detail->{'amount'} = ( $old_latex ? '' : $money_char).
2604                             $line_item->{'amount'};
2605       $detail->{'product_code'} = $line_item->{'pkgpart'} || 'N/A';
2606
2607       push @detail_items, $detail;
2608       push @buf, [ $detail->{'description'},
2609                    $money_char. sprintf("%10.2f", $line_item->{'amount'}),
2610                  ];
2611     }
2612
2613   }
2614
2615   if ( @pr_cust_bill && !$conf->exists('disable_previous_balance') ) {
2616     push @buf, ['','-----------'];
2617     push @buf, [ 'Total Previous Balance',
2618                  $money_char. sprintf("%10.2f", $pr_total) ];
2619     push @buf, ['',''];
2620   }
2621
2622   foreach my $section (@sections, @$late_sections) {
2623
2624     # begin some normalization
2625     $section->{'subtotal'} = $section->{'amount'}
2626       if $multisection
2627          && !exists($section->{subtotal})
2628          && exists($section->{amount});
2629
2630     $invoice_data{finance_amount} = sprintf('%.2f', $section->{'subtotal'} )
2631       if ( $invoice_data{finance_section} &&
2632            $section->{'description'} eq $invoice_data{finance_section} );
2633
2634     $section->{'subtotal'} = $other_money_char.
2635                              sprintf('%.2f', $section->{'subtotal'})
2636       if $multisection;
2637
2638     # continue some normalization
2639     $section->{'amount'}   = $section->{'subtotal'}
2640       if $multisection;
2641
2642
2643     if ( $section->{'description'} ) {
2644       push @buf, ( [ &$escape_function($section->{'description'}), '' ],
2645                    [ '', '' ],
2646                  );
2647     }
2648
2649     my $multilocation = scalar($cust_main->cust_location); #too expensive?
2650     my %options = ();
2651     $options{'section'} = $section if $multisection;
2652     $options{'format'} = $format;
2653     $options{'escape_function'} = $escape_function;
2654     $options{'format_function'} = sub { () } unless $unsquelched;
2655     $options{'unsquelched'} = $unsquelched;
2656     $options{'summary_page'} = $summarypage;
2657     $options{'skip_usage'} =
2658       scalar(@$extra_sections) && !grep{$section == $_} @$extra_sections;
2659     $options{'multilocation'} = $multilocation;
2660
2661     foreach my $line_item ( $self->_items_pkg(%options) ) {
2662       my $detail = {
2663         ext_description => [],
2664       };
2665       $detail->{'ref'} = $line_item->{'pkgnum'};
2666       $detail->{'quantity'} = $line_item->{'quantity'};
2667       $detail->{'section'} = $section;
2668       $detail->{'description'} = &$escape_function($line_item->{'description'});
2669       if ( exists $line_item->{'ext_description'} ) {
2670         @{$detail->{'ext_description'}} = @{$line_item->{'ext_description'}};
2671       }
2672       $detail->{'amount'} = ( $old_latex ? '' : $money_char ).
2673                               $line_item->{'amount'};
2674       $detail->{'unit_amount'} = ( $old_latex ? '' : $money_char ).
2675                                  $line_item->{'unit_amount'};
2676       $detail->{'product_code'} = $line_item->{'pkgpart'} || 'N/A';
2677   
2678       push @detail_items, $detail;
2679       push @buf, ( [ $detail->{'description'},
2680                      $money_char. sprintf("%10.2f", $line_item->{'amount'}),
2681                    ],
2682                    map { [ " ". $_, '' ] } @{$detail->{'ext_description'}},
2683                  );
2684     }
2685
2686     if ( $section->{'description'} ) {
2687       push @buf, ( ['','-----------'],
2688                    [ $section->{'description'}. ' sub-total',
2689                       $money_char. sprintf("%10.2f", $section->{'subtotal'})
2690                    ],
2691                    [ '', '' ],
2692                    [ '', '' ],
2693                  );
2694     }
2695   
2696   }
2697   
2698   $invoice_data{current_less_finance} =
2699     sprintf('%.2f', $self->charged - $invoice_data{finance_amount} );
2700
2701   if ( $multisection && !$conf->exists('disable_previous_balance')
2702     || $conf->exists('previous_balance-summary_only') )
2703   {
2704     unshift @sections, $previous_section if $pr_total;
2705   }
2706
2707   foreach my $tax ( $self->_items_tax ) {
2708
2709     $taxtotal += $tax->{'amount'};
2710
2711     my $description = &$escape_function( $tax->{'description'} );
2712     my $amount      = sprintf( '%.2f', $tax->{'amount'} );
2713
2714     if ( $multisection ) {
2715
2716       my $money = $old_latex ? '' : $money_char;
2717       push @detail_items, {
2718         ext_description => [],
2719         ref          => '',
2720         quantity     => '',
2721         description  => $description,
2722         amount       => $money. $amount,
2723         product_code => '',
2724         section      => $tax_section,
2725       };
2726
2727     } else {
2728
2729       push @total_items, {
2730         'total_item'   => $description,
2731         'total_amount' => $other_money_char. $amount,
2732       };
2733
2734     }
2735
2736     push @buf,[ $description,
2737                 $money_char. $amount,
2738               ];
2739
2740   }
2741   
2742   if ( $taxtotal ) {
2743     my $total = {};
2744     $total->{'total_item'} = 'Sub-total';
2745     $total->{'total_amount'} =
2746       $other_money_char. sprintf('%.2f', $self->charged - $taxtotal );
2747
2748     if ( $multisection ) {
2749       $tax_section->{'subtotal'} = $other_money_char.
2750                                    sprintf('%.2f', $taxtotal);
2751       $tax_section->{'pretotal'} = 'New charges sub-total '.
2752                                    $total->{'total_amount'};
2753       push @sections, $tax_section if $taxtotal;
2754     }else{
2755       unshift @total_items, $total;
2756     }
2757   }
2758   $invoice_data{'taxtotal'} = sprintf('%.2f', $taxtotal);
2759
2760   push @buf,['','-----------'];
2761   push @buf,[( $conf->exists('disable_previous_balance') 
2762                ? 'Total Charges'
2763                : 'Total New Charges'
2764              ),
2765              $money_char. sprintf("%10.2f",$self->charged) ];
2766   push @buf,['',''];
2767
2768   {
2769     my $total = {};
2770     my $item = 'Total';
2771     $item = $conf->config('previous_balance-exclude_from_total')
2772          || 'Total New Charges'
2773       if $conf->exists('previous_balance-exclude_from_total');
2774     my $amount = $self->charged +
2775                    ( $conf->exists('disable_previous_balance') ||
2776                      $conf->exists('previous_balance-exclude_from_total')
2777                      ? 0
2778                      : $pr_total
2779                    );
2780     $total->{'total_item'} = &$embolden_function($item);
2781     $total->{'total_amount'} =
2782       &$embolden_function( $other_money_char.  sprintf( '%.2f', $amount ) );
2783     if ( $multisection ) {
2784       if ( $adjust_section->{'sort_weight'} ) {
2785         $adjust_section->{'posttotal'} = 'Balance Forward '. $other_money_char.
2786           sprintf("%.2f", ($self->billing_balance || 0) );
2787       } else {
2788         $adjust_section->{'pretotal'} = 'New charges total '. $other_money_char.
2789                                         sprintf('%.2f', $self->charged );
2790       } 
2791     }else{
2792       push @total_items, $total;
2793     }
2794     push @buf,['','-----------'];
2795     push @buf,[$item,
2796                $money_char.
2797                sprintf( '%10.2f', $amount )
2798               ];
2799     push @buf,['',''];
2800   }
2801   
2802   unless ( $conf->exists('disable_previous_balance') ) {
2803     #foreach my $thing ( sort { $a->_date <=> $b->_date } $self->_items_credits, $self->_items_payments
2804   
2805     # credits
2806     my $credittotal = 0;
2807     foreach my $credit ( $self->_items_credits('trim_len'=>60) ) {
2808
2809       my $total;
2810       $total->{'total_item'} = &$escape_function($credit->{'description'});
2811       $credittotal += $credit->{'amount'};
2812       $total->{'total_amount'} = '-'. $other_money_char. $credit->{'amount'};
2813       $adjusttotal += $credit->{'amount'};
2814       if ( $multisection ) {
2815         my $money = $old_latex ? '' : $money_char;
2816         push @detail_items, {
2817           ext_description => [],
2818           ref          => '',
2819           quantity     => '',
2820           description  => &$escape_function($credit->{'description'}),
2821           amount       => $money. $credit->{'amount'},
2822           product_code => '',
2823           section      => $adjust_section,
2824         };
2825       } else {
2826         push @total_items, $total;
2827       }
2828
2829     }
2830     $invoice_data{'credittotal'} = sprintf('%.2f', $credittotal);
2831
2832     #credits (again)
2833     foreach my $credit ( $self->_items_credits('trim_len'=>32) ) {
2834       push @buf, [ $credit->{'description'}, $money_char.$credit->{'amount'} ];
2835     }
2836
2837     # payments
2838     my $paymenttotal = 0;
2839     foreach my $payment ( $self->_items_payments ) {
2840       my $total = {};
2841       $total->{'total_item'} = &$escape_function($payment->{'description'});
2842       $paymenttotal += $payment->{'amount'};
2843       $total->{'total_amount'} = '-'. $other_money_char. $payment->{'amount'};
2844       $adjusttotal += $payment->{'amount'};
2845       if ( $multisection ) {
2846         my $money = $old_latex ? '' : $money_char;
2847         push @detail_items, {
2848           ext_description => [],
2849           ref          => '',
2850           quantity     => '',
2851           description  => &$escape_function($payment->{'description'}),
2852           amount       => $money. $payment->{'amount'},
2853           product_code => '',
2854           section      => $adjust_section,
2855         };
2856       }else{
2857         push @total_items, $total;
2858       }
2859       push @buf, [ $payment->{'description'},
2860                    $money_char. sprintf("%10.2f", $payment->{'amount'}),
2861                  ];
2862     }
2863     $invoice_data{'paymenttotal'} = sprintf('%.2f', $paymenttotal);
2864   
2865     if ( $multisection ) {
2866       $adjust_section->{'subtotal'} = $other_money_char.
2867                                       sprintf('%.2f', $adjusttotal);
2868       push @sections, $adjust_section
2869         unless $adjust_section->{sort_weight};
2870     }
2871
2872     { 
2873       my $total;
2874       $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
2875       $total->{'total_amount'} =
2876         &$embolden_function(
2877           $other_money_char. sprintf('%.2f', $summarypage 
2878                                                ? $self->charged +
2879                                                  $self->billing_balance
2880                                                : $self->owed + $pr_total
2881                                     )
2882         );
2883       if ( $multisection && !$adjust_section->{sort_weight} ) {
2884         $adjust_section->{'posttotal'} = $total->{'total_item'}. ' '.
2885                                          $total->{'total_amount'};
2886       }else{
2887         push @total_items, $total;
2888       }
2889       push @buf,['','-----------'];
2890       push @buf,[$self->balance_due_msg, $money_char. 
2891         sprintf("%10.2f", $balance_due ) ];
2892     }
2893   }
2894
2895   if ( $multisection ) {
2896     if ($conf->exists('svc_phone_sections')) {
2897       my $total;
2898       $total->{'total_item'} = &$embolden_function($self->balance_due_msg);
2899       $total->{'total_amount'} =
2900         &$embolden_function(
2901           $other_money_char. sprintf('%.2f', $self->owed + $pr_total)
2902         );
2903       my $last_section = pop @sections;
2904       $last_section->{'posttotal'} = $total->{'total_item'}. ' '.
2905                                      $total->{'total_amount'};
2906       push @sections, $last_section;
2907     }
2908     push @sections, @$late_sections
2909       if $unsquelched;
2910   }
2911
2912   my @includelist = ();
2913   push @includelist, 'summary' if $summarypage;
2914   foreach my $include ( @includelist ) {
2915
2916     my $inc_file = $conf->key_orbase("invoice_${format}$include", $template);
2917     my @inc_src;
2918
2919     if ( length( $conf->config($inc_file, $agentnum) ) ) {
2920
2921       @inc_src = $conf->config($inc_file, $agentnum);
2922
2923     } else {
2924
2925       $inc_file = $conf->key_orbase("invoice_latex$include", $template);
2926
2927       my $convert_map = $convert_maps{$format}{$include};
2928
2929       @inc_src = map { s/\[\@--/$delimiters{$format}[0]/g;
2930                        s/--\@\]/$delimiters{$format}[1]/g;
2931                        $_;
2932                      } 
2933                  &$convert_map( $conf->config($inc_file, $agentnum) );
2934
2935     }
2936
2937     my $inc_tt = new Text::Template (
2938       TYPE       => 'ARRAY',
2939       SOURCE     => [ map "$_\n", @inc_src ],
2940       DELIMITERS => $delimiters{$format},
2941     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
2942
2943     unless ( $inc_tt->compile() ) {
2944       my $error = "Can't compile $inc_file template: $Text::Template::ERROR\n";
2945       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
2946       die $error;
2947     }
2948
2949     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
2950
2951     $invoice_data{$include} =~ s/\n+$//
2952       if ($format eq 'latex');
2953   }
2954
2955   $invoice_lines = 0;
2956   my $wasfunc = 0;
2957   foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
2958     /invoice_lines\((\d*)\)/;
2959     $invoice_lines += $1 || scalar(@buf);
2960     $wasfunc=1;
2961   }
2962   die "no invoice_lines() functions in template?"
2963     if ( $format eq 'template' && !$wasfunc );
2964
2965   if ($format eq 'template') {
2966
2967     if ( $invoice_lines ) {
2968       $invoice_data{'total_pages'} = int( scalar(@buf) / $invoice_lines );
2969       $invoice_data{'total_pages'}++
2970         if scalar(@buf) % $invoice_lines;
2971     }
2972
2973     #setup subroutine for the template
2974     sub FS::cust_bill::_template::invoice_lines {
2975       my $lines = shift || scalar(@FS::cust_bill::_template::buf);
2976       map { 
2977         scalar(@FS::cust_bill::_template::buf)
2978           ? shift @FS::cust_bill::_template::buf
2979           : [ '', '' ];
2980       }
2981       ( 1 .. $lines );
2982     }
2983
2984     my $lines;
2985     my @collect;
2986     while (@buf) {
2987       push @collect, split("\n",
2988         $text_template->fill_in( HASH => \%invoice_data,
2989                                  PACKAGE => 'FS::cust_bill::_template'
2990                                )
2991       );
2992       $FS::cust_bill::_template::page++;
2993     }
2994     map "$_\n", @collect;
2995   }else{
2996     warn "filling in template for invoice ". $self->invnum. "\n"
2997       if $DEBUG;
2998     warn join("\n", map " $_ => ". $invoice_data{$_}, keys %invoice_data). "\n"
2999       if $DEBUG > 1;
3000
3001     $text_template->fill_in(HASH => \%invoice_data);
3002   }
3003 }
3004
3005 # helper routine for generating date ranges
3006 sub _prior_month30s {
3007   my $self = shift;
3008   my @ranges = (
3009    [ 1,       2592000 ], # 0-30 days ago
3010    [ 2592000, 5184000 ], # 30-60 days ago
3011    [ 5184000, 7776000 ], # 60-90 days ago
3012    [ 7776000, 0       ], # 90+   days ago
3013   );
3014
3015   map { [ $_->[0] ? $self->_date - $_->[0] - 1 : '',
3016           $_->[1] ? $self->_date - $_->[1] - 1 : '',
3017       ] }
3018   @ranges;
3019 }
3020
3021 =item print_ps HASHREF | [ TIME [ , TEMPLATE ] ]
3022
3023 Returns an postscript invoice, as a scalar.
3024
3025 Options can be passed as a hashref (recommended) or as a list of time, template
3026 and then any key/value pairs for any other options.
3027
3028 I<time> an optional value used to control the printing of overdue messages.  The
3029 default is now.  It isn't the date of the invoice; that's the `_date' field.
3030 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
3031 L<Time::Local> and L<Date::Parse> for conversion functions.
3032
3033 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
3034
3035 =cut
3036
3037 sub print_ps {
3038   my $self = shift;
3039
3040   my ($file, $lfile) = $self->print_latex(@_);
3041   my $ps = generate_ps($file);
3042   unlink($file.'.tex');
3043   unlink($lfile);
3044
3045   $ps;
3046 }
3047
3048 =item print_pdf HASHREF | [ TIME [ , TEMPLATE ] ]
3049
3050 Returns an PDF invoice, as a scalar.
3051
3052 Options can be passed as a hashref (recommended) or as a list of time, template
3053 and then any key/value pairs for any other options.
3054
3055 I<time> an optional value used to control the printing of overdue messages.  The
3056 default is now.  It isn't the date of the invoice; that's the `_date' field.
3057 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
3058 L<Time::Local> and L<Date::Parse> for conversion functions.
3059
3060 I<template>, if specified, is the name of a suffix for alternate invoices.
3061
3062 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
3063
3064 =cut
3065
3066 sub print_pdf {
3067   my $self = shift;
3068
3069   my ($file, $lfile) = $self->print_latex(@_);
3070   my $pdf = generate_pdf($file);
3071   unlink($file.'.tex');
3072   unlink($lfile);
3073
3074   $pdf;
3075 }
3076
3077 =item print_html HASHREF | [ TIME [ , TEMPLATE [ , CID ] ] ]
3078
3079 Returns an HTML invoice, as a scalar.
3080
3081 I<time> an optional value used to control the printing of overdue messages.  The
3082 default is now.  It isn't the date of the invoice; that's the `_date' field.
3083 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
3084 L<Time::Local> and L<Date::Parse> for conversion functions.
3085
3086 I<template>, if specified, is the name of a suffix for alternate invoices.
3087
3088 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
3089
3090 I<cid> is a MIME Content-ID used to create a "cid:" URL for the logo image, used
3091 when emailing the invoice as part of a multipart/related MIME email.
3092
3093 =cut
3094
3095 sub print_html {
3096   my $self = shift;
3097   my %params;
3098   if ( ref($_[0]) ) {
3099     %params = %{ shift() }; 
3100   }else{
3101     $params{'time'} = shift;
3102     $params{'template'} = shift;
3103     $params{'cid'} = shift;
3104   }
3105
3106   $params{'format'} = 'html';
3107
3108   $self->print_generic( %params );
3109 }
3110
3111 # quick subroutine for print_latex
3112 #
3113 # There are ten characters that LaTeX treats as special characters, which
3114 # means that they do not simply typeset themselves: 
3115 #      # $ % & ~ _ ^ \ { }
3116 #
3117 # TeX ignores blanks following an escaped character; if you want a blank (as
3118 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ..."). 
3119
3120 sub _latex_escape {
3121   my $value = shift;
3122   $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
3123   $value =~ s/([<>])/\$$1\$/g;
3124   $value;
3125 }
3126
3127 #utility methods for print_*
3128
3129 sub _translate_old_latex_format {
3130   warn "_translate_old_latex_format called\n"
3131     if $DEBUG; 
3132
3133   my @template = ();
3134   while ( @_ ) {
3135     my $line = shift;
3136   
3137     if ( $line =~ /^%%Detail\s*$/ ) {
3138   
3139       push @template, q![@--!,
3140                       q!  foreach my $_tr_line (@detail_items) {!,
3141                       q!    if ( scalar ($_tr_item->{'ext_description'} ) ) {!,
3142                       q!      $_tr_line->{'description'} .= !, 
3143                       q!        "\\tabularnewline\n~~".!,
3144                       q!        join( "\\tabularnewline\n~~",!,
3145                       q!          @{$_tr_line->{'ext_description'}}!,
3146                       q!        );!,
3147                       q!    }!;
3148
3149       while ( ( my $line_item_line = shift )
3150               !~ /^%%EndDetail\s*$/                            ) {
3151         $line_item_line =~ s/'/\\'/g;    # nice LTS
3152         $line_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
3153         $line_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
3154         push @template, "    \$OUT .= '$line_item_line';";
3155       }
3156
3157       push @template, '}',
3158                       '--@]';
3159       #' doh, gvim
3160     } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
3161
3162       push @template, '[@--',
3163                       '  foreach my $_tr_line (@total_items) {';
3164
3165       while ( ( my $total_item_line = shift )
3166               !~ /^%%EndTotalDetails\s*$/                      ) {
3167         $total_item_line =~ s/'/\\'/g;    # nice LTS
3168         $total_item_line =~ s/\\/\\\\/g;  # escape quotes and backslashes
3169         $total_item_line =~ s/\$(\w+)/'. \$_tr_line->{$1}. '/g;
3170         push @template, "    \$OUT .= '$total_item_line';";
3171       }
3172
3173       push @template, '}',
3174                       '--@]';
3175
3176     } else {
3177       $line =~ s/\$(\w+)/[\@-- \$$1 --\@]/g;
3178       push @template, $line;  
3179     }
3180   
3181   }
3182
3183   if ($DEBUG) {
3184     warn "$_\n" foreach @template;
3185   }
3186
3187   (@template);
3188 }
3189
3190 sub terms {
3191   my $self = shift;
3192
3193   #check for an invoice-specific override
3194   return $self->invoice_terms if $self->invoice_terms;
3195   
3196   #check for a customer- specific override
3197   my $cust_main = $self->cust_main;
3198   return $cust_main->invoice_terms if $cust_main->invoice_terms;
3199
3200   #use configured default
3201   $conf->config('invoice_default_terms') || '';
3202 }
3203
3204 sub due_date {
3205   my $self = shift;
3206   my $duedate = '';
3207   if ( $self->terms =~ /^\s*Net\s*(\d+)\s*$/ ) {
3208     $duedate = $self->_date() + ( $1 * 86400 );
3209   }
3210   $duedate;
3211 }
3212
3213 sub due_date2str {
3214   my $self = shift;
3215   $self->due_date ? time2str(shift, $self->due_date) : '';
3216 }
3217
3218 sub balance_due_msg {
3219   my $self = shift;
3220   my $msg = 'Balance Due';
3221   return $msg unless $self->terms;
3222   if ( $self->due_date ) {
3223     $msg .= ' - Please pay by '. $self->due_date2str($date_format);
3224   } elsif ( $self->terms ) {
3225     $msg .= ' - '. $self->terms;
3226   }
3227   $msg;
3228 }
3229
3230 sub balance_due_date {
3231   my $self = shift;
3232   my $duedate = '';
3233   if (    $conf->exists('invoice_default_terms') 
3234        && $conf->config('invoice_default_terms')=~ /^\s*Net\s*(\d+)\s*$/ ) {
3235     $duedate = time2str($rdate_format, $self->_date + ($1*86400) );
3236   }
3237   $duedate;
3238 }
3239
3240 =item invnum_date_pretty
3241
3242 Returns a string with the invoice number and date, for example:
3243 "Invoice #54 (3/20/2008)"
3244
3245 =cut
3246
3247 sub invnum_date_pretty {
3248   my $self = shift;
3249   'Invoice #'. $self->invnum. ' ('. $self->_date_pretty. ')';
3250 }
3251
3252 =item _date_pretty
3253
3254 Returns a string with the date, for example: "3/20/2008"
3255
3256 =cut
3257
3258 sub _date_pretty {
3259   my $self = shift;
3260   time2str($date_format, $self->_date);
3261 }
3262
3263 use vars qw(%pkg_category_cache);
3264 sub _items_sections {
3265   my $self = shift;
3266   my $late = shift;
3267   my $summarypage = shift;
3268   my $escape = shift;
3269   my $extra_sections = shift;
3270   my $format = shift;
3271
3272   my %subtotal = ();
3273   my %late_subtotal = ();
3274   my %not_tax = ();
3275
3276   foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
3277   {
3278
3279       my $usage = $cust_bill_pkg->usage;
3280
3281       foreach my $display ($cust_bill_pkg->cust_bill_pkg_display) {
3282         next if ( $display->summary && $summarypage );
3283
3284         my $section = $display->section;
3285         my $type    = $display->type;
3286
3287         $not_tax{$section} = 1
3288           unless $cust_bill_pkg->pkgnum == 0;
3289
3290         if ( $display->post_total && !$summarypage ) {
3291           if (! $type || $type eq 'S') {
3292             $late_subtotal{$section} += $cust_bill_pkg->setup
3293               if $cust_bill_pkg->setup != 0;
3294           }
3295
3296           if (! $type) {
3297             $late_subtotal{$section} += $cust_bill_pkg->recur
3298               if $cust_bill_pkg->recur != 0;
3299           }
3300
3301           if ($type && $type eq 'R') {
3302             $late_subtotal{$section} += $cust_bill_pkg->recur - $usage
3303               if $cust_bill_pkg->recur != 0;
3304           }
3305           
3306           if ($type && $type eq 'U') {
3307             $late_subtotal{$section} += $usage
3308               unless scalar(@$extra_sections);
3309           }
3310
3311         } else {
3312
3313           next if $cust_bill_pkg->pkgnum == 0 && ! $section;
3314
3315           if (! $type || $type eq 'S') {
3316             $subtotal{$section} += $cust_bill_pkg->setup
3317               if $cust_bill_pkg->setup != 0;
3318           }
3319
3320           if (! $type) {
3321             $subtotal{$section} += $cust_bill_pkg->recur
3322               if $cust_bill_pkg->recur != 0;
3323           }
3324
3325           if ($type && $type eq 'R') {
3326             $subtotal{$section} += $cust_bill_pkg->recur - $usage
3327               if $cust_bill_pkg->recur != 0;
3328           }
3329           
3330           if ($type && $type eq 'U') {
3331             $subtotal{$section} += $usage
3332               unless scalar(@$extra_sections);
3333           }
3334
3335         }
3336
3337       }
3338
3339   }
3340
3341   %pkg_category_cache = ();
3342
3343   push @$late, map { { 'description' => &{$escape}($_),
3344                        'subtotal'    => $late_subtotal{$_},
3345                        'post_total'  => 1,
3346                        'sort_weight' => ( _pkg_category($_)
3347                                             ? _pkg_category($_)->weight
3348                                             : 0
3349                                        ),
3350                        ((_pkg_category($_) && _pkg_category($_)->condense)
3351                                            ? $self->_condense_section($format)
3352                                            : ()
3353                        ),
3354                    } }
3355                  sort _sectionsort keys %late_subtotal;
3356
3357   my @sections;
3358   if ( $summarypage ) {
3359     @sections = grep { exists($subtotal{$_}) || ! _pkg_category($_)->disabled }
3360                 map { $_->categoryname } qsearch('pkg_category', {});
3361   } else {
3362     @sections = keys %subtotal;
3363   }
3364
3365   my @early = map { { 'description' => &{$escape}($_),
3366                       'subtotal'    => $subtotal{$_},
3367                       'summarized'  => $not_tax{$_} ? '' : 'Y',
3368                       'tax_section' => $not_tax{$_} ? '' : 'Y',
3369                       'sort_weight' => ( _pkg_category($_)
3370                                            ? _pkg_category($_)->weight
3371                                            : 0
3372                                        ),
3373                        ((_pkg_category($_) && _pkg_category($_)->condense)
3374                                            ? $self->_condense_section($format)
3375                                            : ()
3376                        ),
3377                     }
3378                   } @sections;
3379   push @early, @$extra_sections if $extra_sections;
3380  
3381   sort { $a->{sort_weight} <=> $b->{sort_weight} } @early;
3382
3383 }
3384
3385 #helper subs for above
3386
3387 sub _sectionsort {
3388   _pkg_category($a)->weight <=> _pkg_category($b)->weight;
3389 }
3390
3391 sub _pkg_category {
3392   my $categoryname = shift;
3393   $pkg_category_cache{$categoryname} ||=
3394     qsearchs( 'pkg_category', { 'categoryname' => $categoryname } );
3395 }
3396
3397 my %condensed_format = (
3398   'label' => [ qw( Description Qty Amount ) ],
3399   'fields' => [
3400                 sub { shift->{description} },
3401                 sub { shift->{quantity} },
3402                 sub { my($href, %opt) = @_;
3403                       ($opt{dollar} || ''). $href->{amount};
3404                     },
3405               ],
3406   'align'  => [ qw( l r r ) ],
3407   'span'   => [ qw( 5 1 1 ) ],            # unitprices?
3408   'width'  => [ qw( 10.7cm 1.4cm 1.6cm ) ],   # don't like this
3409 );
3410
3411 sub _condense_section {
3412   my ( $self, $format ) = ( shift, shift );
3413   ( 'condensed' => 1,
3414     map { my $method = "_condensed_$_"; $_ => $self->$method($format) }
3415       qw( description_generator
3416           header_generator
3417           total_generator
3418           total_line_generator
3419         )
3420   );
3421 }
3422
3423 sub _condensed_generator_defaults {
3424   my ( $self, $format ) = ( shift, shift );
3425   return ( \%condensed_format, ' ', ' ', ' ', sub { shift } );
3426 }
3427
3428 my %html_align = (
3429   'c' => 'center',
3430   'l' => 'left',
3431   'r' => 'right',
3432 );
3433
3434 sub _condensed_header_generator {
3435   my ( $self, $format ) = ( shift, shift );
3436
3437   my ( $f, $prefix, $suffix, $separator, $column ) =
3438     _condensed_generator_defaults($format);
3439
3440   if ($format eq 'latex') {
3441     $prefix = "\\hline\n\\rule{0pt}{2.5ex}\n\\makebox[1.4cm]{}&\n";
3442     $suffix = "\\\\\n\\hline";
3443     $separator = "&\n";
3444     $column =
3445       sub { my ($d,$a,$s,$w) = @_;
3446             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
3447           };
3448   } elsif ( $format eq 'html' ) {
3449     $prefix = '<th></th>';
3450     $suffix = '';
3451     $separator = '';
3452     $column =
3453       sub { my ($d,$a,$s,$w) = @_;
3454             return qq!<th align="$html_align{$a}">$d</th>!;
3455       };
3456   }
3457
3458   sub {
3459     my @args = @_;
3460     my @result = ();
3461
3462     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3463       push @result,
3464         &{$column}( map { $f->{$_}->[$i] } qw(label align span width) );
3465     }
3466
3467     $prefix. join($separator, @result). $suffix;
3468   };
3469
3470 }
3471
3472 sub _condensed_description_generator {
3473   my ( $self, $format ) = ( shift, shift );
3474
3475   my ( $f, $prefix, $suffix, $separator, $column ) =
3476     _condensed_generator_defaults($format);
3477
3478   my $money_char = '$';
3479   if ($format eq 'latex') {
3480     $prefix = "\\hline\n\\multicolumn{1}{c}{\\rule{0pt}{2.5ex}~} &\n";
3481     $suffix = '\\\\';
3482     $separator = " & \n";
3483     $column =
3484       sub { my ($d,$a,$s,$w) = @_;
3485             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{\\textbf{$d}}}";
3486           };
3487     $money_char = '\\dollar';
3488   }elsif ( $format eq 'html' ) {
3489     $prefix = '"><td align="center"></td>';
3490     $suffix = '';
3491     $separator = '';
3492     $column =
3493       sub { my ($d,$a,$s,$w) = @_;
3494             return qq!<td align="$html_align{$a}">$d</td>!;
3495       };
3496     #$money_char = $conf->config('money_char') || '$';
3497     $money_char = '';  # this is madness
3498   }
3499
3500   sub {
3501     #my @args = @_;
3502     my $href = shift;
3503     my @result = ();
3504
3505     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3506       my $dollar = '';
3507       $dollar = $money_char if $i == scalar(@{$f->{label}})-1;
3508       push @result,
3509         &{$column}( &{$f->{fields}->[$i]}($href, 'dollar' => $dollar),
3510                     map { $f->{$_}->[$i] } qw(align span width)
3511                   );
3512     }
3513
3514     $prefix. join( $separator, @result ). $suffix;
3515   };
3516
3517 }
3518
3519 sub _condensed_total_generator {
3520   my ( $self, $format ) = ( shift, shift );
3521
3522   my ( $f, $prefix, $suffix, $separator, $column ) =
3523     _condensed_generator_defaults($format);
3524   my $style = '';
3525
3526   if ($format eq 'latex') {
3527     $prefix = "& ";
3528     $suffix = "\\\\\n";
3529     $separator = " & \n";
3530     $column =
3531       sub { my ($d,$a,$s,$w) = @_;
3532             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3533           };
3534   }elsif ( $format eq 'html' ) {
3535     $prefix = '';
3536     $suffix = '';
3537     $separator = '';
3538     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3539     $column =
3540       sub { my ($d,$a,$s,$w) = @_;
3541             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3542       };
3543   }
3544
3545
3546   sub {
3547     my @args = @_;
3548     my @result = ();
3549
3550     #  my $r = &{$f->{fields}->[$i]}(@args);
3551     #  $r .= ' Total' unless $i;
3552
3553     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3554       push @result,
3555         &{$column}( &{$f->{fields}->[$i]}(@args). ($i ? '' : ' Total'),
3556                     map { $f->{$_}->[$i] } qw(align span width)
3557                   );
3558     }
3559
3560     $prefix. join( $separator, @result ). $suffix;
3561   };
3562
3563 }
3564
3565 =item total_line_generator FORMAT
3566
3567 Returns a coderef used for generation of invoice total line items for this
3568 usage_class.  FORMAT is either html or latex
3569
3570 =cut
3571
3572 # should not be used: will have issues with hash element names (description vs
3573 # total_item and amount vs total_amount -- another array of functions?
3574
3575 sub _condensed_total_line_generator {
3576   my ( $self, $format ) = ( shift, shift );
3577
3578   my ( $f, $prefix, $suffix, $separator, $column ) =
3579     _condensed_generator_defaults($format);
3580   my $style = '';
3581
3582   if ($format eq 'latex') {
3583     $prefix = "& ";
3584     $suffix = "\\\\\n";
3585     $separator = " & \n";
3586     $column =
3587       sub { my ($d,$a,$s,$w) = @_;
3588             return "\\multicolumn{$s}{$a}{\\makebox[$w][$a]{$d}}";
3589           };
3590   }elsif ( $format eq 'html' ) {
3591     $prefix = '';
3592     $suffix = '';
3593     $separator = '';
3594     $style = 'border-top: 3px solid #000000;border-bottom: 3px solid #000000;';
3595     $column =
3596       sub { my ($d,$a,$s,$w) = @_;
3597             return qq!<td align="$html_align{$a}" style="$style">$d</td>!;
3598       };
3599   }
3600
3601
3602   sub {
3603     my @args = @_;
3604     my @result = ();
3605
3606     foreach  (my $i = 0; $f->{label}->[$i]; $i++) {
3607       push @result,
3608         &{$column}( &{$f->{fields}->[$i]}(@args),
3609                     map { $f->{$_}->[$i] } qw(align span width)
3610                   );
3611     }
3612
3613     $prefix. join( $separator, @result ). $suffix;
3614   };
3615
3616 }
3617
3618 #sub _items_extra_usage_sections {
3619 #  my $self = shift;
3620 #  my $escape = shift;
3621 #
3622 #  my %sections = ();
3623 #
3624 #  my %usage_class =  map{ $_->classname, $_ } qsearch('usage_class', {});
3625 #  foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
3626 #  {
3627 #    next unless $cust_bill_pkg->pkgnum > 0;
3628 #
3629 #    foreach my $section ( keys %usage_class ) {
3630 #
3631 #      my $usage = $cust_bill_pkg->usage($section);
3632 #
3633 #      next unless $usage && $usage > 0;
3634 #
3635 #      $sections{$section} ||= 0;
3636 #      $sections{$section} += $usage;
3637 #
3638 #    }
3639 #
3640 #  }
3641 #
3642 #  map { { 'description' => &{$escape}($_),
3643 #          'subtotal'    => $sections{$_},
3644 #          'summarized'  => '',
3645 #          'tax_section' => '',
3646 #        }
3647 #      }
3648 #    sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
3649 #
3650 #}
3651
3652 sub _items_extra_usage_sections {
3653   my $self = shift;
3654   my $escape = shift;
3655   my $format = shift;
3656
3657   my %sections = ();
3658   my %classnums = ();
3659   my %lines = ();
3660
3661   my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
3662   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
3663     next unless $cust_bill_pkg->pkgnum > 0;
3664
3665     foreach my $classnum ( keys %usage_class ) {
3666       my $section = $usage_class{$classnum}->classname;
3667       $classnums{$section} = $classnum;
3668
3669       foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
3670         my $amount = $detail->amount;
3671         next unless $amount && $amount > 0;
3672  
3673         $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
3674         $sections{$section}{amount} += $amount;  #subtotal
3675         $sections{$section}{calls}++;
3676         $sections{$section}{duration} += $detail->duration;
3677
3678         my $desc = $detail->regionname; 
3679         my $description = $desc;
3680         $description = substr($desc, 0, 50). '...'
3681           if $format eq 'latex' && length($desc) > 50;
3682
3683         $lines{$section}{$desc} ||= {
3684           description     => &{$escape}($description),
3685           #pkgpart         => $part_pkg->pkgpart,
3686           pkgnum          => $cust_bill_pkg->pkgnum,
3687           ref             => '',
3688           amount          => 0,
3689           calls           => 0,
3690           duration        => 0,
3691           #unit_amount     => $cust_bill_pkg->unitrecur,
3692           quantity        => $cust_bill_pkg->quantity,
3693           product_code    => 'N/A',
3694           ext_description => [],
3695         };
3696
3697         $lines{$section}{$desc}{amount} += $amount;
3698         $lines{$section}{$desc}{calls}++;
3699         $lines{$section}{$desc}{duration} += $detail->duration;
3700
3701       }
3702     }
3703   }
3704
3705   my %sectionmap = ();
3706   foreach (keys %sections) {
3707     my $usage_class = $usage_class{$classnums{$_}};
3708     $sectionmap{$_} = { 'description' => &{$escape}($_),
3709                         'amount'    => $sections{$_}{amount},    #subtotal
3710                         'calls'       => $sections{$_}{calls},
3711                         'duration'    => $sections{$_}{duration},
3712                         'summarized'  => '',
3713                         'tax_section' => '',
3714                         'sort_weight' => $usage_class->weight,
3715                         ( $usage_class->format
3716                           ? ( map { $_ => $usage_class->$_($format) }
3717                               qw( description_generator header_generator total_generator total_line_generator )
3718                             )
3719                           : ()
3720                         ), 
3721                       };
3722   }
3723
3724   my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
3725                  values %sectionmap;
3726
3727   my @lines = ();
3728   foreach my $section ( keys %lines ) {
3729     foreach my $line ( keys %{$lines{$section}} ) {
3730       my $l = $lines{$section}{$line};
3731       $l->{section}     = $sectionmap{$section};
3732       $l->{amount}      = sprintf( "%.2f", $l->{amount} );
3733       #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
3734       push @lines, $l;
3735     }
3736   }
3737
3738   return(\@sections, \@lines);
3739
3740 }
3741
3742 sub _items_svc_phone_sections {
3743   my $self = shift;
3744   my $escape = shift;
3745   my $format = shift;
3746
3747   my %sections = ();
3748   my %classnums = ();
3749   my %lines = ();
3750
3751   my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
3752
3753   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
3754     next unless $cust_bill_pkg->pkgnum > 0;
3755
3756     my @header = $cust_bill_pkg->details_header;
3757     next unless scalar(@header);
3758
3759     foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
3760
3761       my $phonenum = $detail->phonenum;
3762       next unless $phonenum;
3763
3764       my $amount = $detail->amount;
3765       next unless $amount && $amount > 0;
3766
3767       $sections{$phonenum} ||= { 'amount'      => 0,
3768                                  'calls'       => 0,
3769                                  'duration'    => 0,
3770                                  'sort_weight' => -1,
3771                                  'phonenum'    => $phonenum,
3772                                 };
3773       $sections{$phonenum}{amount} += $amount;  #subtotal
3774       $sections{$phonenum}{calls}++;
3775       $sections{$phonenum}{duration} += $detail->duration;
3776
3777       my $desc = $detail->regionname; 
3778       my $description = $desc;
3779       $description = substr($desc, 0, 50). '...'
3780         if $format eq 'latex' && length($desc) > 50;
3781
3782       $lines{$phonenum}{$desc} ||= {
3783         description     => &{$escape}($description),
3784         #pkgpart         => $part_pkg->pkgpart,
3785         pkgnum          => '',
3786         ref             => '',
3787         amount          => 0,
3788         calls           => 0,
3789         duration        => 0,
3790         #unit_amount     => '',
3791         quantity        => '',
3792         product_code    => 'N/A',
3793         ext_description => [],
3794       };
3795
3796       $lines{$phonenum}{$desc}{amount} += $amount;
3797       $lines{$phonenum}{$desc}{calls}++;
3798       $lines{$phonenum}{$desc}{duration} += $detail->duration;
3799
3800       my $line = $usage_class{$detail->classnum}->classname;
3801       $sections{"$phonenum $line"} ||=
3802         { 'amount' => 0,
3803           'calls' => 0,
3804           'duration' => 0,
3805           'sort_weight' => $usage_class{$detail->classnum}->weight,
3806           'phonenum' => $phonenum,
3807           'header'  => [ @header ],
3808         };
3809       $sections{"$phonenum $line"}{amount} += $amount;  #subtotal
3810       $sections{"$phonenum $line"}{calls}++;
3811       $sections{"$phonenum $line"}{duration} += $detail->duration;
3812
3813       $lines{"$phonenum $line"}{$desc} ||= {
3814         description     => &{$escape}($description),
3815         #pkgpart         => $part_pkg->pkgpart,
3816         pkgnum          => '',
3817         ref             => '',
3818         amount          => 0,
3819         calls           => 0,
3820         duration        => 0,
3821         #unit_amount     => '',
3822         quantity        => '',
3823         product_code    => 'N/A',
3824         ext_description => [],
3825       };
3826
3827       $lines{"$phonenum $line"}{$desc}{amount} += $amount;
3828       $lines{"$phonenum $line"}{$desc}{calls}++;
3829       $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
3830       push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
3831            $detail->formatted('format' => $format);
3832
3833     }
3834   }
3835
3836   my %sectionmap = ();
3837   my $simple = new FS::usage_class { format => 'simple' }; #bleh
3838   foreach ( keys %sections ) {
3839     my @header = @{ $sections{$_}{header} || [] };
3840     my $usage_simple =
3841       new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
3842     my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
3843     my $usage_class = $summary ? $simple : $usage_simple;
3844     my $ending = $summary ? ' usage charges' : '';
3845     my %gen_opt = ();
3846     unless ($summary) {
3847       $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
3848     }
3849     $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
3850                         'amount'    => $sections{$_}{amount},    #subtotal
3851                         'calls'       => $sections{$_}{calls},
3852                         'duration'    => $sections{$_}{duration},
3853                         'summarized'  => '',
3854                         'tax_section' => '',
3855                         'phonenum'    => $sections{$_}{phonenum},
3856                         'sort_weight' => $sections{$_}{sort_weight},
3857                         'post_total'  => $summary, #inspire pagebreak
3858                         (
3859                           ( map { $_ => $usage_class->$_($format, %gen_opt) }
3860                             qw( description_generator
3861                                 header_generator
3862                                 total_generator
3863                                 total_line_generator
3864                               )
3865                           )
3866                         ), 
3867                       };
3868   }
3869
3870   my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
3871                         $a->{sort_weight} <=> $b->{sort_weight}
3872                       }
3873                  values %sectionmap;
3874
3875   my @lines = ();
3876   foreach my $section ( keys %lines ) {
3877     foreach my $line ( keys %{$lines{$section}} ) {
3878       my $l = $lines{$section}{$line};
3879       $l->{section}     = $sectionmap{$section};
3880       $l->{amount}      = sprintf( "%.2f", $l->{amount} );
3881       #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
3882       push @lines, $l;
3883     }
3884   }
3885
3886   return(\@sections, \@lines);
3887
3888 }
3889
3890 sub _items {
3891   my $self = shift;
3892
3893   #my @display = scalar(@_)
3894   #              ? @_
3895   #              : qw( _items_previous _items_pkg );
3896   #              #: qw( _items_pkg );
3897   #              #: qw( _items_previous _items_pkg _items_tax _items_credits _items_payments );
3898   my @display = qw( _items_previous _items_pkg );
3899
3900   my @b = ();
3901   foreach my $display ( @display ) {
3902     push @b, $self->$display(@_);
3903   }
3904   @b;
3905 }
3906
3907 sub _items_previous {
3908   my $self = shift;
3909   my $cust_main = $self->cust_main;
3910   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
3911   my @b = ();
3912   foreach ( @pr_cust_bill ) {
3913     my $date = $conf->exists('invoice_show_prior_due_date')
3914                ? 'due '. $_->due_date2str($date_format)
3915                : time2str($date_format, $_->_date);
3916     push @b, {
3917       'description' => 'Previous Balance, Invoice #'. $_->invnum. " ($date)",
3918       #'pkgpart'     => 'N/A',
3919       'pkgnum'      => 'N/A',
3920       'amount'      => sprintf("%.2f", $_->owed),
3921     };
3922   }
3923   @b;
3924
3925   #{
3926   #    'description'     => 'Previous Balance',
3927   #    #'pkgpart'         => 'N/A',
3928   #    'pkgnum'          => 'N/A',
3929   #    'amount'          => sprintf("%10.2f", $pr_total ),
3930   #    'ext_description' => [ map {
3931   #                                 "Invoice ". $_->invnum.
3932   #                                 " (". time2str("%x",$_->_date). ") ".
3933   #                                 sprintf("%10.2f", $_->owed)
3934   #                         } @pr_cust_bill ],
3935
3936   #};
3937 }
3938
3939 sub _items_pkg {
3940   my $self = shift;
3941   my %options = @_;
3942   my @cust_bill_pkg = grep { $_->pkgnum } $self->cust_bill_pkg;
3943   my @items = $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3944   if ($options{section} && $options{section}->{condensed}) {
3945     my %itemshash = ();
3946     local $Storable::canonical = 1;
3947     foreach ( @items ) {
3948       my $item = { %$_ };
3949       delete $item->{ref};
3950       delete $item->{ext_description};
3951       my $key = freeze($item);
3952       $itemshash{$key} ||= 0;
3953       $itemshash{$key} ++; # += $item->{quantity};
3954     }
3955     @items = sort { $a->{description} cmp $b->{description} }
3956              map { my $i = thaw($_);
3957                    $i->{quantity} = $itemshash{$_};
3958                    $i->{amount} =
3959                      sprintf( "%.2f", $i->{quantity} * $i->{amount} );#unit_amount
3960                    $i;
3961                  }
3962              keys %itemshash;
3963   }
3964   @items;
3965 }
3966
3967 sub _taxsort {
3968   return 0 unless $a->itemdesc cmp $b->itemdesc;
3969   return -1 if $b->itemdesc eq 'Tax';
3970   return 1 if $a->itemdesc eq 'Tax';
3971   return -1 if $b->itemdesc eq 'Other surcharges';
3972   return 1 if $a->itemdesc eq 'Other surcharges';
3973   $a->itemdesc cmp $b->itemdesc;
3974 }
3975
3976 sub _items_tax {
3977   my $self = shift;
3978   my @cust_bill_pkg = sort _taxsort grep { ! $_->pkgnum } $self->cust_bill_pkg;
3979   $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
3980 }
3981
3982 sub _items_cust_bill_pkg {
3983   my $self = shift;
3984   my $cust_bill_pkg = shift;
3985   my %opt = @_;
3986
3987   my $format = $opt{format} || '';
3988   my $escape_function = $opt{escape_function} || sub { shift };
3989   my $format_function = $opt{format_function} || '';
3990   my $unsquelched = $opt{unsquelched} || '';
3991   my $section = $opt{section}->{description} if $opt{section};
3992   my $summary_page = $opt{summary_page} || '';
3993   my $multilocation = $opt{multilocation} || '';
3994
3995   my @b = ();
3996   my ($s, $r, $u) = ( undef, undef, undef );
3997   foreach my $cust_bill_pkg ( @$cust_bill_pkg )
3998   {
3999
4000     foreach ( $s, $r, ($opt{skip_usage} ? () : $u ) ) {
4001       if ( $_ && !$cust_bill_pkg->hidden ) {
4002         $_->{amount}      = sprintf( "%.2f", $_->{amount} ),
4003         $_->{amount}      =~ s/^\-0\.00$/0.00/;
4004         $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} ),
4005         push @b, { %$_ }
4006           unless $_->{amount} == 0;
4007         $_ = undef;
4008       }
4009     }
4010
4011     foreach my $display ( grep { defined($section)
4012                                  ? $_->section eq $section
4013                                  : 1
4014                                }
4015                           grep { !$_->summary || !$summary_page }
4016                           $cust_bill_pkg->cust_bill_pkg_display
4017                         )
4018     {
4019
4020       my $type = $display->type;
4021
4022       my $desc = $cust_bill_pkg->desc;
4023       $desc = substr($desc, 0, 50). '...'
4024         if $format eq 'latex' && length($desc) > 50;
4025
4026       my %details_opt = ( 'format'          => $format,
4027                           'escape_function' => $escape_function,
4028                           'format_function' => $format_function,
4029                         );
4030
4031       if ( $cust_bill_pkg->pkgnum > 0 ) {
4032
4033         my $cust_pkg = $cust_bill_pkg->cust_pkg;
4034
4035         if ( $cust_bill_pkg->setup != 0 && (!$type || $type eq 'S') ) {
4036
4037           my $description = $desc;
4038           $description .= ' Setup' if $cust_bill_pkg->recur != 0;
4039
4040           my @d = ();
4041           unless ( $cust_pkg->part_pkg->hide_svc_detail
4042                 || $cust_bill_pkg->hidden )
4043           {
4044             push @d, map &{$escape_function}($_),
4045                          $cust_pkg->h_labels_short($self->_date);
4046             if ( $multilocation ) {
4047               my $loc = $cust_pkg->location_label;
4048               $loc = substr($desc, 0, 50). '...'
4049                 if $format eq 'latex' && length($loc) > 50;
4050               push @d, &{$escape_function}($loc);
4051             }
4052           }
4053           push @d, $cust_bill_pkg->details(%details_opt)
4054             if $cust_bill_pkg->recur == 0;
4055
4056           if ( $cust_bill_pkg->hidden ) {
4057             $s->{amount}      += $cust_bill_pkg->setup;
4058             $s->{unit_amount} += $cust_bill_pkg->unitsetup;
4059             push @{ $s->{ext_description} }, @d;
4060           } else {
4061             $s = {
4062               description     => $description,
4063               #pkgpart         => $part_pkg->pkgpart,
4064               pkgnum          => $cust_bill_pkg->pkgnum,
4065               amount          => $cust_bill_pkg->setup,
4066               unit_amount     => $cust_bill_pkg->unitsetup,
4067               quantity        => $cust_bill_pkg->quantity,
4068               ext_description => \@d,
4069             };
4070           };
4071
4072         }
4073
4074         if ( $cust_bill_pkg->recur != 0 &&
4075              ( !$type || $type eq 'R' || $type eq 'U' )
4076            )
4077         {
4078
4079           my $is_summary = $display->summary;
4080           my $description = ($is_summary && $type && $type eq 'U')
4081                             ? "Usage charges" : $desc;
4082
4083           unless ( $conf->exists('disable_line_item_date_ranges') ) {
4084             $description .= " (" . time2str($date_format, $cust_bill_pkg->sdate).
4085                             " - ". time2str($date_format, $cust_bill_pkg->edate). ")";
4086           }
4087
4088           my @d = ();
4089
4090           #at least until cust_bill_pkg has "past" ranges in addition to
4091           #the "future" sdate/edate ones... see #3032
4092           my @dates = ( $self->_date );
4093           my $prev = $cust_bill_pkg->previous_cust_bill_pkg;
4094           push @dates, $prev->sdate if $prev;
4095
4096           unless ( $cust_pkg->part_pkg->hide_svc_detail
4097                 || $cust_bill_pkg->itemdesc
4098                 || $cust_bill_pkg->hidden
4099                 || $is_summary && $type && $type eq 'U' )
4100           {
4101             push @d, map &{$escape_function}($_),
4102                          $cust_pkg->h_labels_short(@dates)
4103                                                    #$cust_bill_pkg->edate,
4104                                                    #$cust_bill_pkg->sdate)
4105             ;
4106             if ( $multilocation ) {
4107               my $loc = $cust_pkg->location_label;
4108               $loc = substr($desc, 0, 50). '...'
4109                 if $format eq 'latex' && length($loc) > 50;
4110               push @d, &{$escape_function}($loc);
4111             }
4112           }
4113
4114           push @d, $cust_bill_pkg->details(%details_opt)
4115             unless ($is_summary || $type && $type eq 'R');
4116   
4117           my $amount = 0;
4118           if (!$type) {
4119             $amount = $cust_bill_pkg->recur;
4120           }elsif($type eq 'R') {
4121             $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
4122           }elsif($type eq 'U') {
4123             $amount = $cust_bill_pkg->usage;
4124           }
4125   
4126           if ( !$type || $type eq 'R' ) {
4127
4128             if ( $cust_bill_pkg->hidden ) {
4129               $r->{amount}      += $amount;
4130               $r->{unit_amount} += $cust_bill_pkg->unitrecur;
4131               push @{ $r->{ext_description} }, @d;
4132             } else {
4133               $r = {
4134                 description     => $description,
4135                 #pkgpart         => $part_pkg->pkgpart,
4136                 pkgnum          => $cust_bill_pkg->pkgnum,
4137                 amount          => $amount,
4138                 unit_amount     => $cust_bill_pkg->unitrecur,
4139                 quantity        => $cust_bill_pkg->quantity,
4140                 ext_description => \@d,
4141               };
4142             }
4143
4144           } elsif ( $amount ) {  # && $type eq 'U'
4145
4146             if ( $cust_bill_pkg->hidden ) {
4147               $u->{amount}      += $amount;
4148               $u->{unit_amount} += $cust_bill_pkg->unitrecur;
4149               push @{ $u->{ext_description} }, @d;
4150             } else {
4151               $u = {
4152                 description     => $description,
4153                 #pkgpart         => $part_pkg->pkgpart,
4154                 pkgnum          => $cust_bill_pkg->pkgnum,
4155                 amount          => $amount,
4156                 unit_amount     => $cust_bill_pkg->unitrecur,
4157                 quantity        => $cust_bill_pkg->quantity,
4158                 ext_description => \@d,
4159               };
4160             }
4161
4162           }
4163
4164         } # recurring or usage with recurring charge
4165
4166       } else { #pkgnum tax or one-shot line item (??)
4167
4168         if ( $cust_bill_pkg->setup != 0 ) {
4169           push @b, {
4170             'description' => $desc,
4171             'amount'      => sprintf("%.2f", $cust_bill_pkg->setup),
4172           };
4173         }
4174         if ( $cust_bill_pkg->recur != 0 ) {
4175           push @b, {
4176             'description' => "$desc (".
4177                              time2str($date_format, $cust_bill_pkg->sdate). ' - '.
4178                              time2str($date_format, $cust_bill_pkg->edate). ')',
4179             'amount'      => sprintf("%.2f", $cust_bill_pkg->recur),
4180           };
4181         }
4182
4183       }
4184
4185     }
4186
4187   }
4188
4189   foreach ( $s, $r, ($opt{skip_usage} ? () : $u ) ) {
4190     if ( $_  ) {
4191       $_->{amount}      = sprintf( "%.2f", $_->{amount} ),
4192       $_->{amount}      =~ s/^\-0\.00$/0.00/;
4193       $_->{unit_amount} = sprintf( "%.2f", $_->{unit_amount} ),
4194       push @b, { %$_ }
4195         unless $_->{amount} == 0;
4196     }
4197   }
4198
4199   @b;
4200
4201 }
4202
4203 sub _items_credits {
4204   my( $self, %opt ) = @_;
4205   my $trim_len = $opt{'trim_len'} || 60;
4206
4207   my @b;
4208   #credits
4209   foreach ( $self->cust_credited ) {
4210
4211     #something more elaborate if $_->amount ne $_->cust_credit->credited ?
4212
4213     my $reason = substr($_->cust_credit->reason, 0, $trim_len);
4214     $reason .= '...' if length($reason) < length($_->cust_credit->reason);
4215     $reason = " ($reason) " if $reason;
4216
4217     push @b, {
4218       #'description' => 'Credit ref\#'. $_->crednum.
4219       #                 " (". time2str("%x",$_->cust_credit->_date) .")".
4220       #                 $reason,
4221       'description' => 'Credit applied '.
4222                        time2str($date_format,$_->cust_credit->_date). $reason,
4223       'amount'      => sprintf("%.2f",$_->amount),
4224     };
4225   }
4226
4227   @b;
4228
4229 }
4230
4231 sub _items_payments {
4232   my $self = shift;
4233
4234   my @b;
4235   #get & print payments
4236   foreach ( $self->cust_bill_pay ) {
4237
4238     #something more elaborate if $_->amount ne ->cust_pay->paid ?
4239
4240     push @b, {
4241       'description' => "Payment received ".
4242                        time2str($date_format,$_->cust_pay->_date ),
4243       'amount'      => sprintf("%.2f", $_->amount )
4244     };
4245   }
4246
4247   @b;
4248
4249 }
4250
4251 =item call_details [ OPTION => VALUE ... ]
4252
4253 Returns an array of CSV strings representing the call details for this invoice
4254 The only option available is the boolean prepend_billed_number
4255
4256 =cut
4257
4258 sub call_details {
4259   my ($self, %opt) = @_;
4260
4261   my $format_function = sub { shift };
4262
4263   if ($opt{prepend_billed_number}) {
4264     $format_function = sub {
4265       my $detail = shift;
4266       my $row = shift;
4267
4268       $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
4269       
4270     };
4271   }
4272
4273   my @details = map { $_->details( 'format_function' => $format_function,
4274                                    'escape_function' => sub{ return() },
4275                                  )
4276                     }
4277                   grep { $_->pkgnum }
4278                   $self->cust_bill_pkg;
4279   my $header = $details[0];
4280   ( $header, grep { $_ ne $header } @details );
4281 }
4282
4283
4284 =back
4285
4286 =head1 SUBROUTINES
4287
4288 =over 4
4289
4290 =item process_reprint
4291
4292 =cut
4293
4294 sub process_reprint {
4295   process_re_X('print', @_);
4296 }
4297
4298 =item process_reemail
4299
4300 =cut
4301
4302 sub process_reemail {
4303   process_re_X('email', @_);
4304 }
4305
4306 =item process_refax
4307
4308 =cut
4309
4310 sub process_refax {
4311   process_re_X('fax', @_);
4312 }
4313
4314 =item process_reftp
4315
4316 =cut
4317
4318 sub process_reftp {
4319   process_re_X('ftp', @_);
4320 }
4321
4322 =item respool
4323
4324 =cut
4325
4326 sub process_respool {
4327   process_re_X('spool', @_);
4328 }
4329
4330 use Storable qw(thaw);
4331 use Data::Dumper;
4332 use MIME::Base64;
4333 sub process_re_X {
4334   my( $method, $job ) = ( shift, shift );
4335   warn "$me process_re_X $method for job $job\n" if $DEBUG;
4336
4337   my $param = thaw(decode_base64(shift));
4338   warn Dumper($param) if $DEBUG;
4339
4340   re_X(
4341     $method,
4342     $job,
4343     %$param,
4344   );
4345
4346 }
4347
4348 sub re_X {
4349   my($method, $job, %param ) = @_;
4350   if ( $DEBUG ) {
4351     warn "re_X $method for job $job with param:\n".
4352          join( '', map { "  $_ => ". $param{$_}. "\n" } keys %param );
4353   }
4354
4355   #some false laziness w/search/cust_bill.html
4356   my $distinct = '';
4357   my $orderby = 'ORDER BY cust_bill._date';
4358
4359   my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
4360
4361   my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
4362      
4363   my @cust_bill = qsearch( {
4364     #'select'    => "cust_bill.*",
4365     'table'     => 'cust_bill',
4366     'addl_from' => $addl_from,
4367     'hashref'   => {},
4368     'extra_sql' => $extra_sql,
4369     'order_by'  => $orderby,
4370     'debug' => 1,
4371   } );
4372
4373   $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
4374
4375   warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
4376     if $DEBUG;
4377
4378   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
4379   foreach my $cust_bill ( @cust_bill ) {
4380     $cust_bill->$method();
4381
4382     if ( $job ) { #progressbar foo
4383       $num++;
4384       if ( time - $min_sec > $last ) {
4385         my $error = $job->update_statustext(
4386           int( 100 * $num / scalar(@cust_bill) )
4387         );
4388         die $error if $error;
4389         $last = time;
4390       }
4391     }
4392
4393   }
4394
4395 }
4396
4397 =back
4398
4399 =head1 CLASS METHODS
4400
4401 =over 4
4402
4403 =item owed_sql
4404
4405 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
4406
4407 =cut
4408
4409 sub owed_sql {
4410   my ($class, $start, $end) = @_;
4411   'charged - '. 
4412     $class->paid_sql($start, $end). ' - '. 
4413     $class->credited_sql($start, $end);
4414 }
4415
4416 =item net_sql
4417
4418 Returns an SQL fragment to retreive the net amount (charged minus credited).
4419
4420 =cut
4421
4422 sub net_sql {
4423   my ($class, $start, $end) = @_;
4424   'charged - '. $class->credited_sql($start, $end);
4425 }
4426
4427 =item paid_sql
4428
4429 Returns an SQL fragment to retreive the amount paid against this invoice.
4430
4431 =cut
4432
4433 sub paid_sql {
4434   my ($class, $start, $end) = @_;
4435   $start &&= "AND cust_bill_pay._date <= $start";
4436   $end   &&= "AND cust_bill_pay._date > $end";
4437   $start = '' unless defined($start);
4438   $end   = '' unless defined($end);
4439   "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
4440        WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end  )";
4441 }
4442
4443 =item credited_sql
4444
4445 Returns an SQL fragment to retreive the amount credited against this invoice.
4446
4447 =cut
4448
4449 sub credited_sql {
4450   my ($class, $start, $end) = @_;
4451   $start &&= "AND cust_credit_bill._date <= $start";
4452   $end   &&= "AND cust_credit_bill._date >  $end";
4453   $start = '' unless defined($start);
4454   $end   = '' unless defined($end);
4455   "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
4456        WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end  )";
4457 }
4458
4459 =item search_sql_where HASHREF
4460
4461 Class method which returns an SQL WHERE fragment to search for parameters
4462 specified in HASHREF.  Valid parameters are
4463
4464 =over 4
4465
4466 =item _date
4467
4468 List reference of start date, end date, as UNIX timestamps.
4469
4470 =item invnum_min
4471
4472 =item invnum_max
4473
4474 =item agentnum
4475
4476 =item charged
4477
4478 List reference of charged limits (exclusive).
4479
4480 =item owed
4481
4482 List reference of charged limits (exclusive).
4483
4484 =item open
4485
4486 flag, return open invoices only
4487
4488 =item net
4489
4490 flag, return net invoices only
4491
4492 =item days
4493
4494 =item newest_percust
4495
4496 =back
4497
4498 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
4499
4500 =cut
4501
4502 sub search_sql_where {
4503   my($class, $param) = @_;
4504   if ( $DEBUG ) {
4505     warn "$me search_sql_where called with params: \n".
4506          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
4507   }
4508
4509   my @search = ();
4510
4511   #agentnum
4512   if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
4513     push @search, "cust_main.agentnum = $1";
4514   }
4515
4516   #_date
4517   if ( $param->{_date} ) {
4518     my($beginning, $ending) = @{$param->{_date}};
4519
4520     push @search, "cust_bill._date >= $beginning",
4521                   "cust_bill._date <  $ending";
4522   }
4523
4524   #invnum
4525   if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
4526     push @search, "cust_bill.invnum >= $1";
4527   }
4528   if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
4529     push @search, "cust_bill.invnum <= $1";
4530   }
4531
4532   #charged
4533   if ( $param->{charged} ) {
4534     my @charged = ref($param->{charged})
4535                     ? @{ $param->{charged} }
4536                     : ($param->{charged});
4537
4538     push @search, map { s/^charged/cust_bill.charged/; $_; }
4539                       @charged;
4540   }
4541
4542   my $owed_sql = FS::cust_bill->owed_sql;
4543
4544   #owed
4545   if ( $param->{owed} ) {
4546     my @owed = ref($param->{owed})
4547                  ? @{ $param->{owed} }
4548                  : ($param->{owed});
4549     push @search, map { s/^owed/$owed_sql/; $_; }
4550                       @owed;
4551   }
4552
4553   #open/net flags
4554   push @search, "0 != $owed_sql"
4555     if $param->{'open'};
4556   push @search, '0 != '. FS::cust_bill->net_sql
4557     if $param->{'net'};
4558
4559   #days
4560   push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
4561     if $param->{'days'};
4562
4563   #newest_percust
4564   if ( $param->{'newest_percust'} ) {
4565
4566     #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
4567     #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
4568
4569     my @newest_where = map { my $x = $_;
4570                              $x =~ s/\bcust_bill\./newest_cust_bill./g;
4571                              $x;
4572                            }
4573                            grep ! /^cust_main./, @search;
4574     my $newest_where = scalar(@newest_where)
4575                          ? ' AND '. join(' AND ', @newest_where)
4576                          : '';
4577
4578
4579     push @search, "cust_bill._date = (
4580       SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
4581         WHERE newest_cust_bill.custnum = cust_bill.custnum
4582           $newest_where
4583     )";
4584
4585   }
4586
4587   #agent virtualization
4588   my $curuser = $FS::CurrentUser::CurrentUser;
4589   if ( $curuser->username eq 'fs_queue'
4590        && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
4591     my $username = $1;
4592     my $newuser = qsearchs('access_user', {
4593       'username' => $username,
4594       'disabled' => '',
4595     } );
4596     if ( $newuser ) {
4597       $curuser = $newuser;
4598     } else {
4599       warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
4600     }
4601   }
4602   push @search, $curuser->agentnums_sql;
4603
4604   join(' AND ', @search );
4605
4606 }
4607
4608 =back
4609
4610 =head1 BUGS
4611
4612 The delete method.
4613
4614 =head1 SEE ALSO
4615
4616 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
4617 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base
4618 documentation.
4619
4620 =cut
4621
4622 1;
4623