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