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