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