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