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