localize dates that will appear on invoices, #24850
[freeside.git] / FS / FS / cust_bill.pm
1 package FS::cust_bill;
2 use base qw( FS::Template_Mixin FS::cust_main_Mixin FS::Record );
3
4 use strict;
5 use vars qw( $DEBUG $me $date_format );
6              # but NOT $conf
7 use Fcntl qw(:flock); #for spool_csv
8 use Cwd;
9 use List::Util qw(min max sum);
10 use Date::Format;
11 use File::Temp 0.14;
12 use HTML::Entities;
13 use Storable qw( freeze thaw );
14 use GD::Barcode;
15 use FS::UID qw( datasrc );
16 use FS::Misc qw( send_email send_fax do_print );
17 use FS::Record qw( qsearch qsearchs dbh );
18 use FS::cust_main;
19 use FS::cust_statement;
20 use FS::cust_bill_pkg;
21 use FS::cust_bill_pkg_display;
22 use FS::cust_bill_pkg_detail;
23 use FS::cust_credit;
24 use FS::cust_pay;
25 use FS::cust_pkg;
26 use FS::cust_credit_bill;
27 use FS::pay_batch;
28 use FS::cust_pay_batch;
29 use FS::cust_bill_event;
30 use FS::cust_event;
31 use FS::part_pkg;
32 use FS::cust_bill_pay;
33 use FS::cust_bill_pay_batch;
34 use FS::part_bill_event;
35 use FS::payby;
36 use FS::bill_batch;
37 use FS::cust_bill_batch;
38 use FS::cust_bill_pay_pkg;
39 use FS::cust_credit_bill_pkg;
40 use FS::discount_plan;
41 use FS::cust_bill_void;
42 use FS::L10N;
43
44 $DEBUG = 0;
45 $me = '[FS::cust_bill]';
46
47 #ask FS::UID to run this stuff for us later
48 FS::UID->install_callback( sub { 
49   my $conf = new FS::Conf; #global
50   $date_format      = $conf->config('date_format')      || '%x'; #/YY
51 } );
52
53 =head1 NAME
54
55 FS::cust_bill - Object methods for cust_bill records
56
57 =head1 SYNOPSIS
58
59   use FS::cust_bill;
60
61   $record = new FS::cust_bill \%hash;
62   $record = new FS::cust_bill { 'column' => 'value' };
63
64   $error = $record->insert;
65
66   $error = $new_record->replace($old_record);
67
68   $error = $record->delete;
69
70   $error = $record->check;
71
72   ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
73
74   @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
75
76   ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
77
78   @cust_pay_objects = $cust_bill->cust_pay;
79
80   $tax_amount = $record->tax;
81
82   @lines = $cust_bill->print_text;
83   @lines = $cust_bill->print_text('time' => $time);
84
85 =head1 DESCRIPTION
86
87 An FS::cust_bill object represents an invoice; a declaration that a customer
88 owes you money.  The specific charges are itemized as B<cust_bill_pkg> records
89 (see L<FS::cust_bill_pkg>).  FS::cust_bill inherits from FS::Record.  The
90 following fields are currently supported:
91
92 Regular fields
93
94 =over 4
95
96 =item invnum - primary key (assigned automatically for new invoices)
97
98 =item custnum - customer (see L<FS::cust_main>)
99
100 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
101 L<Time::Local> and L<Date::Parse> for conversion functions.
102
103 =item charged - amount of this invoice
104
105 =item invoice_terms - optional terms override for this specific invoice
106
107 =back
108
109 Customer info at invoice generation time
110
111 =over 4
112
113 =item billing_balance - the customer's balance at the time the invoice was 
114 generated (not including charges on this invoice)
115
116 =item previous_balance - the billing_balance of this customer's previous 
117 invoice plus the charges on that invoice
118
119 =back
120
121 Deprecated
122
123 =over 4
124
125 =item printed - deprecated
126
127 =back
128
129 Specific use cases
130
131 =over 4
132
133 =item closed - books closed flag, empty or `Y'
134
135 =item statementnum - invoice aggregation (see L<FS::cust_statement>)
136
137 =item agent_invid - legacy invoice number
138
139 =item promised_date - customer promised payment date, for collection
140
141 =back
142
143 =head1 METHODS
144
145 =over 4
146
147 =item new HASHREF
148
149 Creates a new invoice.  To add the invoice to the database, see L<"insert">.
150 Invoices are normally created by calling the bill method of a customer object
151 (see L<FS::cust_main>).
152
153 =cut
154
155 sub table { 'cust_bill'; }
156
157 # should be the ONLY occurrence of "Invoice" in invoice rendering code.
158 # (except email_subject and invnum_date_pretty)
159 sub notice_name {
160   my $self = shift;
161   $self->conf->config('notice_name') || 'Invoice'
162 }
163
164 sub cust_linked { $_[0]->cust_main_custnum; } 
165 sub cust_unlinked_msg {
166   my $self = shift;
167   "WARNING: can't find cust_main.custnum ". $self->custnum.
168   ' (cust_bill.invnum '. $self->invnum. ')';
169 }
170
171 =item insert
172
173 Adds this invoice to the database ("Posts" the invoice).  If there is an error,
174 returns the error, otherwise returns false.
175
176 =cut
177
178 sub insert {
179   my $self = shift;
180   warn "$me insert called\n" if $DEBUG;
181
182   local $SIG{HUP} = 'IGNORE';
183   local $SIG{INT} = 'IGNORE';
184   local $SIG{QUIT} = 'IGNORE';
185   local $SIG{TERM} = 'IGNORE';
186   local $SIG{TSTP} = 'IGNORE';
187   local $SIG{PIPE} = 'IGNORE';
188
189   my $oldAutoCommit = $FS::UID::AutoCommit;
190   local $FS::UID::AutoCommit = 0;
191   my $dbh = dbh;
192
193   my $error = $self->SUPER::insert;
194   if ( $error ) {
195     $dbh->rollback if $oldAutoCommit;
196     return $error;
197   }
198
199   if ( $self->get('cust_bill_pkg') ) {
200     foreach my $cust_bill_pkg ( @{$self->get('cust_bill_pkg')} ) {
201       $cust_bill_pkg->invnum($self->invnum);
202       my $error = $cust_bill_pkg->insert;
203       if ( $error ) {
204         $dbh->rollback if $oldAutoCommit;
205         return "can't create invoice line item: $error";
206       }
207     }
208   }
209
210   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
211   '';
212
213 }
214
215 =item void
216
217 Voids this invoice: deletes the invoice and adds a record of the voided invoice
218 to the FS::cust_bill_void table (and related tables starting from
219 FS::cust_bill_pkg_void).
220
221 =cut
222
223 sub void {
224   my $self = shift;
225   my $reason = scalar(@_) ? shift : '';
226
227   local $SIG{HUP} = 'IGNORE';
228   local $SIG{INT} = 'IGNORE';
229   local $SIG{QUIT} = 'IGNORE';
230   local $SIG{TERM} = 'IGNORE';
231   local $SIG{TSTP} = 'IGNORE';
232   local $SIG{PIPE} = 'IGNORE';
233
234   my $oldAutoCommit = $FS::UID::AutoCommit;
235   local $FS::UID::AutoCommit = 0;
236   my $dbh = dbh;
237
238   my $cust_bill_void = new FS::cust_bill_void ( {
239     map { $_ => $self->get($_) } $self->fields
240   } );
241   $cust_bill_void->reason($reason);
242   my $error = $cust_bill_void->insert;
243   if ( $error ) {
244     $dbh->rollback if $oldAutoCommit;
245     return $error;
246   }
247
248   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
249     my $error = $cust_bill_pkg->void($reason);
250     if ( $error ) {
251       $dbh->rollback if $oldAutoCommit;
252       return $error;
253     }
254   }
255
256   $error = $self->delete;
257   if ( $error ) {
258     $dbh->rollback if $oldAutoCommit;
259     return $error;
260   }
261
262   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
263
264   '';
265
266 }
267
268 =item delete
269
270 This method now works but you probably shouldn't use it.  Instead, apply a
271 credit against the invoice, or use the new void method.
272
273 Using this method to delete invoices outright is really, really bad.  There
274 would be no record you ever posted this invoice, and there are no check to
275 make sure charged = 0 or that there are no associated cust_bill_pkg records.
276
277 Really, don't use it.
278
279 =cut
280
281 sub delete {
282   my $self = shift;
283   return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
284
285   local $SIG{HUP} = 'IGNORE';
286   local $SIG{INT} = 'IGNORE';
287   local $SIG{QUIT} = 'IGNORE';
288   local $SIG{TERM} = 'IGNORE';
289   local $SIG{TSTP} = 'IGNORE';
290   local $SIG{PIPE} = 'IGNORE';
291
292   my $oldAutoCommit = $FS::UID::AutoCommit;
293   local $FS::UID::AutoCommit = 0;
294   my $dbh = dbh;
295
296   foreach my $table (qw(
297     cust_bill_event
298     cust_event
299     cust_credit_bill
300     cust_bill_pay
301     cust_pay_batch
302     cust_bill_pay_batch
303     cust_bill_batch
304     cust_bill_pkg
305   )) {
306
307     foreach my $linked ( $self->$table() ) {
308       my $error = $linked->delete;
309       if ( $error ) {
310         $dbh->rollback if $oldAutoCommit;
311         return $error;
312       }
313     }
314
315   }
316
317   my $error = $self->SUPER::delete(@_);
318   if ( $error ) {
319     $dbh->rollback if $oldAutoCommit;
320     return $error;
321   }
322
323   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
324
325   '';
326
327 }
328
329 =item replace [ OLD_RECORD ]
330
331 You can, but probably shouldn't modify invoices...
332
333 Replaces the OLD_RECORD with this one in the database, or, if OLD_RECORD is not
334 supplied, replaces this record.  If there is an error, returns the error,
335 otherwise returns false.
336
337 =cut
338
339 #replace can be inherited from Record.pm
340
341 # replace_check is now the preferred way to #implement replace data checks
342 # (so $object->replace() works without an argument)
343
344 sub replace_check {
345   my( $new, $old ) = ( shift, shift );
346   return "Can't modify closed invoice" if $old->closed =~ /^Y/i;
347   #return "Can't change _date!" unless $old->_date eq $new->_date;
348   return "Can't change _date" unless $old->_date == $new->_date;
349   return "Can't change charged" unless $old->charged == $new->charged
350                                     || $old->charged == 0
351                                     || $new->{'Hash'}{'cc_surcharge_replace_hack'};
352
353   '';
354 }
355
356
357 =item add_cc_surcharge
358
359 Giant hack
360
361 =cut
362
363 sub add_cc_surcharge {
364     my ($self, $pkgnum, $amount) = (shift, shift, shift);
365
366     my $error;
367     my $cust_bill_pkg = new FS::cust_bill_pkg({
368                                     'invnum' => $self->invnum,
369                                     'pkgnum' => $pkgnum,
370                                     'setup' => $amount,
371                         });
372     $error = $cust_bill_pkg->insert;
373     return $error if $error;
374
375     $self->{'Hash'}{'cc_surcharge_replace_hack'} = 1;
376     $self->charged($self->charged+$amount);
377     $error = $self->replace;
378     return $error if $error;
379
380     $self->apply_payments_and_credits;
381 }
382
383
384 =item check
385
386 Checks all fields to make sure this is a valid invoice.  If there is an error,
387 returns the error, otherwise returns false.  Called by the insert and replace
388 methods.
389
390 =cut
391
392 sub check {
393   my $self = shift;
394
395   my $error =
396     $self->ut_numbern('invnum')
397     || $self->ut_foreign_key('custnum', 'cust_main', 'custnum' )
398     || $self->ut_numbern('_date')
399     || $self->ut_money('charged')
400     || $self->ut_numbern('printed')
401     || $self->ut_enum('closed', [ '', 'Y' ])
402     || $self->ut_foreign_keyn('statementnum', 'cust_statement', 'statementnum' )
403     || $self->ut_numbern('agent_invid') #varchar?
404   ;
405   return $error if $error;
406
407   $self->_date(time) unless $self->_date;
408
409   $self->printed(0) if $self->printed eq '';
410
411   $self->SUPER::check;
412 }
413
414 =item display_invnum
415
416 Returns the displayed invoice number for this invoice: agent_invid if
417 cust_bill-default_agent_invid is set and it has a value, invnum otherwise.
418
419 =cut
420
421 sub display_invnum {
422   my $self = shift;
423   my $conf = $self->conf;
424   if ( $conf->exists('cust_bill-default_agent_invid') && $self->agent_invid ){
425     return $self->agent_invid;
426   } else {
427     return $self->invnum;
428   }
429 }
430
431 =item previous_bill
432
433 Returns the customer's last invoice before this one.
434
435 =cut
436
437 sub previous_bill {
438   my $self = shift;
439   if ( !$self->get('previous_bill') ) {
440     $self->set('previous_bill', qsearchs({
441           'table'     => 'cust_bill',
442           'hashref'   => { 'custnum'  => $self->custnum,
443                            '_date'    => { op=>'<', value=>$self->_date } },
444           'order_by'  => 'ORDER BY _date DESC LIMIT 1',
445     }) );
446   }
447   $self->get('previous_bill');
448 }
449
450 =item previous
451
452 Returns a list consisting of the total previous balance for this customer, 
453 followed by the previous outstanding invoices (as FS::cust_bill objects also).
454
455 =cut
456
457 sub previous {
458   my $self = shift;
459   my $total = 0;
460   my @cust_bill = sort { $a->_date <=> $b->_date }
461     grep { $_->owed != 0 }
462       qsearch( 'cust_bill', { 'custnum' => $self->custnum,
463                               #'_date'   => { op=>'<', value=>$self->_date },
464                               'invnum'   => { op=>'<', value=>$self->invnum },
465                             } ) 
466   ;
467   foreach ( @cust_bill ) { $total += $_->owed; }
468   $total, @cust_bill;
469 }
470
471 =item enable_previous
472
473 Whether to show the 'Previous Charges' section when printing this invoice.
474 The negation of the 'disable_previous_balance' config setting.
475
476 =cut
477
478 sub enable_previous {
479   my $self = shift;
480   my $agentnum = $self->cust_main->agentnum;
481   !$self->conf->exists('disable_previous_balance', $agentnum);
482 }
483
484 =item cust_bill_pkg
485
486 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
487
488 =cut
489
490 sub cust_bill_pkg {
491   my $self = shift;
492   qsearch(
493     { 'table'    => 'cust_bill_pkg',
494       'hashref'  => { 'invnum' => $self->invnum },
495       'order_by' => 'ORDER BY billpkgnum',
496     }
497   );
498 }
499
500 =item cust_bill_pkg_pkgnum PKGNUM
501
502 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice and
503 specified pkgnum.
504
505 =cut
506
507 sub cust_bill_pkg_pkgnum {
508   my( $self, $pkgnum ) = @_;
509   qsearch(
510     { 'table'    => 'cust_bill_pkg',
511       'hashref'  => { 'invnum' => $self->invnum,
512                       'pkgnum' => $pkgnum,
513                     },
514       'order_by' => 'ORDER BY billpkgnum',
515     }
516   );
517 }
518
519 =item cust_pkg
520
521 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
522 this invoice.
523
524 =cut
525
526 sub cust_pkg {
527   my $self = shift;
528   my @cust_pkg = map { $_->pkgnum > 0 ? $_->cust_pkg : () }
529                      $self->cust_bill_pkg;
530   my %saw = ();
531   grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
532 }
533
534 =item no_auto
535
536 Returns true if any of the packages (or their definitions) corresponding to the
537 line items for this invoice have the no_auto flag set.
538
539 =cut
540
541 sub no_auto {
542   my $self = shift;
543   grep { $_->no_auto || $_->part_pkg->no_auto } $self->cust_pkg;
544 }
545
546 =item open_cust_bill_pkg
547
548 Returns the open line items for this invoice.
549
550 Note that cust_bill_pkg with both setup and recur fees are returned as two
551 separate line items, each with only one fee.
552
553 =cut
554
555 # modeled after cust_main::open_cust_bill
556 sub open_cust_bill_pkg {
557   my $self = shift;
558
559   # grep { $_->owed > 0 } $self->cust_bill_pkg
560
561   my %other = ( 'recur' => 'setup',
562                 'setup' => 'recur', );
563   my @open = ();
564   foreach my $field ( qw( recur setup )) {
565     push @open, map  { $_->set( $other{$field}, 0 ); $_; }
566                 grep { $_->owed($field) > 0 }
567                 $self->cust_bill_pkg;
568   }
569
570   @open;
571 }
572
573 =item cust_bill_event
574
575 Returns the completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
576
577 =cut
578
579 sub cust_bill_event {
580   my $self = shift;
581   qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
582 }
583
584 =item num_cust_bill_event
585
586 Returns the number of completed invoice events (deprecated, old-style events - see L<FS::cust_bill_event>) for this invoice.
587
588 =cut
589
590 sub num_cust_bill_event {
591   my $self = shift;
592   my $sql =
593     "SELECT COUNT(*) FROM cust_bill_event WHERE invnum = ?";
594   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
595   $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
596   $sth->fetchrow_arrayref->[0];
597 }
598
599 =item cust_event
600
601 Returns the new-style customer billing events (see L<FS::cust_event>) for this invoice.
602
603 =cut
604
605 #false laziness w/cust_pkg.pm
606 sub cust_event {
607   my $self = shift;
608   qsearch({
609     'table'     => 'cust_event',
610     'addl_from' => 'JOIN part_event USING ( eventpart )',
611     'hashref'   => { 'tablenum' => $self->invnum },
612     'extra_sql' => " AND eventtable = 'cust_bill' ",
613   });
614 }
615
616 =item num_cust_event
617
618 Returns the number of new-style customer billing events (see L<FS::cust_event>) for this invoice.
619
620 =cut
621
622 #false laziness w/cust_pkg.pm
623 sub num_cust_event {
624   my $self = shift;
625   my $sql =
626     "SELECT COUNT(*) FROM cust_event JOIN part_event USING ( eventpart ) ".
627     "  WHERE tablenum = ? AND eventtable = 'cust_bill'";
628   my $sth = dbh->prepare($sql) or die  dbh->errstr. " preparing $sql"; 
629   $sth->execute($self->invnum) or die $sth->errstr. " executing $sql";
630   $sth->fetchrow_arrayref->[0];
631 }
632
633 =item cust_main
634
635 Returns the customer (see L<FS::cust_main>) for this invoice.
636
637 =cut
638
639 sub cust_main {
640   my $self = shift;
641   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
642 }
643
644 =item cust_suspend_if_balance_over AMOUNT
645
646 Suspends the customer associated with this invoice if the total amount owed on
647 this invoice and all older invoices is greater than the specified amount.
648
649 Returns a list: an empty list on success or a list of errors.
650
651 =cut
652
653 sub cust_suspend_if_balance_over {
654   my( $self, $amount ) = ( shift, shift );
655   my $cust_main = $self->cust_main;
656   if ( $cust_main->total_owed_date($self->_date) < $amount ) {
657     return ();
658   } else {
659     $cust_main->suspend(@_);
660   }
661 }
662
663 =item cust_credit
664
665 Depreciated.  See the cust_credited method.
666
667  #Returns a list consisting of the total previous credited (see
668  #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
669  #outstanding credits (FS::cust_credit objects).
670
671 =cut
672
673 sub cust_credit {
674   use Carp;
675   croak "FS::cust_bill->cust_credit depreciated; see ".
676         "FS::cust_bill->cust_credit_bill";
677   #my $self = shift;
678   #my $total = 0;
679   #my @cust_credit = sort { $a->_date <=> $b->_date }
680   #  grep { $_->credited != 0 && $_->_date < $self->_date }
681   #    qsearch('cust_credit', { 'custnum' => $self->custnum } )
682   #;
683   #foreach (@cust_credit) { $total += $_->credited; }
684   #$total, @cust_credit;
685 }
686
687 =item cust_pay
688
689 Depreciated.  See the cust_bill_pay method.
690
691 #Returns all payments (see L<FS::cust_pay>) for this invoice.
692
693 =cut
694
695 sub cust_pay {
696   use Carp;
697   croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
698   #my $self = shift;
699   #sort { $a->_date <=> $b->_date }
700   #  qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
701   #;
702 }
703
704 sub cust_pay_batch {
705   my $self = shift;
706   qsearch('cust_pay_batch', { 'invnum' => $self->invnum } );
707 }
708
709 sub cust_bill_pay_batch {
710   my $self = shift;
711   qsearch('cust_bill_pay_batch', { 'invnum' => $self->invnum } );
712 }
713
714 =item cust_bill_pay
715
716 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
717
718 =cut
719
720 sub cust_bill_pay {
721   my $self = shift;
722   map { $_ } #return $self->num_cust_bill_pay unless wantarray;
723   sort { $a->_date <=> $b->_date }
724     qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
725 }
726
727 =item cust_credited
728
729 =item cust_credit_bill
730
731 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
732
733 =cut
734
735 sub cust_credited {
736   my $self = shift;
737   map { $_ } #return $self->num_cust_credit_bill unless wantarray;
738   sort { $a->_date <=> $b->_date }
739     qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
740   ;
741 }
742
743 sub cust_credit_bill {
744   shift->cust_credited(@_);
745 }
746
747 #=item cust_bill_pay_pkgnum PKGNUM
748 #
749 #Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
750 #with matching pkgnum.
751 #
752 #=cut
753 #
754 #sub cust_bill_pay_pkgnum {
755 #  my( $self, $pkgnum ) = @_;
756 #  map { $_ } #return $self->num_cust_bill_pay_pkgnum($pkgnum) unless wantarray;
757 #  sort { $a->_date <=> $b->_date }
758 #    qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum,
759 #                                'pkgnum' => $pkgnum,
760 #                              }
761 #           );
762 #}
763
764 =item cust_bill_pay_pkg PKGNUM
765
766 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice
767 applied against the matching pkgnum.
768
769 =cut
770
771 sub cust_bill_pay_pkg {
772   my( $self, $pkgnum ) = @_;
773
774   qsearch({
775     'select'    => 'cust_bill_pay_pkg.*',
776     'table'     => 'cust_bill_pay_pkg',
777     'addl_from' => ' LEFT JOIN cust_bill_pay USING ( billpaynum ) '.
778                    ' LEFT JOIN cust_bill_pkg USING ( billpkgnum ) ',
779     'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
780                    "   AND cust_bill_pkg.pkgnum = $pkgnum",
781   });
782
783 }
784
785 #=item cust_credited_pkgnum PKGNUM
786 #
787 #=item cust_credit_bill_pkgnum PKGNUM
788 #
789 #Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice
790 #with matching pkgnum.
791 #
792 #=cut
793 #
794 #sub cust_credited_pkgnum {
795 #  my( $self, $pkgnum ) = @_;
796 #  map { $_ } #return $self->num_cust_credit_bill_pkgnum($pkgnum) unless wantarray;
797 #  sort { $a->_date <=> $b->_date }
798 #    qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum,
799 #                                   'pkgnum' => $pkgnum,
800 #                                 }
801 #           );
802 #}
803 #
804 #sub cust_credit_bill_pkgnum {
805 #  shift->cust_credited_pkgnum(@_);
806 #}
807
808 =item cust_credit_bill_pkg PKGNUM
809
810 Returns all credit applications (see L<FS::cust_credit_bill>) for this invoice
811 applied against the matching pkgnum.
812
813 =cut
814
815 sub cust_credit_bill_pkg {
816   my( $self, $pkgnum ) = @_;
817
818   qsearch({
819     'select'    => 'cust_credit_bill_pkg.*',
820     'table'     => 'cust_credit_bill_pkg',
821     'addl_from' => ' LEFT JOIN cust_credit_bill USING ( creditbillnum ) '.
822                    ' LEFT JOIN cust_bill_pkg    USING ( billpkgnum    ) ',
823     'extra_sql' => ' WHERE cust_bill_pkg.invnum = '. $self->invnum.
824                    "   AND cust_bill_pkg.pkgnum = $pkgnum",
825   });
826
827 }
828
829 =item cust_bill_batch
830
831 Returns all invoice batch records (L<FS::cust_bill_batch>) for this invoice.
832
833 =cut
834
835 sub cust_bill_batch {
836   my $self = shift;
837   qsearch('cust_bill_batch', { 'invnum' => $self->invnum });
838 }
839
840 =item discount_plans
841
842 Returns all discount plans (L<FS::discount_plan>) for this invoice, as a 
843 hash keyed by term length.
844
845 =cut
846
847 sub discount_plans {
848   my $self = shift;
849   FS::discount_plan->all($self);
850 }
851
852 =item tax
853
854 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
855
856 =cut
857
858 sub tax {
859   my $self = shift;
860   my $total = 0;
861   my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
862                                              'pkgnum' => 0 } );
863   foreach (@taxlines) { $total += $_->setup; }
864   $total;
865 }
866
867 =item owed
868
869 Returns the amount owed (still outstanding) on this invoice, which is charged
870 minus all payment applications (see L<FS::cust_bill_pay>) and credit
871 applications (see L<FS::cust_credit_bill>).
872
873 =cut
874
875 sub owed {
876   my $self = shift;
877   my $balance = $self->charged;
878   $balance -= $_->amount foreach ( $self->cust_bill_pay );
879   $balance -= $_->amount foreach ( $self->cust_credited );
880   $balance = sprintf( "%.2f", $balance);
881   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
882   $balance;
883 }
884
885 sub owed_pkgnum {
886   my( $self, $pkgnum ) = @_;
887
888   #my $balance = $self->charged;
889   my $balance = 0;
890   $balance += $_->setup + $_->recur for $self->cust_bill_pkg_pkgnum($pkgnum);
891
892   $balance -= $_->amount            for $self->cust_bill_pay_pkg($pkgnum);
893   $balance -= $_->amount            for $self->cust_credit_bill_pkg($pkgnum);
894
895   $balance = sprintf( "%.2f", $balance);
896   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
897   $balance;
898 }
899
900 =item hide
901
902 Returns true if this invoice should be hidden.  See the
903 selfservice-hide_invoices-taxclass configuraiton setting.
904
905 =cut
906
907 sub hide {
908   my $self = shift;
909   my $conf = $self->conf;
910   my $hide_taxclass = $conf->config('selfservice-hide_invoices-taxclass')
911     or return '';
912   my @cust_bill_pkg = $self->cust_bill_pkg;
913   my @part_pkg = grep $_, map $_->part_pkg, @cust_bill_pkg;
914   ! grep { $_->taxclass ne $hide_taxclass } @part_pkg;
915 }
916
917 =item apply_payments_and_credits [ OPTION => VALUE ... ]
918
919 Applies unapplied payments and credits to this invoice.
920
921 A hash of optional arguments may be passed.  Currently "manual" is supported.
922 If true, a payment receipt is sent instead of a statement when
923 'payment_receipt_email' configuration option is set.
924
925 If there is an error, returns the error, otherwise returns false.
926
927 =cut
928
929 sub apply_payments_and_credits {
930   my( $self, %options ) = @_;
931   my $conf = $self->conf;
932
933   local $SIG{HUP} = 'IGNORE';
934   local $SIG{INT} = 'IGNORE';
935   local $SIG{QUIT} = 'IGNORE';
936   local $SIG{TERM} = 'IGNORE';
937   local $SIG{TSTP} = 'IGNORE';
938   local $SIG{PIPE} = 'IGNORE';
939
940   my $oldAutoCommit = $FS::UID::AutoCommit;
941   local $FS::UID::AutoCommit = 0;
942   my $dbh = dbh;
943
944   $self->select_for_update; #mutex
945
946   my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
947   my @credits  = grep { $_->credited > 0 } $self->cust_main->cust_credit;
948
949   if ( $conf->exists('pkg-balances') ) {
950     # limit @payments & @credits to those w/ a pkgnum grepped from $self
951     my %pkgnums = map { $_ => 1 } map $_->pkgnum, $self->cust_bill_pkg;
952     @payments = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @payments;
953     @credits  = grep { ! $_->pkgnum || $pkgnums{$_->pkgnum} } @credits;
954   }
955
956   while ( $self->owed > 0 and ( @payments || @credits ) ) {
957
958     my $app = '';
959     if ( @payments && @credits ) {
960
961       #decide which goes first by weight of top (unapplied) line item
962
963       my @open_lineitems = $self->open_cust_bill_pkg;
964
965       my $max_pay_weight =
966         max( map  { $_->part_pkg->pay_weight || 0 }
967              grep { $_ }
968              map  { $_->cust_pkg }
969                   @open_lineitems
970            );
971       my $max_credit_weight =
972         max( map  { $_->part_pkg->credit_weight || 0 }
973              grep { $_ } 
974              map  { $_->cust_pkg }
975                   @open_lineitems
976            );
977
978       #if both are the same... payments first?  it has to be something
979       if ( $max_pay_weight >= $max_credit_weight ) {
980         $app = 'pay';
981       } else {
982         $app = 'credit';
983       }
984     
985     } elsif ( @payments ) {
986       $app = 'pay';
987     } elsif ( @credits ) {
988       $app = 'credit';
989     } else {
990       die "guru meditation #12 and 35";
991     }
992
993     my $unapp_amount;
994     if ( $app eq 'pay' ) {
995
996       my $payment = shift @payments;
997       $unapp_amount = $payment->unapplied;
998       $app = new FS::cust_bill_pay { 'paynum'  => $payment->paynum };
999       $app->pkgnum( $payment->pkgnum )
1000         if $conf->exists('pkg-balances') && $payment->pkgnum;
1001
1002     } elsif ( $app eq 'credit' ) {
1003
1004       my $credit = shift @credits;
1005       $unapp_amount = $credit->credited;
1006       $app = new FS::cust_credit_bill { 'crednum' => $credit->crednum };
1007       $app->pkgnum( $credit->pkgnum )
1008         if $conf->exists('pkg-balances') && $credit->pkgnum;
1009
1010     } else {
1011       die "guru meditation #12 and 35";
1012     }
1013
1014     my $owed;
1015     if ( $conf->exists('pkg-balances') && $app->pkgnum ) {
1016       warn "owed_pkgnum ". $app->pkgnum;
1017       $owed = $self->owed_pkgnum($app->pkgnum);
1018     } else {
1019       $owed = $self->owed;
1020     }
1021     next unless $owed > 0;
1022
1023     warn "min ( $unapp_amount, $owed )\n" if $DEBUG;
1024     $app->amount( sprintf('%.2f', min( $unapp_amount, $owed ) ) );
1025
1026     $app->invnum( $self->invnum );
1027
1028     my $error = $app->insert(%options);
1029     if ( $error ) {
1030       $dbh->rollback if $oldAutoCommit;
1031       return "Error inserting ". $app->table. " record: $error";
1032     }
1033     die $error if $error;
1034
1035   }
1036
1037   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1038   ''; #no error
1039
1040 }
1041
1042 =item generate_email OPTION => VALUE ...
1043
1044 Options:
1045
1046 =over 4
1047
1048 =item from
1049
1050 sender address, required
1051
1052 =item template
1053
1054 alternate template name, optional
1055
1056 =item print_text
1057
1058 text attachment arrayref, optional
1059
1060 =item subject
1061
1062 email subject, optional
1063
1064 =item notice_name
1065
1066 notice name instead of "Invoice", optional
1067
1068 =back
1069
1070 Returns an argument list to be passed to L<FS::Misc::send_email>.
1071
1072 =cut
1073
1074 use MIME::Entity;
1075
1076 sub generate_email {
1077
1078   my $self = shift;
1079   my %args = @_;
1080   my $conf = $self->conf;
1081
1082   my $me = '[FS::cust_bill::generate_email]';
1083
1084   my %return = (
1085     'from'      => $args{'from'},
1086     'subject'   => ($args{'subject'} || $self->email_subject),
1087   );
1088
1089   $args{'unsquelch_cdr'} = $conf->exists('voip-cdr_email');
1090
1091   my $cust_main = $self->cust_main;
1092
1093   if (ref($args{'to'}) eq 'ARRAY') {
1094     $return{'to'} = $args{'to'};
1095   } else {
1096     $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
1097                            $cust_main->invoicing_list
1098                     ];
1099   }
1100
1101   if ( $conf->exists('invoice_html') ) {
1102
1103     warn "$me creating HTML/text multipart message"
1104       if $DEBUG;
1105
1106     $return{'nobody'} = 1;
1107
1108     my $alternative = build MIME::Entity
1109       'Type'        => 'multipart/alternative',
1110       #'Encoding'    => '7bit',
1111       'Disposition' => 'inline'
1112     ;
1113
1114     my $data;
1115     if ( $conf->exists('invoice_email_pdf')
1116          and scalar($conf->config('invoice_email_pdf_note')) ) {
1117
1118       warn "$me using 'invoice_email_pdf_note' in multipart message"
1119         if $DEBUG;
1120       $data = [ map { $_ . "\n" }
1121                     $conf->config('invoice_email_pdf_note')
1122               ];
1123
1124     } else {
1125
1126       warn "$me not using 'invoice_email_pdf_note' in multipart message"
1127         if $DEBUG;
1128       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1129         $data = $args{'print_text'};
1130       } else {
1131         $data = [ $self->print_text(\%args) ];
1132       }
1133
1134     }
1135
1136     $alternative->attach(
1137       'Type'        => 'text/plain',
1138       'Encoding'    => 'quoted-printable',
1139       #'Encoding'    => '7bit',
1140       'Data'        => $data,
1141       'Disposition' => 'inline',
1142     );
1143
1144
1145     my $htmldata;
1146     my $image = '';
1147     my $barcode = '';
1148     if ( $conf->exists('invoice_email_pdf')
1149          and scalar($conf->config('invoice_email_pdf_note')) ) {
1150
1151       $htmldata = join('<BR>', $conf->config('invoice_email_pdf_note') );
1152
1153     } else {
1154
1155       $args{'from'} =~ /\@([\w\.\-]+)/;
1156       my $from = $1 || 'example.com';
1157       my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1158
1159       my $logo;
1160       my $agentnum = $cust_main->agentnum;
1161       if ( defined($args{'template'}) && length($args{'template'})
1162            && $conf->exists( 'logo_'. $args{'template'}. '.png', $agentnum )
1163          )
1164       {
1165         $logo = 'logo_'. $args{'template'}. '.png';
1166       } else {
1167         $logo = "logo.png";
1168       }
1169       my $image_data = $conf->config_binary( $logo, $agentnum);
1170
1171       $image = build MIME::Entity
1172         'Type'       => 'image/png',
1173         'Encoding'   => 'base64',
1174         'Data'       => $image_data,
1175         'Filename'   => 'logo.png',
1176         'Content-ID' => "<$content_id>",
1177       ;
1178    
1179       if ($conf->exists('invoice-barcode')) {
1180         my $barcode_content_id = join('.', rand()*(2**32), $$, time). "\@$from";
1181         $barcode = build MIME::Entity
1182           'Type'       => 'image/png',
1183           'Encoding'   => 'base64',
1184           'Data'       => $self->invoice_barcode(0),
1185           'Filename'   => 'barcode.png',
1186           'Content-ID' => "<$barcode_content_id>",
1187         ;
1188         $args{'barcode_cid'} = $barcode_content_id;
1189       }
1190
1191       $htmldata = $self->print_html({ 'cid'=>$content_id, %args });
1192     }
1193
1194     $alternative->attach(
1195       'Type'        => 'text/html',
1196       'Encoding'    => 'quoted-printable',
1197       'Data'        => [ '<html>',
1198                          '  <head>',
1199                          '    <title>',
1200                          '      '. encode_entities($return{'subject'}), 
1201                          '    </title>',
1202                          '  </head>',
1203                          '  <body bgcolor="#e8e8e8">',
1204                          $htmldata,
1205                          '  </body>',
1206                          '</html>',
1207                        ],
1208       'Disposition' => 'inline',
1209       #'Filename'    => 'invoice.pdf',
1210     );
1211
1212
1213     my @otherparts = ();
1214     if ( $cust_main->email_csv_cdr ) {
1215
1216       push @otherparts, build MIME::Entity
1217         'Type'        => 'text/csv',
1218         'Encoding'    => '7bit',
1219         'Data'        => [ map { "$_\n" }
1220                              $self->call_details('prepend_billed_number' => 1)
1221                          ],
1222         'Disposition' => 'attachment',
1223         'Filename'    => 'usage-'. $self->invnum. '.csv',
1224       ;
1225
1226     }
1227
1228     if ( $conf->exists('invoice_email_pdf') ) {
1229
1230       #attaching pdf too:
1231       # multipart/mixed
1232       #   multipart/related
1233       #     multipart/alternative
1234       #       text/plain
1235       #       text/html
1236       #     image/png
1237       #   application/pdf
1238
1239       my $related = build MIME::Entity 'Type'     => 'multipart/related',
1240                                        'Encoding' => '7bit';
1241
1242       #false laziness w/Misc::send_email
1243       $related->head->replace('Content-type',
1244         $related->mime_type.
1245         '; boundary="'. $related->head->multipart_boundary. '"'.
1246         '; type=multipart/alternative'
1247       );
1248
1249       $related->add_part($alternative);
1250
1251       $related->add_part($image) if $image;
1252
1253       my $pdf = build MIME::Entity $self->mimebuild_pdf(\%args);
1254
1255       $return{'mimeparts'} = [ $related, $pdf, @otherparts ];
1256
1257     } else {
1258
1259       #no other attachment:
1260       # multipart/related
1261       #   multipart/alternative
1262       #     text/plain
1263       #     text/html
1264       #   image/png
1265
1266       $return{'content-type'} = 'multipart/related';
1267       if ($conf->exists('invoice-barcode') && $barcode) {
1268         $return{'mimeparts'} = [ $alternative, $image, $barcode, @otherparts ];
1269       } else {
1270         $return{'mimeparts'} = [ $alternative, $image, @otherparts ];
1271       }
1272       $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
1273       #$return{'disposition'} = 'inline';
1274
1275     }
1276   
1277   } else {
1278
1279     if ( $conf->exists('invoice_email_pdf') ) {
1280       warn "$me creating PDF attachment"
1281         if $DEBUG;
1282
1283       #mime parts arguments a la MIME::Entity->build().
1284       $return{'mimeparts'} = [
1285         { $self->mimebuild_pdf(\%args) }
1286       ];
1287     }
1288   
1289     if ( $conf->exists('invoice_email_pdf')
1290          and scalar($conf->config('invoice_email_pdf_note')) ) {
1291
1292       warn "$me using 'invoice_email_pdf_note'"
1293         if $DEBUG;
1294       $return{'body'} = [ map { $_ . "\n" }
1295                               $conf->config('invoice_email_pdf_note')
1296                         ];
1297
1298     } else {
1299
1300       warn "$me not using 'invoice_email_pdf_note'"
1301         if $DEBUG;
1302       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
1303         $return{'body'} = $args{'print_text'};
1304       } else {
1305         $return{'body'} = [ $self->print_text(\%args) ];
1306       }
1307
1308     }
1309
1310   }
1311
1312   %return;
1313
1314 }
1315
1316 =item mimebuild_pdf
1317
1318 Returns a list suitable for passing to MIME::Entity->build(), representing
1319 this invoice as PDF attachment.
1320
1321 =cut
1322
1323 sub mimebuild_pdf {
1324   my $self = shift;
1325   (
1326     'Type'        => 'application/pdf',
1327     'Encoding'    => 'base64',
1328     'Data'        => [ $self->print_pdf(@_) ],
1329     'Disposition' => 'attachment',
1330     'Filename'    => 'invoice-'. $self->invnum. '.pdf',
1331   );
1332 }
1333
1334 =item send HASHREF
1335
1336 Sends this invoice to the destinations configured for this customer: sends
1337 email, prints and/or faxes.  See L<FS::cust_main_invoice>.
1338
1339 Options can be passed as a hashref.  Positional parameters are no longer
1340 allowed.
1341
1342 I<template>: a suffix for alternate invoices
1343
1344 I<agentnum>: obsolete, now does nothing.
1345
1346 I<invoice_from> overrides the default email invoice From: address.
1347
1348 I<amount>: obsolete, does nothing
1349
1350 I<notice_name> overrides "Invoice" as the name of the sent document 
1351 (templates from 10/2009 or newer required).
1352
1353 I<lpr> overrides the system 'lpr' option as the command to print a document
1354 from standard input.
1355
1356 =cut
1357
1358 sub send {
1359   my $self = shift;
1360   my $opt = ref($_[0]) ? $_[0] : +{ @_ };
1361   my $conf = $self->conf;
1362
1363   my $cust_main = $self->cust_main;
1364
1365   my @invoicing_list = $cust_main->invoicing_list;
1366
1367   $self->email($opt)
1368     if ( grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list )
1369     && ! $self->invoice_noemail;
1370
1371   $self->print($opt)
1372     if grep { $_ eq 'POST' } @invoicing_list; #postal
1373
1374   #this has never been used post-$ORIGINAL_ISP afaik
1375   $self->fax_invoice($opt)
1376     if grep { $_ eq 'FAX' } @invoicing_list; #fax
1377
1378   '';
1379
1380 }
1381
1382 =item email HASHREF | [ TEMPLATE [ , INVOICE_FROM ] ] 
1383
1384 Sends this invoice to the customer's email destination(s).
1385
1386 Options must be passed as a hashref.  Positional parameters are no longer
1387 allowed.
1388
1389 I<template>, if specified, is the name of a suffix for alternate invoices.
1390
1391 I<invoice_from>, if specified, overrides the default email invoice From: 
1392 address.
1393
1394 I<notice_name> is the name of the sent document.
1395
1396 =cut
1397
1398 sub queueable_email {
1399   my %opt = @_;
1400
1401   my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
1402     or die "invalid invoice number: " . $opt{invnum};
1403
1404   my %args = map {$_ => $opt{$_}} 
1405              grep { $opt{$_} }
1406               qw( invoice_from notice_name no_coupon template );
1407
1408   my $error = $self->email( \%args );
1409   die $error if $error;
1410
1411 }
1412
1413 sub email {
1414   my $self = shift;
1415   return if $self->hide;
1416   my $conf = $self->conf;
1417   my $opt = shift || {};
1418   if ($opt and !ref($opt)) {
1419     die "FS::cust_bill::email called with positional parameters";
1420   }
1421
1422   my $template = $opt->{template};
1423   my $from = delete $opt->{invoice_from};
1424
1425   # this is where we set the From: address
1426   $from ||= $self->_agent_invoice_from ||    #XXX should go away
1427             $conf->config('invoice_from', $self->cust_main->agentnum );
1428
1429   my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } 
1430                             $self->cust_main->invoicing_list;
1431
1432   if ( ! @invoicing_list ) { #no recipients
1433     if ( $conf->exists('cust_bill-no_recipients-error') ) {
1434       die 'No recipients for customer #'. $self->custnum;
1435     } else {
1436       #default: better to notify this person than silence
1437       @invoicing_list = ($from);
1438     }
1439   }
1440
1441   # this is where we set the Subject:
1442   my $subject = $self->email_subject($template);
1443
1444   my $error = send_email(
1445     $self->generate_email(
1446       'from'        => $from,
1447       'to'          => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
1448       'subject'     => $subject,
1449       %$opt, # template, etc.
1450     )
1451   );
1452   die "can't email invoice: $error\n" if $error;
1453   #die "$error\n" if $error;
1454
1455 }
1456
1457 sub email_subject {
1458   my $self = shift;
1459   my $conf = $self->conf;
1460
1461   #my $template = scalar(@_) ? shift : '';
1462   #per-template?
1463
1464   my $subject = $conf->config('invoice_subject', $self->cust_main->agentnum)
1465                 || 'Invoice';
1466
1467   my $cust_main = $self->cust_main;
1468   my $name = $cust_main->name;
1469   my $name_short = $cust_main->name_short;
1470   my $invoice_number = $self->invnum;
1471   my $invoice_date = $self->_date_pretty;
1472
1473   eval qq("$subject");
1474 }
1475
1476 =item lpr_data HASHREF
1477
1478 Returns the postscript or plaintext for this invoice as an arrayref.
1479
1480 Options must be passed as a hashref.  Positional parameters are no longer 
1481 allowed.
1482
1483 I<template>, if specified, is the name of a suffix for alternate invoices.
1484
1485 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1486
1487 =cut
1488
1489 sub lpr_data {
1490   my $self = shift;
1491   my $conf = $self->conf;
1492   my $opt = shift || {};
1493   if ($opt and !ref($opt)) {
1494     # nobody does this anyway
1495     die "FS::cust_bill::lpr_data called with positional parameters";
1496   }
1497
1498   my $method = $conf->exists('invoice_latex') ? 'print_ps' : 'print_text';
1499   [ $self->$method( $opt ) ];
1500 }
1501
1502 =item print HASHREF
1503
1504 Prints this invoice.
1505
1506 Options must be passed as a hashref.
1507
1508 I<template>, if specified, is the name of a suffix for alternate invoices.
1509
1510 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1511
1512 =cut
1513
1514 sub print {
1515   my $self = shift;
1516   return if $self->hide;
1517   my $conf = $self->conf;
1518   my $opt = shift || {};
1519   if ($opt and !ref($opt)) {
1520     die "FS::cust_bill::print called with positional parameters";
1521   }
1522
1523   my $lpr = delete $opt->{lpr};
1524   if($conf->exists('invoice_print_pdf')) {
1525     # Add the invoice to the current batch.
1526     $self->batch_invoice($opt);
1527   }
1528   else {
1529     do_print(
1530       $self->lpr_data($opt),
1531       'agentnum' => $self->cust_main->agentnum,
1532       'lpr'      => $lpr,
1533     );
1534   }
1535 }
1536
1537 =item fax_invoice HASHREF
1538
1539 Faxes this invoice.
1540
1541 Options must be passed as a hashref.
1542
1543 I<template>, if specified, is the name of a suffix for alternate invoices.
1544
1545 I<notice_name>, if specified, overrides "Invoice" as the name of the sent document (templates from 10/2009 or newer required)
1546
1547 =cut
1548
1549 sub fax_invoice {
1550   my $self = shift;
1551   return if $self->hide;
1552   my $conf = $self->conf;
1553   my $opt = shift || {};
1554   if ($opt and !ref($opt)) {
1555     die "FS::cust_bill::fax_invoice called with positional parameters";
1556   }
1557
1558   die 'FAX invoice destination not (yet?) supported with plain text invoices.'
1559     unless $conf->exists('invoice_latex');
1560
1561   my $dialstring = $self->cust_main->getfield('fax');
1562   #Check $dialstring?
1563
1564   my $error = send_fax( 'docdata'    => $self->lpr_data($opt),
1565                         'dialstring' => $dialstring,
1566                       );
1567   die $error if $error;
1568
1569 }
1570
1571 =item batch_invoice [ HASHREF ]
1572
1573 Place this invoice into the open batch (see C<FS::bill_batch>).  If there 
1574 isn't an open batch, one will be created.
1575
1576 =cut
1577
1578 sub batch_invoice {
1579   my ($self, $opt) = @_;
1580   my $bill_batch = $self->get_open_bill_batch;
1581   my $cust_bill_batch = FS::cust_bill_batch->new({
1582       batchnum => $bill_batch->batchnum,
1583       invnum   => $self->invnum,
1584   });
1585   return $cust_bill_batch->insert($opt);
1586 }
1587
1588 =item get_open_batch
1589
1590 Returns the currently open batch as an FS::bill_batch object, creating a new
1591 one if necessary.  (A per-agent batch if invoice_print_pdf-spoolagent is
1592 enabled)
1593
1594 =cut
1595
1596 sub get_open_bill_batch {
1597   my $self = shift;
1598   my $conf = $self->conf;
1599   my $hashref = { status => 'O' };
1600   $hashref->{'agentnum'} = $conf->exists('invoice_print_pdf-spoolagent')
1601                              ? $self->cust_main->agentnum
1602                              : '';
1603   my $batch = qsearchs('bill_batch', $hashref);
1604   return $batch if $batch;
1605   $batch = FS::bill_batch->new($hashref);
1606   my $error = $batch->insert;
1607   die $error if $error;
1608   return $batch;
1609 }
1610
1611 =item ftp_invoice [ TEMPLATENAME ] 
1612
1613 Sends this invoice data via FTP.
1614
1615 TEMPLATENAME is unused?
1616
1617 =cut
1618
1619 sub ftp_invoice {
1620   my $self = shift;
1621   my $conf = $self->conf;
1622   my $template = scalar(@_) ? shift : '';
1623
1624   $self->send_csv(
1625     'protocol'   => 'ftp',
1626     'server'     => $conf->config('cust_bill-ftpserver'),
1627     'username'   => $conf->config('cust_bill-ftpusername'),
1628     'password'   => $conf->config('cust_bill-ftppassword'),
1629     'dir'        => $conf->config('cust_bill-ftpdir'),
1630     'format'     => $conf->config('cust_bill-ftpformat'),
1631   );
1632 }
1633
1634 =item spool_invoice [ TEMPLATENAME ] 
1635
1636 Spools this invoice data (see L<FS::spool_csv>)
1637
1638 TEMPLATENAME is unused?
1639
1640 =cut
1641
1642 sub spool_invoice {
1643   my $self = shift;
1644   my $conf = $self->conf;
1645   my $template = scalar(@_) ? shift : '';
1646
1647   $self->spool_csv(
1648     'format'       => $conf->config('cust_bill-spoolformat'),
1649     'agent_spools' => $conf->exists('cust_bill-spoolagent'),
1650   );
1651 }
1652
1653 =item send_csv OPTION => VALUE, ...
1654
1655 Sends invoice as a CSV data-file to a remote host with the specified protocol.
1656
1657 Options are:
1658
1659 protocol - currently only "ftp"
1660 server
1661 username
1662 password
1663 dir
1664
1665 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
1666 and YYMMDDHHMMSS is a timestamp.
1667
1668 See L</print_csv> for a description of the output format.
1669
1670 =cut
1671
1672 sub send_csv {
1673   my($self, %opt) = @_;
1674
1675   #create file(s)
1676
1677   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1678   mkdir $spooldir, 0700 unless -d $spooldir;
1679
1680   # don't localize dates here, they're a defined format
1681   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1682   my $file = "$spooldir/$tracctnum.csv";
1683   
1684   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1685
1686   open(CSV, ">$file") or die "can't open $file: $!";
1687   print CSV $header;
1688
1689   print CSV $detail;
1690
1691   close CSV;
1692
1693   my $net;
1694   if ( $opt{protocol} eq 'ftp' ) {
1695     eval "use Net::FTP;";
1696     die $@ if $@;
1697     $net = Net::FTP->new($opt{server}) or die @$;
1698   } else {
1699     die "unknown protocol: $opt{protocol}";
1700   }
1701
1702   $net->login( $opt{username}, $opt{password} )
1703     or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
1704
1705   $net->binary or die "can't set binary mode";
1706
1707   $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
1708
1709   $net->put($file) or die "can't put $file: $!";
1710
1711   $net->quit;
1712
1713   unlink $file;
1714
1715 }
1716
1717 =item spool_csv
1718
1719 Spools CSV invoice data.
1720
1721 Options are:
1722
1723 =over 4
1724
1725 =item format - any of FS::Misc::::Invoicing::spool_formats
1726
1727 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the
1728 customer has the corresponding invoice destinations set (see
1729 L<FS::cust_main_invoice>).
1730
1731 =item agent_spools - if set to a true value, will spool to per-agent files
1732 rather than a single global file
1733
1734 =item upload_targetnum - if set to a target (see L<FS::upload_target>), will
1735 append to that spool.  L<FS::Cron::upload> will then send the spool file to
1736 that destination.
1737
1738 =item balanceover - if set, only spools the invoice if the total amount owed on
1739 this invoice and all older invoices is greater than the specified amount.
1740
1741 =item time - the "current time".  Controls the printing of past due messages
1742 in the ICS format.
1743
1744 =back
1745
1746 =cut
1747
1748 sub spool_csv {
1749   my($self, %opt) = @_;
1750
1751   my $time = $opt{'time'} || time;
1752   my $cust_main = $self->cust_main;
1753
1754   if ( $opt{'dest'} ) {
1755     my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1756                              $cust_main->invoicing_list;
1757     return 'N/A' unless $invoicing_list{$opt{'dest'}}
1758                      || ! keys %invoicing_list;
1759   }
1760
1761   if ( $opt{'balanceover'} ) {
1762     return 'N/A'
1763       if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1764   }
1765
1766   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1767   mkdir $spooldir, 0700 unless -d $spooldir;
1768
1769   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', $time);
1770
1771   my $file;
1772   if ( $opt{'agent_spools'} ) {
1773     $file = 'agentnum'.$cust_main->agentnum;
1774   } else {
1775     $file = 'spool';
1776   }
1777
1778   if ( $opt{'upload_targetnum'} ) {
1779     $spooldir .= '/target'.$opt{'upload_targetnum'};
1780     mkdir $spooldir, 0700 unless -d $spooldir;
1781   } # otherwise it just goes into export.xxx/cust_bill
1782
1783   if ( lc($opt{'format'}) eq 'billco' ) {
1784     $file .= '-header';
1785   }
1786
1787   $file = "$spooldir/$file.csv";
1788   
1789   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum);
1790
1791   open(CSV, ">>$file") or die "can't open $file: $!";
1792   flock(CSV, LOCK_EX);
1793   seek(CSV, 0, 2);
1794
1795   print CSV $header;
1796
1797   if ( lc($opt{'format'}) eq 'billco' ) {
1798
1799     flock(CSV, LOCK_UN);
1800     close CSV;
1801
1802     $file =~ s/-header.csv$/-detail.csv/;
1803
1804     open(CSV,">>$file") or die "can't open $file: $!";
1805     flock(CSV, LOCK_EX);
1806     seek(CSV, 0, 2);
1807   }
1808
1809   print CSV $detail if defined($detail);
1810
1811   flock(CSV, LOCK_UN);
1812   close CSV;
1813
1814   return '';
1815
1816 }
1817
1818 =item print_csv OPTION => VALUE, ...
1819
1820 Returns CSV data for this invoice.
1821
1822 Options are:
1823
1824 format - 'default', 'billco', 'oneline', 'bridgestone'
1825
1826 Returns a list consisting of two scalars.  The first is a single line of CSV
1827 header information for this invoice.  The second is one or more lines of CSV
1828 detail information for this invoice.
1829
1830 If I<format> is not specified or "default", the fields of the CSV file are as
1831 follows:
1832
1833 record_type, invnum, custnum, _date, charged, first, last, company, address1, 
1834 address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1835
1836 =over 4
1837
1838 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1839
1840 B<record_type> is C<cust_bill> for the initial header line only.  The
1841 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1842 fields are filled in.
1843
1844 B<record_type> is C<cust_bill_pkg> for detail lines.  Only the first two fields
1845 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1846 are filled in.
1847
1848 =item invnum - invoice number
1849
1850 =item custnum - customer number
1851
1852 =item _date - invoice date
1853
1854 =item charged - total invoice amount
1855
1856 =item first - customer first name
1857
1858 =item last - customer first name
1859
1860 =item company - company name
1861
1862 =item address1 - address line 1
1863
1864 =item address2 - address line 1
1865
1866 =item city
1867
1868 =item state
1869
1870 =item zip
1871
1872 =item country
1873
1874 =item pkg - line item description
1875
1876 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1877
1878 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1879
1880 =item sdate - start date for recurring fee
1881
1882 =item edate - end date for recurring fee
1883
1884 =back
1885
1886 If I<format> is "billco", the fields of the header CSV file are as follows:
1887
1888   +-------------------------------------------------------------------+
1889   |                        FORMAT HEADER FILE                         |
1890   |-------------------------------------------------------------------|
1891   | Field | Description                   | Name       | Type | Width |
1892   | 1     | N/A-Leave Empty               | RC         | CHAR |     2 |
1893   | 2     | N/A-Leave Empty               | CUSTID     | CHAR |    15 |
1894   | 3     | Transaction Account No        | TRACCTNUM  | CHAR |    15 |
1895   | 4     | Transaction Invoice No        | TRINVOICE  | CHAR |    15 |
1896   | 5     | Transaction Zip Code          | TRZIP      | CHAR |     5 |
1897   | 6     | Transaction Company Bill To   | TRCOMPANY  | CHAR |    30 |
1898   | 7     | Transaction Contact Bill To   | TRNAME     | CHAR |    30 |
1899   | 8     | Additional Address Unit Info  | TRADDR1    | CHAR |    30 |
1900   | 9     | Bill To Street Address        | TRADDR2    | CHAR |    30 |
1901   | 10    | Ancillary Billing Information | TRADDR3    | CHAR |    30 |
1902   | 11    | Transaction City Bill To      | TRCITY     | CHAR |    20 |
1903   | 12    | Transaction State Bill To     | TRSTATE    | CHAR |     2 |
1904   | 13    | Bill Cycle Close Date         | CLOSEDATE  | CHAR |    10 |
1905   | 14    | Bill Due Date                 | DUEDATE    | CHAR |    10 |
1906   | 15    | Previous Balance              | BALFWD     | NUM* |     9 |
1907   | 16    | Pmt/CR Applied                | CREDAPPLY  | NUM* |     9 |
1908   | 17    | Total Current Charges         | CURRENTCHG | NUM* |     9 |
1909   | 18    | Total Amt Due                 | TOTALDUE   | NUM* |     9 |
1910   | 19    | Total Amt Due                 | AMTDUE     | NUM* |     9 |
1911   | 20    | 30 Day Aging                  | AMT30      | NUM* |     9 |
1912   | 21    | 60 Day Aging                  | AMT60      | NUM* |     9 |
1913   | 22    | 90 Day Aging                  | AMT90      | NUM* |     9 |
1914   | 23    | Y/N                           | AGESWITCH  | CHAR |     1 |
1915   | 24    | Remittance automation         | SCANLINE   | CHAR |   100 |
1916   | 25    | Total Taxes & Fees            | TAXTOT     | NUM* |     9 |
1917   | 26    | Customer Reference Number     | CUSTREF    | CHAR |    15 |
1918   | 27    | Federal Tax***                | FEDTAX     | NUM* |     9 |
1919   | 28    | State Tax***                  | STATETAX   | NUM* |     9 |
1920   | 29    | Other Taxes & Fees***         | OTHERTAX   | NUM* |     9 |
1921   +-------+-------------------------------+------------+------+-------+
1922
1923 If I<format> is "billco", the fields of the detail CSV file are as follows:
1924
1925                                   FORMAT FOR DETAIL FILE
1926         |                            |           |      |
1927   Field | Description                | Name      | Type | Width
1928   1     | N/A-Leave Empty            | RC        | CHAR |     2
1929   2     | N/A-Leave Empty            | CUSTID    | CHAR |    15
1930   3     | Account Number             | TRACCTNUM | CHAR |    15
1931   4     | Invoice Number             | TRINVOICE | CHAR |    15
1932   5     | Line Sequence (sort order) | LINESEQ   | NUM  |     6
1933   6     | Transaction Detail         | DETAILS   | CHAR |   100
1934   7     | Amount                     | AMT       | NUM* |     9
1935   8     | Line Format Control**      | LNCTRL    | CHAR |     2
1936   9     | Grouping Code              | GROUP     | CHAR |     2
1937   10    | User Defined               | ACCT CODE | CHAR |    15
1938
1939 If format is 'oneline', there is no detail file.  Each invoice has a 
1940 header line only, with the fields:
1941
1942 Agent number, agent name, customer number, first name, last name, address
1943 line 1, address line 2, city, state, zip, invoice date, invoice number,
1944 amount charged, amount due, previous balance, due date.
1945
1946 and then, for each line item, three columns containing the package number,
1947 description, and amount.
1948
1949 If format is 'bridgestone', there is no detail file.  Each invoice has a 
1950 header line with the following fields in a fixed-width format:
1951
1952 Customer number (in display format), date, name (first last), company,
1953 address 1, address 2, city, state, zip.
1954
1955 This is a mailing list format, and has no per-invoice fields.  To avoid
1956 sending redundant notices, the spooling event should have a "once" or 
1957 "once_percust_every" condition.
1958
1959 =cut
1960
1961 sub print_csv {
1962   my($self, %opt) = @_;
1963   
1964   eval "use Text::CSV_XS";
1965   die $@ if $@;
1966
1967   my $cust_main = $self->cust_main;
1968
1969   my $csv = Text::CSV_XS->new({'always_quote'=>1});
1970   my $format = lc($opt{'format'});
1971
1972   my $time = $opt{'time'} || time;
1973
1974   my $tracctnum = ''; #leaking out from billco-specific sections :/
1975   if ( $format eq 'billco' ) {
1976
1977     my $account_num =
1978       $self->conf->config('billco-account_num', $cust_main->agentnum);
1979
1980     $tracctnum = $account_num eq 'display_custnum'
1981                    ? $cust_main->display_custnum
1982                    : $opt{'tracctnum'};
1983
1984     my $taxtotal = 0;
1985     $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1986
1987     my $duedate = $self->due_date2str('%m/%d/%Y'); #date_format?
1988
1989     my( $previous_balance, @unused ) = $self->previous; #previous balance
1990
1991     my $pmt_cr_applied = 0;
1992     $pmt_cr_applied += $_->{'amount'}
1993       foreach ( $self->_items_payments(%opt), $self->_items_credits(%opt) ) ;
1994
1995     my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1996
1997     $csv->combine(
1998       '',                         #  1 | N/A-Leave Empty               CHAR   2
1999       '',                         #  2 | N/A-Leave Empty               CHAR  15
2000       $tracctnum,                 #  3 | Transaction Account No        CHAR  15
2001       $self->invnum,              #  4 | Transaction Invoice No        CHAR  15
2002       $cust_main->zip,            #  5 | Transaction Zip Code          CHAR   5
2003       $cust_main->company,        #  6 | Transaction Company Bill To   CHAR  30
2004       #$cust_main->payname,        #  7 | Transaction Contact Bill To   CHAR  30
2005       $cust_main->contact,        #  7 | Transaction Contact Bill To   CHAR  30
2006       $cust_main->address2,       #  8 | Additional Address Unit Info  CHAR  30
2007       $cust_main->address1,       #  9 | Bill To Street Address        CHAR  30
2008       '',                         # 10 | Ancillary Billing Information CHAR  30
2009       $cust_main->city,           # 11 | Transaction City Bill To      CHAR  20
2010       $cust_main->state,          # 12 | Transaction State Bill To     CHAR   2
2011
2012       # XXX ?
2013       time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR  10
2014
2015       # XXX ?
2016       $duedate,                   # 14 | Bill Due Date                 CHAR  10
2017
2018       $previous_balance,          # 15 | Previous Balance              NUM*   9
2019       $pmt_cr_applied,            # 16 | Pmt/CR Applied                NUM*   9
2020       sprintf("%.2f", $self->charged), # 17 | Total Current Charges    NUM*   9
2021       $totaldue,                  # 18 | Total Amt Due                 NUM*   9
2022       $totaldue,                  # 19 | Total Amt Due                 NUM*   9
2023       '',                         # 20 | 30 Day Aging                  NUM*   9
2024       '',                         # 21 | 60 Day Aging                  NUM*   9
2025       '',                         # 22 | 90 Day Aging                  NUM*   9
2026       'N',                        # 23 | Y/N                           CHAR   1
2027       '',                         # 24 | Remittance automation         CHAR 100
2028       $taxtotal,                  # 25 | Total Taxes & Fees            NUM*   9
2029       $self->custnum,             # 26 | Customer Reference Number     CHAR  15
2030       '0',                        # 27 | Federal Tax***                NUM*   9
2031       sprintf("%.2f", $taxtotal), # 28 | State Tax***                  NUM*   9
2032       '0',                        # 29 | Other Taxes & Fees***         NUM*   9
2033     );
2034
2035   } elsif ( $format eq 'oneline' ) { #name
2036   
2037     my ($previous_balance) = $self->previous; 
2038     $previous_balance = sprintf('%.2f', $previous_balance);
2039     my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
2040     my @items = map {
2041                       $_->{pkgnum},
2042                       $_->{description},
2043                       $_->{amount}
2044                     }
2045                   $self->_items_pkg, #_items_nontax?  no sections or anything
2046                                      # with this format
2047                   $self->_items_tax;
2048
2049     $csv->combine(
2050       $cust_main->agentnum,
2051       $cust_main->agent->agent,
2052       $self->custnum,
2053       $cust_main->first,
2054       $cust_main->last,
2055       $cust_main->company,
2056       $cust_main->address1,
2057       $cust_main->address2,
2058       $cust_main->city,
2059       $cust_main->state,
2060       $cust_main->zip,
2061
2062       # invoice fields
2063       time2str("%x", $self->_date),
2064       $self->invnum,
2065       $self->charged,
2066       $totaldue,
2067       $previous_balance,
2068       $self->due_date2str("%x"),
2069
2070       @items,
2071     );
2072
2073   } elsif ( $format eq 'bridgestone' ) {
2074
2075     # bypass the CSV stuff and just return this
2076     my $longdate = time2str('%B %d, %Y', $time); #current time, right?
2077     my $zip = $cust_main->zip;
2078     $zip =~ s/\D//;
2079     my $prefix = $self->conf->config('bridgestone-prefix', $cust_main->agentnum)
2080       || '';
2081     return (
2082       sprintf(
2083         "%-5s%-15s%-20s%-30s%-30s%-30s%-30s%-20s%-2s%-9s\n",
2084         $prefix,
2085         $cust_main->display_custnum,
2086         $longdate,
2087         uc(substr($cust_main->contact_firstlast,0,30)),
2088         uc(substr($cust_main->company          ,0,30)),
2089         uc(substr($cust_main->address1         ,0,30)),
2090         uc(substr($cust_main->address2         ,0,30)),
2091         uc(substr($cust_main->city             ,0,20)),
2092         uc($cust_main->state),
2093         $zip
2094       ),
2095       '' #detail
2096       );
2097
2098   } elsif ( $format eq 'ics' ) {
2099
2100     my $bill = $cust_main->bill_location;
2101     my $zip = $bill->zip;
2102     my $zip4 = '';
2103
2104     $zip =~ s/\D//;
2105     if ( $zip =~ /^(\d{5})(\d{4})$/ ) {
2106       $zip = $1;
2107       $zip4 = $2;
2108     }
2109
2110     # minor false laziness with print_generic
2111     my ($previous_balance) = $self->previous;
2112     my $balance_due = $self->owed + $previous_balance;
2113     my $payment_total = sum(0, map { $_->{'amount'} } $self->_items_payments);
2114     my $credit_total  = sum(0, map { $_->{'amount'} } $self->_items_credits);
2115
2116     my $past_due = '';
2117     if ( $self->due_date and $time >= $self->due_date ) {
2118       $past_due = sprintf('Past due:$%0.2f Due Immediately', $balance_due);
2119     }
2120
2121     # again, bypass CSV
2122     my $header = sprintf(
2123       '%-10s%-30s%-48s%-2s%-50s%-30s%-30s%-25s%-2s%-5s%-4s%-8s%-8s%-10s%-10s%-10s%-10s%-10s%-10s%-480s%-35s',
2124       $cust_main->display_custnum, #BID
2125       uc($cust_main->first), #FNAME
2126       uc($cust_main->last), #LNAME
2127       '00', #BATCH, should this ever be anything else?
2128       uc($cust_main->company), #COMP
2129       uc($bill->address1), #STREET1
2130       uc($bill->address2), #STREET2
2131       uc($bill->city), #CITY
2132       uc($bill->state), #STATE
2133       $zip,
2134       $zip4,
2135       time2str('%Y%m%d', $self->_date), #BILL_DATE
2136       $self->due_date2str('%Y%m%d'), #DUE_DATE,
2137       ( map {sprintf('%0.2f', $_)}
2138         $balance_due, #AMNT_DUE
2139         $previous_balance, #PREV_BAL
2140         $payment_total, #PYMT_RCVD
2141         $credit_total, #CREDITS
2142         $previous_balance, #BEG_BAL--is this correct?
2143         $self->charged, #NEW_CHRG
2144       ),
2145       'img01', #MRKT_MSG?
2146       $past_due, #PAST_MSG
2147     );
2148
2149     my @details;
2150     my %svc_class = ('' => ''); # maybe cache this more persistently?
2151
2152     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2153
2154       my $show_pkgnum = $cust_bill_pkg->pkgnum || '';
2155       my $cust_pkg = $cust_bill_pkg->cust_pkg if $show_pkgnum;
2156
2157       if ( $cust_pkg ) {
2158
2159         my @dates = ( $self->_date, undef );
2160         if ( my $prev = $cust_bill_pkg->previous_cust_bill_pkg ) {
2161           $dates[1] = $prev->sdate; #questionable
2162         }
2163
2164         # generate an 01 detail for each service
2165         my @svcs = $cust_pkg->h_cust_svc(@dates, 'I');
2166         foreach my $cust_svc ( @svcs ) {
2167           $show_pkgnum = ''; # hide it if we're showing svcnums
2168
2169           my $svcpart = $cust_svc->svcpart;
2170           if (!exists($svc_class{$svcpart})) {
2171             my $classnum = $cust_svc->part_svc->classnum;
2172             my $part_svc_class = FS::part_svc_class->by_key($classnum)
2173               if $classnum;
2174             $svc_class{$svcpart} = $part_svc_class ? 
2175                                    $part_svc_class->classname :
2176                                    '';
2177           }
2178
2179           my @h_label = $cust_svc->label(@dates, 'I');
2180           push @details, sprintf('01%-9s%-20s%-47s',
2181             $cust_svc->svcnum,
2182             $svc_class{$svcpart},
2183             $h_label[1],
2184           );
2185         } #foreach $cust_svc
2186       } #if $cust_pkg
2187
2188       my $desc = $cust_bill_pkg->desc; # itemdesc or part_pkg.pkg
2189       if ($cust_bill_pkg->recur > 0) {
2190         $desc .= ' '.time2str('%d-%b-%Y', $cust_bill_pkg->sdate).' to '.
2191                      time2str('%d-%b-%Y', $cust_bill_pkg->edate - 86400);
2192       }
2193       push @details, sprintf('02%-6s%-60s%-10s',
2194         $show_pkgnum,
2195         $desc,
2196         sprintf('%0.2f', $cust_bill_pkg->setup + $cust_bill_pkg->recur),
2197       );
2198     } #foreach $cust_bill_pkg
2199
2200     # Tag this row so that we know whether this is one page (1), two pages
2201     # (2), # or "big" (B).  The tag will be stripped off before uploading.
2202     if ( scalar(@details) < 12 ) {
2203       push @details, '1';
2204     } elsif ( scalar(@details) < 58 ) {
2205       push @details, '2';
2206     } else {
2207       push @details, 'B';
2208     }
2209
2210     return join('', $header, @details, "\n");
2211
2212   } else { # default
2213   
2214     $csv->combine(
2215       'cust_bill',
2216       $self->invnum,
2217       $self->custnum,
2218       time2str("%x", $self->_date),
2219       sprintf("%.2f", $self->charged),
2220       ( map { $cust_main->getfield($_) }
2221           qw( first last company address1 address2 city state zip country ) ),
2222       map { '' } (1..5),
2223     ) or die "can't create csv";
2224   }
2225
2226   my $header = $csv->string. "\n";
2227
2228   my $detail = '';
2229   if ( lc($opt{'format'}) eq 'billco' ) {
2230
2231     my $lineseq = 0;
2232     foreach my $item ( $self->_items_pkg ) {
2233
2234       $csv->combine(
2235         '',                     #  1 | N/A-Leave Empty            CHAR   2
2236         '',                     #  2 | N/A-Leave Empty            CHAR  15
2237         $tracctnum,             #  3 | Account Number             CHAR  15
2238         $self->invnum,          #  4 | Invoice Number             CHAR  15
2239         $lineseq++,             #  5 | Line Sequence (sort order) NUM    6
2240         $item->{'description'}, #  6 | Transaction Detail         CHAR 100
2241         $item->{'amount'},      #  7 | Amount                     NUM*   9
2242         '',                     #  8 | Line Format Control**      CHAR   2
2243         '',                     #  9 | Grouping Code              CHAR   2
2244         '',                     # 10 | User Defined               CHAR  15
2245       );
2246
2247       $detail .= $csv->string. "\n";
2248
2249     }
2250
2251   } elsif ( lc($opt{'format'}) eq 'oneline' ) {
2252
2253     #do nothing
2254
2255   } else {
2256
2257     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2258
2259       my($pkg, $setup, $recur, $sdate, $edate);
2260       if ( $cust_bill_pkg->pkgnum ) {
2261       
2262         ($pkg, $setup, $recur, $sdate, $edate) = (
2263           $cust_bill_pkg->part_pkg->pkg,
2264           ( $cust_bill_pkg->setup != 0
2265             ? sprintf("%.2f", $cust_bill_pkg->setup )
2266             : '' ),
2267           ( $cust_bill_pkg->recur != 0
2268             ? sprintf("%.2f", $cust_bill_pkg->recur )
2269             : '' ),
2270           ( $cust_bill_pkg->sdate 
2271             ? time2str("%x", $cust_bill_pkg->sdate)
2272             : '' ),
2273           ($cust_bill_pkg->edate 
2274             ? time2str("%x", $cust_bill_pkg->edate)
2275             : '' ),
2276         );
2277   
2278       } else { #pkgnum tax
2279         next unless $cust_bill_pkg->setup != 0;
2280         $pkg = $cust_bill_pkg->desc;
2281         $setup = sprintf('%10.2f', $cust_bill_pkg->setup );
2282         ( $sdate, $edate ) = ( '', '' );
2283       }
2284   
2285       $csv->combine(
2286         'cust_bill_pkg',
2287         $self->invnum,
2288         ( map { '' } (1..11) ),
2289         ($pkg, $setup, $recur, $sdate, $edate)
2290       ) or die "can't create csv";
2291
2292       $detail .= $csv->string. "\n";
2293
2294     }
2295
2296   }
2297
2298   ( $header, $detail );
2299
2300 }
2301
2302 =item comp
2303
2304 Pays this invoice with a compliemntary payment.  If there is an error,
2305 returns the error, otherwise returns false.
2306
2307 =cut
2308
2309 sub comp {
2310   my $self = shift;
2311   my $cust_pay = new FS::cust_pay ( {
2312     'invnum'   => $self->invnum,
2313     'paid'     => $self->owed,
2314     '_date'    => '',
2315     'payby'    => 'COMP',
2316     'payinfo'  => $self->cust_main->payinfo,
2317     'paybatch' => '',
2318   } );
2319   $cust_pay->insert;
2320 }
2321
2322 =item realtime_card
2323
2324 Attempts to pay this invoice with a credit card payment via a
2325 Business::OnlinePayment realtime gateway.  See
2326 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2327 for supported processors.
2328
2329 =cut
2330
2331 sub realtime_card {
2332   my $self = shift;
2333   $self->realtime_bop( 'CC', @_ );
2334 }
2335
2336 =item realtime_ach
2337
2338 Attempts to pay this invoice with an electronic check (ACH) payment via a
2339 Business::OnlinePayment realtime gateway.  See
2340 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2341 for supported processors.
2342
2343 =cut
2344
2345 sub realtime_ach {
2346   my $self = shift;
2347   $self->realtime_bop( 'ECHECK', @_ );
2348 }
2349
2350 =item realtime_lec
2351
2352 Attempts to pay this invoice with phone bill (LEC) payment via a
2353 Business::OnlinePayment realtime gateway.  See
2354 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
2355 for supported processors.
2356
2357 =cut
2358
2359 sub realtime_lec {
2360   my $self = shift;
2361   $self->realtime_bop( 'LEC', @_ );
2362 }
2363
2364 sub realtime_bop {
2365   my( $self, $method ) = (shift,shift);
2366   my $conf = $self->conf;
2367   my %opt = @_;
2368
2369   my $cust_main = $self->cust_main;
2370   my $balance = $cust_main->balance;
2371   my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
2372   $amount = sprintf("%.2f", $amount);
2373   return "not run (balance $balance)" unless $amount > 0;
2374
2375   my $description = 'Internet Services';
2376   if ( $conf->exists('business-onlinepayment-description') ) {
2377     my $dtempl = $conf->config('business-onlinepayment-description');
2378
2379     my $agent_obj = $cust_main->agent
2380       or die "can't retreive agent for $cust_main (agentnum ".
2381              $cust_main->agentnum. ")";
2382     my $agent = $agent_obj->agent;
2383     my $pkgs = join(', ',
2384       map { $_->part_pkg->pkg }
2385         grep { $_->pkgnum } $self->cust_bill_pkg
2386     );
2387     $description = eval qq("$dtempl");
2388   }
2389
2390   $cust_main->realtime_bop($method, $amount,
2391     'description' => $description,
2392     'invnum'      => $self->invnum,
2393 #this didn't do what we want, it just calls apply_payments_and_credits
2394 #    'apply'       => 1,
2395     'apply_to_invoice' => 1,
2396     %opt,
2397  #what we want:
2398  #this changes application behavior: auto payments
2399                         #triggered against a specific invoice are now applied
2400                         #to that invoice instead of oldest open.
2401                         #seem okay to me...
2402   );
2403
2404 }
2405
2406 =item batch_card OPTION => VALUE...
2407
2408 Adds a payment for this invoice to the pending credit card batch (see
2409 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
2410 runs the payment using a realtime gateway.
2411
2412 =cut
2413
2414 sub batch_card {
2415   my ($self, %options) = @_;
2416   my $cust_main = $self->cust_main;
2417
2418   $options{invnum} = $self->invnum;
2419   
2420   $cust_main->batch_card(%options);
2421 }
2422
2423 sub _agent_template {
2424   my $self = shift;
2425   $self->cust_main->agent_template;
2426 }
2427
2428 sub _agent_invoice_from {
2429   my $self = shift;
2430   $self->cust_main->agent_invoice_from;
2431 }
2432
2433 =item invoice_barcode DIR_OR_FALSE
2434
2435 Generates an invoice barcode PNG. If DIR_OR_FALSE is a true value,
2436 it is taken as the temp directory where the PNG file will be generated and the
2437 PNG file name is returned. Otherwise, the PNG image itself is returned.
2438
2439 =cut
2440
2441 sub invoice_barcode {
2442     my ($self, $dir) = (shift,shift);
2443     
2444     my $gdbar = new GD::Barcode('Code39',$self->invnum);
2445         die "can't create barcode: " . $GD::Barcode::errStr unless $gdbar;
2446     my $gd = $gdbar->plot(Height => 30);
2447
2448     if($dir) {
2449         my $bh = new File::Temp( TEMPLATE => 'barcode.'. $self->invnum. '.XXXXXXXX',
2450                            DIR      => $dir,
2451                            SUFFIX   => '.png',
2452                            UNLINK   => 0,
2453                          ) or die "can't open temp file: $!\n";
2454         print $bh $gd->png or die "cannot write barcode to file: $!\n";
2455         my $png_file = $bh->filename;
2456         close $bh;
2457         return $png_file;
2458     }
2459     return $gd->png;
2460 }
2461
2462 =item invnum_date_pretty
2463
2464 Returns a string with the invoice number and date, for example:
2465 "Invoice #54 (3/20/2008)"
2466
2467 =cut
2468
2469 sub invnum_date_pretty {
2470   my $self = shift;
2471   $self->mt('Invoice #'). $self->invnum. ' ('. $self->_date_pretty. ')';
2472 }
2473
2474 #sub _items_extra_usage_sections {
2475 #  my $self = shift;
2476 #  my $escape = shift;
2477 #
2478 #  my %sections = ();
2479 #
2480 #  my %usage_class =  map{ $_->classname, $_ } qsearch('usage_class', {});
2481 #  foreach my $cust_bill_pkg ( $self->cust_bill_pkg )
2482 #  {
2483 #    next unless $cust_bill_pkg->pkgnum > 0;
2484 #
2485 #    foreach my $section ( keys %usage_class ) {
2486 #
2487 #      my $usage = $cust_bill_pkg->usage($section);
2488 #
2489 #      next unless $usage && $usage > 0;
2490 #
2491 #      $sections{$section} ||= 0;
2492 #      $sections{$section} += $usage;
2493 #
2494 #    }
2495 #
2496 #  }
2497 #
2498 #  map { { 'description' => &{$escape}($_),
2499 #          'subtotal'    => $sections{$_},
2500 #          'summarized'  => '',
2501 #          'tax_section' => '',
2502 #        }
2503 #      }
2504 #    sort {$usage_class{$a}->weight <=> $usage_class{$b}->weight} keys %sections;
2505 #
2506 #}
2507
2508 sub _items_extra_usage_sections {
2509   my $self = shift;
2510   my $conf = $self->conf;
2511   my $escape = shift;
2512   my $format = shift;
2513
2514   my %sections = ();
2515   my %classnums = ();
2516   my %lines = ();
2517
2518   my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2519
2520   my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2521   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2522     next unless $cust_bill_pkg->pkgnum > 0;
2523
2524     foreach my $classnum ( keys %usage_class ) {
2525       my $section = $usage_class{$classnum}->classname;
2526       $classnums{$section} = $classnum;
2527
2528       foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail($classnum) ) {
2529         my $amount = $detail->amount;
2530         next unless $amount && $amount > 0;
2531  
2532         $sections{$section} ||= { 'subtotal'=>0, 'calls'=>0, 'duration'=>0 };
2533         $sections{$section}{amount} += $amount;  #subtotal
2534         $sections{$section}{calls}++;
2535         $sections{$section}{duration} += $detail->duration;
2536
2537         my $desc = $detail->regionname; 
2538         my $description = $desc;
2539         $description = substr($desc, 0, $maxlength). '...'
2540           if $format eq 'latex' && length($desc) > $maxlength;
2541
2542         $lines{$section}{$desc} ||= {
2543           description     => &{$escape}($description),
2544           #pkgpart         => $part_pkg->pkgpart,
2545           pkgnum          => $cust_bill_pkg->pkgnum,
2546           ref             => '',
2547           amount          => 0,
2548           calls           => 0,
2549           duration        => 0,
2550           #unit_amount     => $cust_bill_pkg->unitrecur,
2551           quantity        => $cust_bill_pkg->quantity,
2552           product_code    => 'N/A',
2553           ext_description => [],
2554         };
2555
2556         $lines{$section}{$desc}{amount} += $amount;
2557         $lines{$section}{$desc}{calls}++;
2558         $lines{$section}{$desc}{duration} += $detail->duration;
2559
2560       }
2561     }
2562   }
2563
2564   my %sectionmap = ();
2565   foreach (keys %sections) {
2566     my $usage_class = $usage_class{$classnums{$_}};
2567     $sectionmap{$_} = { 'description' => &{$escape}($_),
2568                         'amount'    => $sections{$_}{amount},    #subtotal
2569                         'calls'       => $sections{$_}{calls},
2570                         'duration'    => $sections{$_}{duration},
2571                         'summarized'  => '',
2572                         'tax_section' => '',
2573                         'sort_weight' => $usage_class->weight,
2574                         ( $usage_class->format
2575                           ? ( map { $_ => $usage_class->$_($format) }
2576                               qw( description_generator header_generator total_generator total_line_generator )
2577                             )
2578                           : ()
2579                         ), 
2580                       };
2581   }
2582
2583   my @sections = sort { $a->{sort_weight} <=> $b->{sort_weight} }
2584                  values %sectionmap;
2585
2586   my @lines = ();
2587   foreach my $section ( keys %lines ) {
2588     foreach my $line ( keys %{$lines{$section}} ) {
2589       my $l = $lines{$section}{$line};
2590       $l->{section}     = $sectionmap{$section};
2591       $l->{amount}      = sprintf( "%.2f", $l->{amount} );
2592       #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2593       push @lines, $l;
2594     }
2595   }
2596
2597   return(\@sections, \@lines);
2598
2599 }
2600
2601 sub _did_summary {
2602     my $self = shift;
2603     my $end = $self->_date;
2604
2605     # start at date of previous invoice + 1 second or 0 if no previous invoice
2606     my $start = $self->scalar_sql("SELECT max(_date) FROM cust_bill WHERE custnum = ? and invnum != ?",$self->custnum,$self->invnum);
2607     $start = 0 if !$start;
2608     $start++;
2609
2610     my $cust_main = $self->cust_main;
2611     my @pkgs = $cust_main->all_pkgs;
2612     my($num_activated,$num_deactivated,$num_portedin,$num_portedout,$minutes)
2613         = (0,0,0,0,0);
2614     my @seen = ();
2615     foreach my $pkg ( @pkgs ) {
2616         my @h_cust_svc = $pkg->h_cust_svc($end);
2617         foreach my $h_cust_svc ( @h_cust_svc ) {
2618             next if grep {$_ eq $h_cust_svc->svcnum} @seen;
2619             next unless $h_cust_svc->part_svc->svcdb eq 'svc_phone';
2620
2621             my $inserted = $h_cust_svc->date_inserted;
2622             my $deleted = $h_cust_svc->date_deleted;
2623             my $phone_inserted = $h_cust_svc->h_svc_x($inserted+5);
2624             my $phone_deleted;
2625             $phone_deleted =  $h_cust_svc->h_svc_x($deleted) if $deleted;
2626             
2627 # DID either activated or ported in; cannot be both for same DID simultaneously
2628             if ($inserted >= $start && $inserted <= $end && $phone_inserted
2629                 && (!$phone_inserted->lnp_status 
2630                     || $phone_inserted->lnp_status eq ''
2631                     || $phone_inserted->lnp_status eq 'native')) {
2632                 $num_activated++;
2633             }
2634             else { # this one not so clean, should probably move to (h_)svc_phone
2635                  my $phone_portedin = qsearchs( 'h_svc_phone',
2636                       { 'svcnum' => $h_cust_svc->svcnum, 
2637                         'lnp_status' => 'portedin' },  
2638                       FS::h_svc_phone->sql_h_searchs($end),  
2639                     );
2640                  $num_portedin++ if $phone_portedin;
2641             }
2642
2643 # DID either deactivated or ported out; cannot be both for same DID simultaneously
2644             if($deleted >= $start && $deleted <= $end && $phone_deleted
2645                 && (!$phone_deleted->lnp_status 
2646                     || $phone_deleted->lnp_status ne 'portingout')) {
2647                 $num_deactivated++;
2648             } 
2649             elsif($deleted >= $start && $deleted <= $end && $phone_deleted 
2650                 && $phone_deleted->lnp_status 
2651                 && $phone_deleted->lnp_status eq 'portingout') {
2652                 $num_portedout++;
2653             }
2654
2655             # increment usage minutes
2656         if ( $phone_inserted ) {
2657             my @cdrs = $phone_inserted->get_cdrs('begin'=>$start,'end'=>$end,'billsec_sum'=>1);
2658             $minutes = $cdrs[0]->billsec_sum if scalar(@cdrs) == 1;
2659         }
2660         else {
2661             warn "WARNING: no matching h_svc_phone insert record for insert time $inserted, svcnum " . $h_cust_svc->svcnum;
2662         }
2663
2664             # don't look at this service again
2665             push @seen, $h_cust_svc->svcnum;
2666         }
2667     }
2668
2669     $minutes = sprintf("%d", $minutes);
2670     ("Activated: $num_activated  Ported-In: $num_portedin  Deactivated: "
2671         . "$num_deactivated  Ported-Out: $num_portedout ",
2672             "Total Minutes: $minutes");
2673 }
2674
2675 sub _items_accountcode_cdr {
2676     my $self = shift;
2677     my $escape = shift;
2678     my $format = shift;
2679
2680     my $section = { 'amount'        => 0,
2681                     'calls'         => 0,
2682                     'duration'      => 0,
2683                     'sort_weight'   => '',
2684                     'phonenum'      => '',
2685                     'description'   => 'Usage by Account Code',
2686                     'post_total'    => '',
2687                     'summarized'    => '',
2688                     'header'        => '',
2689                   };
2690     my @lines;
2691     my %accountcodes = ();
2692
2693     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2694         next unless $cust_bill_pkg->pkgnum > 0;
2695
2696         my @header = $cust_bill_pkg->details_header;
2697         next unless scalar(@header);
2698         $section->{'header'} = join(',',@header);
2699
2700         foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2701
2702             $section->{'header'} = $detail->formatted('format' => $format)
2703                 if($detail->detail eq $section->{'header'}); 
2704       
2705             my $accountcode = $detail->accountcode;
2706             next unless $accountcode;
2707
2708             my $amount = $detail->amount;
2709             next unless $amount && $amount > 0;
2710
2711             $accountcodes{$accountcode} ||= {
2712                     description => $accountcode,
2713                     pkgnum      => '',
2714                     ref         => '',
2715                     amount      => 0,
2716                     calls       => 0,
2717                     duration    => 0,
2718                     quantity    => '',
2719                     product_code => 'N/A',
2720                     section     => $section,
2721                     ext_description => [ $section->{'header'} ],
2722                     detail_temp => [],
2723             };
2724
2725             $section->{'amount'} += $amount;
2726             $accountcodes{$accountcode}{'amount'} += $amount;
2727             $accountcodes{$accountcode}{calls}++;
2728             $accountcodes{$accountcode}{duration} += $detail->duration;
2729             push @{$accountcodes{$accountcode}{detail_temp}}, $detail;
2730         }
2731     }
2732
2733     foreach my $l ( values %accountcodes ) {
2734         $l->{amount} = sprintf( "%.2f", $l->{amount} );
2735         my @sorted_detail = sort { $a->startdate <=> $b->startdate } @{$l->{detail_temp}};
2736         foreach my $sorted_detail ( @sorted_detail ) {
2737             push @{$l->{ext_description}}, $sorted_detail->formatted('format'=>$format);
2738         }
2739         delete $l->{detail_temp};
2740         push @lines, $l;
2741     }
2742
2743     my @sorted_lines = sort { $a->{'description'} <=> $b->{'description'} } @lines;
2744
2745     return ($section,\@sorted_lines);
2746 }
2747
2748 sub _items_svc_phone_sections {
2749   my $self = shift;
2750   my $conf = $self->conf;
2751   my $escape = shift;
2752   my $format = shift;
2753
2754   my %sections = ();
2755   my %classnums = ();
2756   my %lines = ();
2757
2758   my $maxlength = $conf->config('cust_bill-latex_lineitem_maxlength') || 50;
2759
2760   my %usage_class =  map { $_->classnum => $_ } qsearch( 'usage_class', {} );
2761   $usage_class{''} ||= new FS::usage_class { 'classname' => '', 'weight' => 0 };
2762
2763   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
2764     next unless $cust_bill_pkg->pkgnum > 0;
2765
2766     my @header = $cust_bill_pkg->details_header;
2767     next unless scalar(@header);
2768
2769     foreach my $detail ( $cust_bill_pkg->cust_bill_pkg_detail ) {
2770
2771       my $phonenum = $detail->phonenum;
2772       next unless $phonenum;
2773
2774       my $amount = $detail->amount;
2775       next unless $amount && $amount > 0;
2776
2777       $sections{$phonenum} ||= { 'amount'      => 0,
2778                                  'calls'       => 0,
2779                                  'duration'    => 0,
2780                                  'sort_weight' => -1,
2781                                  'phonenum'    => $phonenum,
2782                                 };
2783       $sections{$phonenum}{amount} += $amount;  #subtotal
2784       $sections{$phonenum}{calls}++;
2785       $sections{$phonenum}{duration} += $detail->duration;
2786
2787       my $desc = $detail->regionname; 
2788       my $description = $desc;
2789       $description = substr($desc, 0, $maxlength). '...'
2790         if $format eq 'latex' && length($desc) > $maxlength;
2791
2792       $lines{$phonenum}{$desc} ||= {
2793         description     => &{$escape}($description),
2794         #pkgpart         => $part_pkg->pkgpart,
2795         pkgnum          => '',
2796         ref             => '',
2797         amount          => 0,
2798         calls           => 0,
2799         duration        => 0,
2800         #unit_amount     => '',
2801         quantity        => '',
2802         product_code    => 'N/A',
2803         ext_description => [],
2804       };
2805
2806       $lines{$phonenum}{$desc}{amount} += $amount;
2807       $lines{$phonenum}{$desc}{calls}++;
2808       $lines{$phonenum}{$desc}{duration} += $detail->duration;
2809
2810       my $line = $usage_class{$detail->classnum}->classname;
2811       $sections{"$phonenum $line"} ||=
2812         { 'amount' => 0,
2813           'calls' => 0,
2814           'duration' => 0,
2815           'sort_weight' => $usage_class{$detail->classnum}->weight,
2816           'phonenum' => $phonenum,
2817           'header'  => [ @header ],
2818         };
2819       $sections{"$phonenum $line"}{amount} += $amount;  #subtotal
2820       $sections{"$phonenum $line"}{calls}++;
2821       $sections{"$phonenum $line"}{duration} += $detail->duration;
2822
2823       $lines{"$phonenum $line"}{$desc} ||= {
2824         description     => &{$escape}($description),
2825         #pkgpart         => $part_pkg->pkgpart,
2826         pkgnum          => '',
2827         ref             => '',
2828         amount          => 0,
2829         calls           => 0,
2830         duration        => 0,
2831         #unit_amount     => '',
2832         quantity        => '',
2833         product_code    => 'N/A',
2834         ext_description => [],
2835       };
2836
2837       $lines{"$phonenum $line"}{$desc}{amount} += $amount;
2838       $lines{"$phonenum $line"}{$desc}{calls}++;
2839       $lines{"$phonenum $line"}{$desc}{duration} += $detail->duration;
2840       push @{$lines{"$phonenum $line"}{$desc}{ext_description}},
2841            $detail->formatted('format' => $format);
2842
2843     }
2844   }
2845
2846   my %sectionmap = ();
2847   my $simple = new FS::usage_class { format => 'simple' }; #bleh
2848   foreach ( keys %sections ) {
2849     my @header = @{ $sections{$_}{header} || [] };
2850     my $usage_simple =
2851       new FS::usage_class { format => 'usage_'. (scalar(@header) || 6). 'col' };
2852     my $summary = $sections{$_}{sort_weight} < 0 ? 1 : 0;
2853     my $usage_class = $summary ? $simple : $usage_simple;
2854     my $ending = $summary ? ' usage charges' : '';
2855     my %gen_opt = ();
2856     unless ($summary) {
2857       $gen_opt{label} = [ map{ &{$escape}($_) } @header ];
2858     }
2859     $sectionmap{$_} = { 'description' => &{$escape}($_. $ending),
2860                         'amount'    => $sections{$_}{amount},    #subtotal
2861                         'calls'       => $sections{$_}{calls},
2862                         'duration'    => $sections{$_}{duration},
2863                         'summarized'  => '',
2864                         'tax_section' => '',
2865                         'phonenum'    => $sections{$_}{phonenum},
2866                         'sort_weight' => $sections{$_}{sort_weight},
2867                         'post_total'  => $summary, #inspire pagebreak
2868                         (
2869                           ( map { $_ => $usage_class->$_($format, %gen_opt) }
2870                             qw( description_generator
2871                                 header_generator
2872                                 total_generator
2873                                 total_line_generator
2874                               )
2875                           )
2876                         ), 
2877                       };
2878   }
2879
2880   my @sections = sort { $a->{phonenum} cmp $b->{phonenum} ||
2881                         $a->{sort_weight} <=> $b->{sort_weight}
2882                       }
2883                  values %sectionmap;
2884
2885   my @lines = ();
2886   foreach my $section ( keys %lines ) {
2887     foreach my $line ( keys %{$lines{$section}} ) {
2888       my $l = $lines{$section}{$line};
2889       $l->{section}     = $sectionmap{$section};
2890       $l->{amount}      = sprintf( "%.2f", $l->{amount} );
2891       #$l->{unit_amount} = sprintf( "%.2f", $l->{unit_amount} );
2892       push @lines, $l;
2893     }
2894   }
2895   
2896   if($conf->exists('phone_usage_class_summary')) { 
2897       # this only works with Latex
2898       my @newlines;
2899       my @newsections;
2900
2901       # after this, we'll have only two sections per DID:
2902       # Calls Summary and Calls Detail
2903       foreach my $section ( @sections ) {
2904         if($section->{'post_total'}) {
2905             $section->{'description'} = 'Calls Summary: '.$section->{'phonenum'};
2906             $section->{'total_line_generator'} = sub { '' };
2907             $section->{'total_generator'} = sub { '' };
2908             $section->{'header_generator'} = sub { '' };
2909             $section->{'description_generator'} = '';
2910             push @newsections, $section;
2911             my %calls_detail = %$section;
2912             $calls_detail{'post_total'} = '';
2913             $calls_detail{'sort_weight'} = '';
2914             $calls_detail{'description_generator'} = sub { '' };
2915             $calls_detail{'header_generator'} = sub {
2916                 return ' & Date/Time & Called Number & Duration & Price'
2917                     if $format eq 'latex';
2918                 '';
2919             };
2920             $calls_detail{'description'} = 'Calls Detail: '
2921                                                     . $section->{'phonenum'};
2922             push @newsections, \%calls_detail;  
2923         }
2924       }
2925
2926       # after this, each usage class is collapsed/summarized into a single
2927       # line under the Calls Summary section
2928       foreach my $newsection ( @newsections ) {
2929         if($newsection->{'post_total'}) { # this means Calls Summary
2930             foreach my $section ( @sections ) {
2931                 next unless ($section->{'phonenum'} eq $newsection->{'phonenum'} 
2932                                 && !$section->{'post_total'});
2933                 my $newdesc = $section->{'description'};
2934                 my $tn = $section->{'phonenum'};
2935                 $newdesc =~ s/$tn//g;
2936                 my $line = {  ext_description => [],
2937                               pkgnum => '',
2938                               ref => '',
2939                               quantity => '',
2940                               calls => $section->{'calls'},
2941                               section => $newsection,
2942                               duration => $section->{'duration'},
2943                               description => $newdesc,
2944                               amount => sprintf("%.2f",$section->{'amount'}),
2945                               product_code => 'N/A',
2946                             };
2947                 push @newlines, $line;
2948             }
2949         }
2950       }
2951
2952       # after this, Calls Details is populated with all CDRs
2953       foreach my $newsection ( @newsections ) {
2954         if(!$newsection->{'post_total'}) { # this means Calls Details
2955             foreach my $line ( @lines ) {
2956                 next unless (scalar(@{$line->{'ext_description'}}) &&
2957                         $line->{'section'}->{'phonenum'} eq $newsection->{'phonenum'}
2958                             );
2959                 my @extdesc = @{$line->{'ext_description'}};
2960                 my @newextdesc;
2961                 foreach my $extdesc ( @extdesc ) {
2962                     $extdesc =~ s/scriptsize/normalsize/g if $format eq 'latex';
2963                     push @newextdesc, $extdesc;
2964                 }
2965                 $line->{'ext_description'} = \@newextdesc;
2966                 $line->{'section'} = $newsection;
2967                 push @newlines, $line;
2968             }
2969         }
2970       }
2971
2972       return(\@newsections, \@newlines);
2973   }
2974
2975   return(\@sections, \@lines);
2976
2977 }
2978
2979 sub _items_previous {
2980   my $self = shift;
2981   my $conf = $self->conf;
2982   my $cust_main = $self->cust_main;
2983   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2984   my @b = ();
2985   foreach ( @pr_cust_bill ) {
2986     my $date = $conf->exists('invoice_show_prior_due_date')
2987                ? 'due '. $_->due_date2str($date_format)
2988                : $self->time2str_local($date_format, $_->_date);
2989     push @b, {
2990       'description' => $self->mt('Previous Balance, Invoice #'). $_->invnum. " ($date)",
2991       #'pkgpart'     => 'N/A',
2992       'pkgnum'      => 'N/A',
2993       'amount'      => sprintf("%.2f", $_->owed),
2994     };
2995   }
2996   @b;
2997
2998   #{
2999   #    'description'     => 'Previous Balance',
3000   #    #'pkgpart'         => 'N/A',
3001   #    'pkgnum'          => 'N/A',
3002   #    'amount'          => sprintf("%10.2f", $pr_total ),
3003   #    'ext_description' => [ map {
3004   #                                 "Invoice ". $_->invnum.
3005   #                                 " (". time2str("%x",$_->_date). ") ".
3006   #                                 sprintf("%10.2f", $_->owed)
3007   #                         } @pr_cust_bill ],
3008
3009   #};
3010 }
3011
3012 sub _items_credits {
3013   my( $self, %opt ) = @_;
3014   my $trim_len = $opt{'trim_len'} || 60;
3015
3016   my @b;
3017   #credits
3018   my @objects;
3019   if ( $self->conf->exists('previous_balance-payments_since') ) {
3020     if ( $opt{'template'} eq 'statement' ) {
3021       # then the current bill is a "statement" (i.e. an invoice sent as
3022       # a payment receipt)
3023       # and in that case we want to see payments on or after THIS invoice
3024       @objects = qsearch('cust_credit', {
3025           'custnum' => $self->custnum,
3026           '_date'   => {op => '>=', value => $self->_date},
3027       });
3028     } else {
3029       my $date = 0;
3030       $date = $self->previous_bill->_date if $self->previous_bill;
3031       @objects = qsearch('cust_credit', {
3032           'custnum' => $self->custnum,
3033           '_date'   => {op => '>=', value => $date},
3034       });
3035     }
3036   } else {
3037     @objects = $self->cust_credited;
3038   }
3039
3040   foreach my $obj ( @objects ) {
3041     my $cust_credit = $obj->isa('FS::cust_credit') ? $obj : $obj->cust_credit;
3042
3043     my $reason = substr($cust_credit->reason, 0, $trim_len);
3044     $reason .= '...' if length($reason) < length($cust_credit->reason);
3045     $reason = " ($reason) " if $reason;
3046
3047     push @b, {
3048       #'description' => 'Credit ref\#'. $_->crednum.
3049       #                 " (". time2str("%x",$_->cust_credit->_date) .")".
3050       #                 $reason,
3051       'description' => $self->mt('Credit applied').' '.
3052                        $self->time2str_local($date_format,$obj->_date). $reason,
3053       'amount'      => sprintf("%.2f",$obj->amount),
3054     };
3055   }
3056
3057   @b;
3058
3059 }
3060
3061 sub _items_payments {
3062   my $self = shift;
3063   my %opt = @_;
3064
3065   my @b;
3066   my $detailed = $self->conf->exists('invoice_payment_details');
3067   my @objects;
3068   if ( $self->conf->exists('previous_balance-payments_since') ) {
3069     # then show payments dated on/after the previous bill...
3070     if ( $opt{'template'} eq 'statement' ) {
3071       # then the current bill is a "statement" (i.e. an invoice sent as
3072       # a payment receipt)
3073       # and in that case we want to see payments on or after THIS invoice
3074       @objects = qsearch('cust_pay', {
3075           'custnum' => $self->custnum,
3076           '_date'   => {op => '>=', value => $self->_date},
3077       });
3078     } else {
3079       # the normal case: payments on or after the previous invoice
3080       my $date = 0;
3081       $date = $self->previous_bill->_date if $self->previous_bill;
3082       @objects = qsearch('cust_pay', {
3083         'custnum' => $self->custnum,
3084         '_date'   => {op => '>=', value => $date},
3085       });
3086       # and before the current bill...
3087       @objects = grep { $_->_date < $self->_date } @objects;
3088     }
3089   } else {
3090     @objects = $self->cust_bill_pay;
3091   }
3092
3093   foreach my $obj (@objects) {
3094     my $cust_pay = $obj->isa('FS::cust_pay') ? $obj : $obj->cust_pay;
3095     my $desc = $self->mt('Payment received').' '.
3096                $self->time2str_local($date_format, $cust_pay->_date );
3097     $desc .= $self->mt(' via ') .
3098              $cust_pay->payby_payinfo_pretty( $self->cust_main->locale )
3099       if $detailed;
3100
3101     push @b, {
3102       'description' => $desc,
3103       'amount'      => sprintf("%.2f", $obj->amount )
3104     };
3105   }
3106
3107   @b;
3108
3109 }
3110
3111 =item call_details [ OPTION => VALUE ... ]
3112
3113 Returns an array of CSV strings representing the call details for this invoice
3114 The only option available is the boolean prepend_billed_number
3115
3116 =cut
3117
3118 sub call_details {
3119   my ($self, %opt) = @_;
3120
3121   my $format_function = sub { shift };
3122
3123   if ($opt{prepend_billed_number}) {
3124     $format_function = sub {
3125       my $detail = shift;
3126       my $row = shift;
3127
3128       $row->amount ? $row->phonenum. ",". $detail : '"Billed number",'. $detail;
3129       
3130     };
3131   }
3132
3133   my @details = map { $_->details( 'format_function' => $format_function,
3134                                    'escape_function' => sub{ return() },
3135                                  )
3136                     }
3137                   grep { $_->pkgnum }
3138                   $self->cust_bill_pkg;
3139   my $header = $details[0];
3140   ( $header, grep { $_ ne $header } @details );
3141 }
3142
3143
3144 =back
3145
3146 =head1 SUBROUTINES
3147
3148 =over 4
3149
3150 =item process_reprint
3151
3152 =cut
3153
3154 sub process_reprint {
3155   process_re_X('print', @_);
3156 }
3157
3158 =item process_reemail
3159
3160 =cut
3161
3162 sub process_reemail {
3163   process_re_X('email', @_);
3164 }
3165
3166 =item process_refax
3167
3168 =cut
3169
3170 sub process_refax {
3171   process_re_X('fax', @_);
3172 }
3173
3174 =item process_reftp
3175
3176 =cut
3177
3178 sub process_reftp {
3179   process_re_X('ftp', @_);
3180 }
3181
3182 =item respool
3183
3184 =cut
3185
3186 sub process_respool {
3187   process_re_X('spool', @_);
3188 }
3189
3190 use Storable qw(thaw);
3191 use Data::Dumper;
3192 use MIME::Base64;
3193 sub process_re_X {
3194   my( $method, $job ) = ( shift, shift );
3195   warn "$me process_re_X $method for job $job\n" if $DEBUG;
3196
3197   my $param = thaw(decode_base64(shift));
3198   warn Dumper($param) if $DEBUG;
3199
3200   re_X(
3201     $method,
3202     $job,
3203     %$param,
3204   );
3205
3206 }
3207
3208 sub re_X {
3209   # spool_invoice ftp_invoice fax_invoice print_invoice
3210   my($method, $job, %param ) = @_;
3211   if ( $DEBUG ) {
3212     warn "re_X $method for job $job with param:\n".
3213          join( '', map { "  $_ => ". $param{$_}. "\n" } keys %param );
3214   }
3215
3216   #some false laziness w/search/cust_bill.html
3217   my $distinct = '';
3218   my $orderby = 'ORDER BY cust_bill._date';
3219
3220   my $extra_sql = ' WHERE '. FS::cust_bill->search_sql_where(\%param);
3221
3222   my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
3223      
3224   my @cust_bill = qsearch( {
3225     #'select'    => "cust_bill.*",
3226     'table'     => 'cust_bill',
3227     'addl_from' => $addl_from,
3228     'hashref'   => {},
3229     'extra_sql' => $extra_sql,
3230     'order_by'  => $orderby,
3231     'debug' => 1,
3232   } );
3233
3234   $method .= '_invoice' unless $method eq 'email' || $method eq 'print';
3235
3236   warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
3237     if $DEBUG;
3238
3239   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
3240   foreach my $cust_bill ( @cust_bill ) {
3241     $cust_bill->$method();
3242
3243     if ( $job ) { #progressbar foo
3244       $num++;
3245       if ( time - $min_sec > $last ) {
3246         my $error = $job->update_statustext(
3247           int( 100 * $num / scalar(@cust_bill) )
3248         );
3249         die $error if $error;
3250         $last = time;
3251       }
3252     }
3253
3254   }
3255
3256 }
3257
3258 =back
3259
3260 =head1 CLASS METHODS
3261
3262 =over 4
3263
3264 =item owed_sql
3265
3266 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
3267
3268 =cut
3269
3270 sub owed_sql {
3271   my ($class, $start, $end) = @_;
3272   'charged - '. 
3273     $class->paid_sql($start, $end). ' - '. 
3274     $class->credited_sql($start, $end);
3275 }
3276
3277 =item net_sql
3278
3279 Returns an SQL fragment to retreive the net amount (charged minus credited).
3280
3281 =cut
3282
3283 sub net_sql {
3284   my ($class, $start, $end) = @_;
3285   'charged - '. $class->credited_sql($start, $end);
3286 }
3287
3288 =item paid_sql
3289
3290 Returns an SQL fragment to retreive the amount paid against this invoice.
3291
3292 =cut
3293
3294 sub paid_sql {
3295   my ($class, $start, $end) = @_;
3296   $start &&= "AND cust_bill_pay._date <= $start";
3297   $end   &&= "AND cust_bill_pay._date > $end";
3298   $start = '' unless defined($start);
3299   $end   = '' unless defined($end);
3300   "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
3301        WHERE cust_bill.invnum = cust_bill_pay.invnum $start $end  )";
3302 }
3303
3304 =item credited_sql
3305
3306 Returns an SQL fragment to retreive the amount credited against this invoice.
3307
3308 =cut
3309
3310 sub credited_sql {
3311   my ($class, $start, $end) = @_;
3312   $start &&= "AND cust_credit_bill._date <= $start";
3313   $end   &&= "AND cust_credit_bill._date >  $end";
3314   $start = '' unless defined($start);
3315   $end   = '' unless defined($end);
3316   "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
3317        WHERE cust_bill.invnum = cust_credit_bill.invnum $start $end  )";
3318 }
3319
3320 =item due_date_sql
3321
3322 Returns an SQL fragment to retrieve the due date of an invoice.
3323 Currently only supported on PostgreSQL.
3324
3325 =cut
3326
3327 sub due_date_sql {
3328   my $conf = new FS::Conf;
3329 'COALESCE(
3330   SUBSTRING(
3331     COALESCE(
3332       cust_bill.invoice_terms,
3333       cust_main.invoice_terms,
3334       \''.($conf->config('invoice_default_terms') || '').'\'
3335     ), E\'Net (\\\\d+)\'
3336   )::INTEGER, 0
3337 ) * 86400 + cust_bill._date'
3338 }
3339
3340 =item search_sql_where HASHREF
3341
3342 Class method which returns an SQL WHERE fragment to search for parameters
3343 specified in HASHREF.  Valid parameters are
3344
3345 =over 4
3346
3347 =item _date
3348
3349 List reference of start date, end date, as UNIX timestamps.
3350
3351 =item invnum_min
3352
3353 =item invnum_max
3354
3355 =item agentnum
3356
3357 =item charged
3358
3359 List reference of charged limits (exclusive).
3360
3361 =item owed
3362
3363 List reference of charged limits (exclusive).
3364
3365 =item open
3366
3367 flag, return open invoices only
3368
3369 =item net
3370
3371 flag, return net invoices only
3372
3373 =item days
3374
3375 =item newest_percust
3376
3377 =back
3378
3379 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
3380
3381 =cut
3382
3383 sub search_sql_where {
3384   my($class, $param) = @_;
3385   if ( $DEBUG ) {
3386     warn "$me search_sql_where called with params: \n".
3387          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
3388   }
3389
3390   my @search = ();
3391
3392   #agentnum
3393   if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
3394     push @search, "cust_main.agentnum = $1";
3395   }
3396
3397   #refnum
3398   if ( $param->{'refnum'} =~ /^(\d+)$/ ) {
3399     push @search, "cust_main.refnum = $1";
3400   }
3401
3402   #custnum
3403   if ( $param->{'custnum'} =~ /^(\d+)$/ ) {
3404     push @search, "cust_bill.custnum = $1";
3405   }
3406
3407   #customer classnum (false laziness w/ cust_main/Search.pm)
3408   if ( $param->{'cust_classnum'} ) {
3409
3410     my @classnum = ref( $param->{'cust_classnum'} )
3411                      ? @{ $param->{'cust_classnum'} }
3412                      :  ( $param->{'cust_classnum'} );
3413
3414     @classnum = grep /^(\d*)$/, @classnum;
3415
3416     if ( @classnum ) {
3417       push @search, '( '. join(' OR ', map {
3418                                              $_ ? "cust_main.classnum = $_"
3419                                                 : "cust_main.classnum IS NULL"
3420                                            }
3421                                            @classnum
3422                               ).
3423                     ' )';
3424     }
3425
3426   }
3427
3428   #_date
3429   if ( $param->{_date} ) {
3430     my($beginning, $ending) = @{$param->{_date}};
3431
3432     push @search, "cust_bill._date >= $beginning",
3433                   "cust_bill._date <  $ending";
3434   }
3435
3436   #invnum
3437   if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
3438     push @search, "cust_bill.invnum >= $1";
3439   }
3440   if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
3441     push @search, "cust_bill.invnum <= $1";
3442   }
3443
3444   #charged
3445   if ( $param->{charged} ) {
3446     my @charged = ref($param->{charged})
3447                     ? @{ $param->{charged} }
3448                     : ($param->{charged});
3449
3450     push @search, map { s/^charged/cust_bill.charged/; $_; }
3451                       @charged;
3452   }
3453
3454   my $owed_sql = FS::cust_bill->owed_sql;
3455
3456   #owed
3457   if ( $param->{owed} ) {
3458     my @owed = ref($param->{owed})
3459                  ? @{ $param->{owed} }
3460                  : ($param->{owed});
3461     push @search, map { s/^owed/$owed_sql/; $_; }
3462                       @owed;
3463   }
3464
3465   #open/net flags
3466   push @search, "0 != $owed_sql"
3467     if $param->{'open'};
3468   push @search, '0 != '. FS::cust_bill->net_sql
3469     if $param->{'net'};
3470
3471   #days
3472   push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
3473     if $param->{'days'};
3474
3475   #newest_percust
3476   if ( $param->{'newest_percust'} ) {
3477
3478     #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
3479     #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
3480
3481     my @newest_where = map { my $x = $_;
3482                              $x =~ s/\bcust_bill\./newest_cust_bill./g;
3483                              $x;
3484                            }
3485                            grep ! /^cust_main./, @search;
3486     my $newest_where = scalar(@newest_where)
3487                          ? ' AND '. join(' AND ', @newest_where)
3488                          : '';
3489
3490
3491     push @search, "cust_bill._date = (
3492       SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
3493         WHERE newest_cust_bill.custnum = cust_bill.custnum
3494           $newest_where
3495     )";
3496
3497   }
3498
3499   #promised_date - also has an option to accept nulls
3500   if ( $param->{promised_date} ) {
3501     my($beginning, $ending, $null) = @{$param->{promised_date}};
3502
3503     push @search, "(( cust_bill.promised_date >= $beginning AND ".
3504                     "cust_bill.promised_date <  $ending )" .
3505                     ($null ? ' OR cust_bill.promised_date IS NULL ) ' : ')');
3506   }
3507
3508   #agent virtualization
3509   my $curuser = $FS::CurrentUser::CurrentUser;
3510   if ( $curuser->username eq 'fs_queue'
3511        && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
3512     my $username = $1;
3513     my $newuser = qsearchs('access_user', {
3514       'username' => $username,
3515       'disabled' => '',
3516     } );
3517     if ( $newuser ) {
3518       $curuser = $newuser;
3519     } else {
3520       warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
3521     }
3522   }
3523   push @search, $curuser->agentnums_sql;
3524
3525   join(' AND ', @search );
3526
3527 }
3528
3529 =back
3530
3531 =head1 BUGS
3532
3533 The delete method.
3534
3535 =head1 SEE ALSO
3536
3537 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
3538 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base
3539 documentation.
3540
3541 =cut
3542
3543 1;
3544