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