voxline invoice formatting
[freeside.git] / FS / FS / cust_bill.pm
1 package FS::cust_bill;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $me $conf $money_char );
5 use vars qw( $invoice_lines @buf ); #yuck
6 use Fcntl qw(:flock); #for spool_csv
7 use List::Util qw(min max);
8 use Date::Format;
9 use Text::Template 1.20;
10 use File::Temp 0.14;
11 use String::ShellQuote;
12 use HTML::Entities;
13 use Locale::Country;
14 use FS::UID qw( datasrc );
15 use FS::Misc qw( send_email send_fax generate_ps generate_pdf do_print );
16 use FS::Record qw( qsearch qsearchs dbh );
17 use FS::cust_main_Mixin;
18 use FS::cust_main;
19 use FS::cust_bill_pkg;
20 use FS::cust_credit;
21 use FS::cust_pay;
22 use FS::cust_pkg;
23 use FS::cust_credit_bill;
24 use FS::pay_batch;
25 use FS::cust_pay_batch;
26 use FS::cust_bill_event;
27 use FS::part_pkg;
28 use FS::cust_bill_pay;
29 use FS::cust_bill_pay_batch;
30 use FS::part_bill_event;
31 use FS::payby;
32
33 @ISA = qw( FS::cust_main_Mixin FS::Record );
34
35 $DEBUG = 0;
36 $me = '[FS::cust_bill]';
37
38 #ask FS::UID to run this stuff for us later
39 FS::UID->install_callback( sub { 
40   $conf = new FS::Conf;
41   $money_char = $conf->config('money_char') || '$';  
42 } );
43
44 =head1 NAME
45
46 FS::cust_bill - Object methods for cust_bill records
47
48 =head1 SYNOPSIS
49
50   use FS::cust_bill;
51
52   $record = new FS::cust_bill \%hash;
53   $record = new FS::cust_bill { 'column' => 'value' };
54
55   $error = $record->insert;
56
57   $error = $new_record->replace($old_record);
58
59   $error = $record->delete;
60
61   $error = $record->check;
62
63   ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
64
65   @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
66
67   ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
68
69   @cust_pay_objects = $cust_bill->cust_pay;
70
71   $tax_amount = $record->tax;
72
73   @lines = $cust_bill->print_text;
74   @lines = $cust_bill->print_text $time;
75
76 =head1 DESCRIPTION
77
78 An FS::cust_bill object represents an invoice; a declaration that a customer
79 owes you money.  The specific charges are itemized as B<cust_bill_pkg> records
80 (see L<FS::cust_bill_pkg>).  FS::cust_bill inherits from FS::Record.  The
81 following fields are currently supported:
82
83 =over 4
84
85 =item invnum - primary key (assigned automatically for new invoices)
86
87 =item custnum - customer (see L<FS::cust_main>)
88
89 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
90 L<Time::Local> and L<Date::Parse> for conversion functions.
91
92 =item charged - amount of this invoice
93
94 =item printed - deprecated
95
96 =item closed - books closed flag, empty or `Y'
97
98 =back
99
100 =head1 METHODS
101
102 =over 4
103
104 =item new HASHREF
105
106 Creates a new invoice.  To add the invoice to the database, see L<"insert">.
107 Invoices are normally created by calling the bill method of a customer object
108 (see L<FS::cust_main>).
109
110 =cut
111
112 sub table { 'cust_bill'; }
113
114 sub cust_linked { $_[0]->cust_main_custnum; } 
115 sub cust_unlinked_msg {
116   my $self = shift;
117   "WARNING: can't find cust_main.custnum ". $self->custnum.
118   ' (cust_bill.invnum '. $self->invnum. ')';
119 }
120
121 =item insert
122
123 Adds this invoice to the database ("Posts" the invoice).  If there is an error,
124 returns the error, otherwise returns false.
125
126 =item delete
127
128 This method now works but you probably shouldn't use it.  Instead, apply a
129 credit against the invoice.
130
131 Using this method to delete invoices outright is really, really bad.  There
132 would be no record you ever posted this invoice, and there are no check to
133 make sure charged = 0 or that there are no associated cust_bill_pkg records.
134
135 Really, don't use it.
136
137 =cut
138
139 sub delete {
140   my $self = shift;
141   return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
142   $self->SUPER::delete(@_);
143 }
144
145 =item replace OLD_RECORD
146
147 Replaces the OLD_RECORD with this one in the database.  If there is an error,
148 returns the error, otherwise returns false.
149
150 Only printed may be changed.  printed is normally updated by calling the
151 collect method of a customer object (see L<FS::cust_main>).
152
153 =cut
154
155 #replace can be inherited from Record.pm
156
157 # replace_check is now the preferred way to #implement replace data checks
158 # (so $object->replace() works without an argument)
159
160 sub replace_check {
161   my( $new, $old ) = ( shift, shift );
162   return "Can't change custnum!" unless $old->custnum == $new->custnum;
163   #return "Can't change _date!" unless $old->_date eq $new->_date;
164   return "Can't change _date!" unless $old->_date == $new->_date;
165   return "Can't change charged!" unless $old->charged == $new->charged
166                                      || $old->charged == 0;
167
168   '';
169 }
170
171 =item check
172
173 Checks all fields to make sure this is a valid invoice.  If there is an error,
174 returns the error, otherwise returns false.  Called by the insert and replace
175 methods.
176
177 =cut
178
179 sub check {
180   my $self = shift;
181
182   my $error =
183     $self->ut_numbern('invnum')
184     || $self->ut_number('custnum')
185     || $self->ut_numbern('_date')
186     || $self->ut_money('charged')
187     || $self->ut_numbern('printed')
188     || $self->ut_enum('closed', [ '', 'Y' ])
189   ;
190   return $error if $error;
191
192   return "Unknown customer"
193     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
194
195   $self->_date(time) unless $self->_date;
196
197   $self->printed(0) if $self->printed eq '';
198
199   $self->SUPER::check;
200 }
201
202 =item previous
203
204 Returns a list consisting of the total previous balance for this customer, 
205 followed by the previous outstanding invoices (as FS::cust_bill objects also).
206
207 =cut
208
209 sub previous {
210   my $self = shift;
211   my $total = 0;
212   my @cust_bill = sort { $a->_date <=> $b->_date }
213     grep { $_->owed != 0 && $_->_date < $self->_date }
214       qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) 
215   ;
216   foreach ( @cust_bill ) { $total += $_->owed; }
217   $total, @cust_bill;
218 }
219
220 =item cust_bill_pkg
221
222 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
223
224 =cut
225
226 sub cust_bill_pkg {
227   my $self = shift;
228   qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum } );
229 }
230
231 =item cust_pkg
232
233 Returns the packages (see L<FS::cust_pkg>) corresponding to the line items for
234 this invoice.
235
236 =cut
237
238 sub cust_pkg {
239   my $self = shift;
240   my @cust_pkg = map { $_->cust_pkg } $self->cust_bill_pkg;
241   my %saw = ();
242   grep { ! $saw{$_->pkgnum}++ } @cust_pkg;
243 }
244
245 =item open_cust_bill_pkg
246
247 Returns the open line items for this invoice.
248
249 Note that cust_bill_pkg with both setup and recur fees are returned as two
250 separate line items, each with only one fee.
251
252 =cut
253
254 # modeled after cust_main::open_cust_bill
255 sub open_cust_bill_pkg {
256   my $self = shift;
257
258   # grep { $_->owed > 0 } $self->cust_bill_pkg
259
260   my %other = ( 'recur' => 'setup',
261                 'setup' => 'recur', );
262   my @open = ();
263   foreach my $field ( qw( recur setup )) {
264     push @open, map  { $_->set( $other{$field}, 0 ); $_; }
265                 grep { $_->owed($field) > 0 }
266                 $self->cust_bill_pkg;
267   }
268
269   @open;
270 }
271
272 =item cust_bill_event
273
274 Returns the completed invoice events (see L<FS::cust_bill_event>) for this
275 invoice.
276
277 =cut
278
279 sub cust_bill_event {
280   my $self = shift;
281   qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
282 }
283
284
285 =item cust_main
286
287 Returns the customer (see L<FS::cust_main>) for this invoice.
288
289 =cut
290
291 sub cust_main {
292   my $self = shift;
293   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
294 }
295
296 =item cust_suspend_if_balance_over AMOUNT
297
298 Suspends the customer associated with this invoice if the total amount owed on
299 this invoice and all older invoices is greater than the specified amount.
300
301 Returns a list: an empty list on success or a list of errors.
302
303 =cut
304
305 sub cust_suspend_if_balance_over {
306   my( $self, $amount ) = ( shift, shift );
307   my $cust_main = $self->cust_main;
308   if ( $cust_main->total_owed_date($self->_date) < $amount ) {
309     return ();
310   } else {
311     $cust_main->suspend(@_);
312   }
313 }
314
315 =item cust_credit
316
317 Depreciated.  See the cust_credited method.
318
319  #Returns a list consisting of the total previous credited (see
320  #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
321  #outstanding credits (FS::cust_credit objects).
322
323 =cut
324
325 sub cust_credit {
326   use Carp;
327   croak "FS::cust_bill->cust_credit depreciated; see ".
328         "FS::cust_bill->cust_credit_bill";
329   #my $self = shift;
330   #my $total = 0;
331   #my @cust_credit = sort { $a->_date <=> $b->_date }
332   #  grep { $_->credited != 0 && $_->_date < $self->_date }
333   #    qsearch('cust_credit', { 'custnum' => $self->custnum } )
334   #;
335   #foreach (@cust_credit) { $total += $_->credited; }
336   #$total, @cust_credit;
337 }
338
339 =item cust_pay
340
341 Depreciated.  See the cust_bill_pay method.
342
343 #Returns all payments (see L<FS::cust_pay>) for this invoice.
344
345 =cut
346
347 sub cust_pay {
348   use Carp;
349   croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
350   #my $self = shift;
351   #sort { $a->_date <=> $b->_date }
352   #  qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
353   #;
354 }
355
356 =item cust_bill_pay
357
358 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
359
360 =cut
361
362 sub cust_bill_pay {
363   my $self = shift;
364   sort { $a->_date <=> $b->_date }
365     qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
366 }
367
368 =item cust_credited
369
370 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
371
372 =cut
373
374 sub cust_credited {
375   my $self = shift;
376   sort { $a->_date <=> $b->_date }
377     qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
378   ;
379 }
380
381 =item tax
382
383 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
384
385 =cut
386
387 sub tax {
388   my $self = shift;
389   my $total = 0;
390   my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
391                                              'pkgnum' => 0 } );
392   foreach (@taxlines) { $total += $_->setup; }
393   $total;
394 }
395
396 =item owed
397
398 Returns the amount owed (still outstanding) on this invoice, which is charged
399 minus all payment applications (see L<FS::cust_bill_pay>) and credit
400 applications (see L<FS::cust_credit_bill>).
401
402 =cut
403
404 sub owed {
405   my $self = shift;
406   my $balance = $self->charged;
407   $balance -= $_->amount foreach ( $self->cust_bill_pay );
408   $balance -= $_->amount foreach ( $self->cust_credited );
409   $balance = sprintf( "%.2f", $balance);
410   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
411   $balance;
412 }
413
414 =item apply_payments_and_credits
415
416 =cut
417
418 sub apply_payments_and_credits {
419   my $self = shift;
420
421   local $SIG{HUP} = 'IGNORE';
422   local $SIG{INT} = 'IGNORE';
423   local $SIG{QUIT} = 'IGNORE';
424   local $SIG{TERM} = 'IGNORE';
425   local $SIG{TSTP} = 'IGNORE';
426   local $SIG{PIPE} = 'IGNORE';
427
428   my $oldAutoCommit = $FS::UID::AutoCommit;
429   local $FS::UID::AutoCommit = 0;
430   my $dbh = dbh;
431
432   $self->select_for_update; #mutex
433
434   my @payments = grep { $_->unapplied > 0 } $self->cust_main->cust_pay;
435   my @credits  = grep { $_->credited > 0 } $self->cust_main->cust_credit;
436
437   while ( $self->owed > 0 and ( @payments || @credits ) ) {
438
439     my $app = '';
440     if ( @payments && @credits ) {
441
442       #decide which goes first by weight of top (unapplied) line item
443
444       my @open_lineitems = $self->open_cust_bill_pkg;
445
446       my $max_pay_weight =
447         max( map  { $_->part_pkg->pay_weight || 0 }
448              grep { $_ }
449              map  { $_->cust_pkg }
450                   @open_lineitems
451            );
452       my $max_credit_weight =
453         max( map  { $_->part_pkg->credit_weight || 0 }
454              grep { $_ } 
455              map  { $_->cust_pkg }
456                   @open_lineitems
457            );
458
459       #if both are the same... payments first?  it has to be something
460       if ( $max_pay_weight >= $max_credit_weight ) {
461         $app = 'pay';
462       } else {
463         $app = 'credit';
464       }
465     
466     } elsif ( @payments ) {
467       $app = 'pay';
468     } elsif ( @credits ) {
469       $app = 'credit';
470     } else {
471       die "guru meditation #12 and 35";
472     }
473
474     if ( $app eq 'pay' ) {
475
476       my $payment = shift @payments;
477
478       $app = new FS::cust_bill_pay {
479         'paynum'  => $payment->paynum,
480         'amount'  => sprintf('%.2f', min( $payment->unapplied, $self->owed ) ),
481       };
482
483     } elsif ( $app eq 'credit' ) {
484
485       my $credit = shift @credits;
486
487       $app = new FS::cust_credit_bill {
488         'crednum' => $credit->crednum,
489         'amount'  => sprintf('%.2f', min( $credit->credited, $self->owed ) ),
490       };
491
492     } else {
493       die "guru meditation #12 and 35";
494     }
495
496     $app->invnum( $self->invnum );
497
498     my $error = $app->insert;
499     if ( $error ) {
500       $dbh->rollback if $oldAutoCommit;
501       return "Error inserting ". $app->table. " record: $error";
502     }
503     die $error if $error;
504
505   }
506
507   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
508   ''; #no error
509
510 }
511
512 =item generate_email PARAMHASH
513
514 PARAMHASH can contain the following:
515
516 =over 4
517
518 =item from       => sender address, required
519
520 =item tempate    => alternate template name, optional
521
522 =item print_text => text attachment arrayref, optional
523
524 =item subject    => email subject, optional
525
526 =back
527
528 Returns an argument list to be passed to L<FS::Misc::send_email>.
529
530 =cut
531
532 use MIME::Entity;
533
534 sub generate_email {
535
536   my $self = shift;
537   my %args = @_;
538
539   my $me = '[FS::cust_bill::generate_email]';
540
541   my %return = (
542     'from'      => $args{'from'},
543     'subject'   => (($args{'subject'}) ? $args{'subject'} : 'Invoice'),
544   );
545
546   if (ref($args{'to'}) eq 'ARRAY') {
547     $return{'to'} = $args{'to'};
548   } else {
549     $return{'to'} = [ grep { $_ !~ /^(POST|FAX)$/ }
550                            $self->cust_main->invoicing_list
551                     ];
552   }
553
554   if ( $conf->exists('invoice_html') ) {
555
556     warn "$me creating HTML/text multipart message"
557       if $DEBUG;
558
559     $return{'nobody'} = 1;
560
561     my $alternative = build MIME::Entity
562       'Type'        => 'multipart/alternative',
563       'Encoding'    => '7bit',
564       'Disposition' => 'inline'
565     ;
566
567     my $data;
568     if ( $conf->exists('invoice_email_pdf')
569          and scalar($conf->config('invoice_email_pdf_note')) ) {
570
571       warn "$me using 'invoice_email_pdf_note' in multipart message"
572         if $DEBUG;
573       $data = [ map { $_ . "\n" }
574                     $conf->config('invoice_email_pdf_note')
575               ];
576
577     } else {
578
579       warn "$me not using 'invoice_email_pdf_note' in multipart message"
580         if $DEBUG;
581       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
582         $data = $args{'print_text'};
583       } else {
584         $data = [ $self->print_text('', $args{'template'}) ];
585       }
586
587     }
588
589     $alternative->attach(
590       'Type'        => 'text/plain',
591       #'Encoding'    => 'quoted-printable',
592       'Encoding'    => '7bit',
593       'Data'        => $data,
594       'Disposition' => 'inline',
595     );
596
597     $args{'from'} =~ /\@([\w\.\-]+)/;
598     my $from = $1 || 'example.com';
599     my $content_id = join('.', rand()*(2**32), $$, time). "\@$from";
600
601     my $path = "$FS::UID::conf_dir/conf.$FS::UID::datasrc";
602     my $file;
603     if ( defined($args{'template'}) && length($args{'template'})
604          && -e "$path/logo_". $args{'template'}. ".png"
605        )
606     {
607       $file = "$path/logo_". $args{'template'}. ".png";
608     } else {
609       $file = "$path/logo.png";
610     }
611
612     my $image = build MIME::Entity
613       'Type'       => 'image/png',
614       'Encoding'   => 'base64',
615       'Path'       => $file,
616       'Filename'   => 'logo.png',
617       'Content-ID' => "<$content_id>",
618     ;
619
620     $alternative->attach(
621       'Type'        => 'text/html',
622       'Encoding'    => 'quoted-printable',
623       'Data'        => [ '<html>',
624                          '  <head>',
625                          '    <title>',
626                          '      '. encode_entities($return{'subject'}), 
627                          '    </title>',
628                          '  </head>',
629                          '  <body bgcolor="#e8e8e8">',
630                          $self->print_html('', $args{'template'}, $content_id),
631                          '  </body>',
632                          '</html>',
633                        ],
634       'Disposition' => 'inline',
635       #'Filename'    => 'invoice.pdf',
636     );
637
638     if ( $conf->exists('invoice_email_pdf') ) {
639
640       #attaching pdf too:
641       # multipart/mixed
642       #   multipart/related
643       #     multipart/alternative
644       #       text/plain
645       #       text/html
646       #     image/png
647       #   application/pdf
648
649       my $related = build MIME::Entity 'Type'     => 'multipart/related',
650                                        'Encoding' => '7bit';
651
652       #false laziness w/Misc::send_email
653       $related->head->replace('Content-type',
654         $related->mime_type.
655         '; boundary="'. $related->head->multipart_boundary. '"'.
656         '; type=multipart/alternative'
657       );
658
659       $related->add_part($alternative);
660
661       $related->add_part($image);
662
663       my $pdf = build MIME::Entity $self->mimebuild_pdf('', $args{'template'});
664
665       $return{'mimeparts'} = [ $related, $pdf ];
666
667     } else {
668
669       #no other attachment:
670       # multipart/related
671       #   multipart/alternative
672       #     text/plain
673       #     text/html
674       #   image/png
675
676       $return{'content-type'} = 'multipart/related';
677       $return{'mimeparts'} = [ $alternative, $image ];
678       $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
679       #$return{'disposition'} = 'inline';
680
681     }
682   
683   } else {
684
685     if ( $conf->exists('invoice_email_pdf') ) {
686       warn "$me creating PDF attachment"
687         if $DEBUG;
688
689       #mime parts arguments a la MIME::Entity->build().
690       $return{'mimeparts'} = [
691         { $self->mimebuild_pdf('', $args{'template'}) }
692       ];
693     }
694   
695     if ( $conf->exists('invoice_email_pdf')
696          and scalar($conf->config('invoice_email_pdf_note')) ) {
697
698       warn "$me using 'invoice_email_pdf_note'"
699         if $DEBUG;
700       $return{'body'} = [ map { $_ . "\n" }
701                               $conf->config('invoice_email_pdf_note')
702                         ];
703
704     } else {
705
706       warn "$me not using 'invoice_email_pdf_note'"
707         if $DEBUG;
708       if ( ref($args{'print_text'}) eq 'ARRAY' ) {
709         $return{'body'} = $args{'print_text'};
710       } else {
711         $return{'body'} = [ $self->print_text('', $args{'template'}) ];
712       }
713
714     }
715
716   }
717
718   %return;
719
720 }
721
722 =item mimebuild_pdf
723
724 Returns a list suitable for passing to MIME::Entity->build(), representing
725 this invoice as PDF attachment.
726
727 =cut
728
729 sub mimebuild_pdf {
730   my $self = shift;
731   (
732     'Type'        => 'application/pdf',
733     'Encoding'    => 'base64',
734     'Data'        => [ $self->print_pdf(@_) ],
735     'Disposition' => 'attachment',
736     'Filename'    => 'invoice.pdf',
737   );
738 }
739
740 =item send [ TEMPLATENAME [ , AGENTNUM [ , INVOICE_FROM ] ] ]
741
742 Sends this invoice to the destinations configured for this customer: sends
743 email, prints and/or faxes.  See L<FS::cust_main_invoice>.
744
745 TEMPLATENAME, if specified, is the name of a suffix for alternate invoices.
746
747 AGENTNUM, if specified, means that this invoice will only be sent for customers
748 of the specified agent or agent(s).  AGENTNUM can be a scalar agentnum (for a
749 single agent) or an arrayref of agentnums.
750
751 INVOICE_FROM, if specified, overrides the default email invoice From: address.
752
753 AMOUNT, if specified, only sends the invoice if the total amount owed on this
754 invoice and all older invoices is greater than the specified amount.
755
756 =cut
757
758 sub queueable_send {
759   my %opt = @_;
760
761   my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
762     or die "invalid invoice number: " . $opt{invnum};
763
764   my @args = ( $opt{template}, $opt{agentnum} );
765   push @args, $opt{invoice_from}
766     if exists($opt{invoice_from}) && $opt{invoice_from};
767
768   my $error = $self->send( @args );
769   die $error if $error;
770
771 }
772
773 sub send {
774   my $self = shift;
775   my $template = scalar(@_) ? shift : '';
776   if ( scalar(@_) && $_[0]  ) {
777     my $agentnums = ref($_[0]) ? shift : [ shift ];
778     return 'N/A' unless grep { $_ == $self->cust_main->agentnum } @$agentnums;
779   }
780
781   my $invoice_from =
782     scalar(@_)
783       ? shift
784       : ( $self->_agent_invoice_from || $conf->config('invoice_from') );
785
786   my $balance_over = ( scalar(@_) && $_[0] !~ /^\s*$/ ) ? shift : 0;
787
788   return ''
789     unless $self->cust_main->total_owed_date($self->_date) > $balance_over;
790
791   my @invoicing_list = $self->cust_main->invoicing_list;
792
793   $self->email($template, $invoice_from)
794     if grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list or !@invoicing_list;
795
796   $self->print($template)
797     if grep { $_ eq 'POST' } @invoicing_list; #postal
798
799   $self->fax($template)
800     if grep { $_ eq 'FAX' } @invoicing_list; #fax
801
802   '';
803
804 }
805
806 =item email [ TEMPLATENAME  [ , INVOICE_FROM ] ] 
807
808 Emails this invoice.
809
810 TEMPLATENAME, if specified, is the name of a suffix for alternate invoices.
811
812 INVOICE_FROM, if specified, overrides the default email invoice From: address.
813
814 =cut
815
816 sub queueable_email {
817   my %opt = @_;
818
819   my $self = qsearchs('cust_bill', { 'invnum' => $opt{invnum} } )
820     or die "invalid invoice number: " . $opt{invnum};
821
822   my @args = ( $opt{template} );
823   push @args, $opt{invoice_from}
824     if exists($opt{invoice_from}) && $opt{invoice_from};
825
826   my $error = $self->email( @args );
827   die $error if $error;
828
829 }
830
831 sub email {
832   my $self = shift;
833   my $template = scalar(@_) ? shift : '';
834   my $invoice_from =
835     scalar(@_)
836       ? shift
837       : ( $self->_agent_invoice_from || $conf->config('invoice_from') );
838
839   my @invoicing_list = grep { $_ !~ /^(POST|FAX)$/ } 
840                             $self->cust_main->invoicing_list;
841
842   #better to notify this person than silence
843   @invoicing_list = ($invoice_from) unless @invoicing_list;
844
845   my $error = send_email(
846     $self->generate_email(
847       'from'       => $invoice_from,
848       'to'         => [ grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list ],
849       'template'   => $template,
850     )
851   );
852   die "can't email invoice: $error\n" if $error;
853   #die "$error\n" if $error;
854
855 }
856
857 =item lpr_data [ TEMPLATENAME ]
858
859 Returns the postscript or plaintext for this invoice as an arrayref.
860
861 TEMPLATENAME, if specified, is the name of a suffix for alternate invoices.
862
863 =cut
864
865 sub lpr_data {
866   my( $self, $template) = @_;
867   $conf->exists('invoice_latex')
868     ? [ $self->print_ps('', $template) ]
869     : [ $self->print_text('', $template) ];
870 }
871
872 =item print [ TEMPLATENAME ]
873
874 Prints this invoice.
875
876 TEMPLATENAME, if specified, is the name of a suffix for alternate invoices.
877
878 =cut
879
880 sub print {
881   my $self = shift;
882   my $template = scalar(@_) ? shift : '';
883
884   do_print $self->lpr_data($template);
885 }
886
887 =item fax [ TEMPLATENAME ] 
888
889 Faxes this invoice.
890
891 TEMPLATENAME, if specified, is the name of a suffix for alternate invoices.
892
893 =cut
894
895 sub fax {
896   my $self = shift;
897   my $template = scalar(@_) ? shift : '';
898
899   die 'FAX invoice destination not (yet?) supported with plain text invoices.'
900     unless $conf->exists('invoice_latex');
901
902   my $dialstring = $self->cust_main->getfield('fax');
903   #Check $dialstring?
904
905   my $error = send_fax( 'docdata'    => $self->lpr_data($template),
906                         'dialstring' => $dialstring,
907                       );
908   die $error if $error;
909
910 }
911
912 =item send_if_newest [ TEMPLATENAME [ , AGENTNUM [ , INVOICE_FROM ] ] ]
913
914 Like B<send>, but only sends the invoice if it is the newest open invoice for
915 this customer.
916
917 =cut
918
919 sub send_if_newest {
920   my $self = shift;
921
922   return ''
923     if scalar(
924                grep { $_->owed > 0 } 
925                     qsearch('cust_bill', {
926                       'custnum' => $self->custnum,
927                       #'_date'   => { op=>'>', value=>$self->_date },
928                       'invnum'  => { op=>'>', value=>$self->invnum },
929                     } )
930              );
931     
932   $self->send(@_);
933 }
934
935 =item send_csv OPTION => VALUE, ...
936
937 Sends invoice as a CSV data-file to a remote host with the specified protocol.
938
939 Options are:
940
941 protocol - currently only "ftp"
942 server
943 username
944 password
945 dir
946
947 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
948 and YYMMDDHHMMSS is a timestamp.
949
950 See L</print_csv> for a description of the output format.
951
952 =cut
953
954 sub send_csv {
955   my($self, %opt) = @_;
956
957   #create file(s)
958
959   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
960   mkdir $spooldir, 0700 unless -d $spooldir;
961
962   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
963   my $file = "$spooldir/$tracctnum.csv";
964   
965   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
966
967   open(CSV, ">$file") or die "can't open $file: $!";
968   print CSV $header;
969
970   print CSV $detail;
971
972   close CSV;
973
974   my $net;
975   if ( $opt{protocol} eq 'ftp' ) {
976     eval "use Net::FTP;";
977     die $@ if $@;
978     $net = Net::FTP->new($opt{server}) or die @$;
979   } else {
980     die "unknown protocol: $opt{protocol}";
981   }
982
983   $net->login( $opt{username}, $opt{password} )
984     or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
985
986   $net->binary or die "can't set binary mode";
987
988   $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
989
990   $net->put($file) or die "can't put $file: $!";
991
992   $net->quit;
993
994   unlink $file;
995
996 }
997
998 =item spool_csv
999
1000 Spools CSV invoice data.
1001
1002 Options are:
1003
1004 =over 4
1005
1006 =item format - 'default' or 'billco'
1007
1008 =item dest - if set (to POST, EMAIL or FAX), only sends spools invoices if the customer has the corresponding invoice destinations set (see L<FS::cust_main_invoice>).
1009
1010 =item agent_spools - if set to a true value, will spool to per-agent files rather than a single global file
1011
1012 =item balanceover - if set, only spools the invoice if the total amount owed on this invoice and all older invoices is greater than the specified amount.
1013
1014 =back
1015
1016 =cut
1017
1018 sub spool_csv {
1019   my($self, %opt) = @_;
1020
1021   my $cust_main = $self->cust_main;
1022
1023   if ( $opt{'dest'} ) {
1024     my %invoicing_list = map { /^(POST|FAX)$/ or 'EMAIL' =~ /^(.*)$/; $1 => 1 }
1025                              $cust_main->invoicing_list;
1026     return 'N/A' unless $invoicing_list{$opt{'dest'}}
1027                      || ! keys %invoicing_list;
1028   }
1029
1030   if ( $opt{'balanceover'} ) {
1031     return 'N/A'
1032       if $cust_main->total_owed_date($self->_date) < $opt{'balanceover'};
1033   }
1034
1035   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
1036   mkdir $spooldir, 0700 unless -d $spooldir;
1037
1038   my $tracctnum = $self->invnum. time2str('-%Y%m%d%H%M%S', time);
1039
1040   my $file =
1041     "$spooldir/".
1042     ( $opt{'agent_spools'} ? 'agentnum'.$cust_main->agentnum : 'spool' ).
1043     ( lc($opt{'format'}) eq 'billco' ? '-header' : '' ) .
1044     '.csv';
1045   
1046   my ( $header, $detail ) = $self->print_csv(%opt, 'tracctnum' => $tracctnum );
1047
1048   open(CSV, ">>$file") or die "can't open $file: $!";
1049   flock(CSV, LOCK_EX);
1050   seek(CSV, 0, 2);
1051
1052   print CSV $header;
1053
1054   if ( lc($opt{'format'}) eq 'billco' ) {
1055
1056     flock(CSV, LOCK_UN);
1057     close CSV;
1058
1059     $file =
1060       "$spooldir/".
1061       ( $opt{'agent_spools'} ? 'agentnum'.$cust_main->agentnum : 'spool' ).
1062       '-detail.csv';
1063
1064     open(CSV,">>$file") or die "can't open $file: $!";
1065     flock(CSV, LOCK_EX);
1066     seek(CSV, 0, 2);
1067   }
1068
1069   print CSV $detail;
1070
1071   flock(CSV, LOCK_UN);
1072   close CSV;
1073
1074   return '';
1075
1076 }
1077
1078 =item print_csv OPTION => VALUE, ...
1079
1080 Returns CSV data for this invoice.
1081
1082 Options are:
1083
1084 format - 'default' or 'billco'
1085
1086 Returns a list consisting of two scalars.  The first is a single line of CSV
1087 header information for this invoice.  The second is one or more lines of CSV
1088 detail information for this invoice.
1089
1090 If I<format> is not specified or "default", the fields of the CSV file are as
1091 follows:
1092
1093 record_type, invnum, custnum, _date, charged, first, last, company, address1, address2, city, state, zip, country, pkg, setup, recur, sdate, edate
1094
1095 =over 4
1096
1097 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
1098
1099 B<record_type> is C<cust_bill> for the initial header line only.  The
1100 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
1101 fields are filled in.
1102
1103 B<record_type> is C<cust_bill_pkg> for detail lines.  Only the first two fields
1104 (B<record_type> and B<invnum>) and the last five fields (B<pkg> through B<edate>)
1105 are filled in.
1106
1107 =item invnum - invoice number
1108
1109 =item custnum - customer number
1110
1111 =item _date - invoice date
1112
1113 =item charged - total invoice amount
1114
1115 =item first - customer first name
1116
1117 =item last - customer first name
1118
1119 =item company - company name
1120
1121 =item address1 - address line 1
1122
1123 =item address2 - address line 1
1124
1125 =item city
1126
1127 =item state
1128
1129 =item zip
1130
1131 =item country
1132
1133 =item pkg - line item description
1134
1135 =item setup - line item setup fee (one or both of B<setup> and B<recur> will be defined)
1136
1137 =item recur - line item recurring fee (one or both of B<setup> and B<recur> will be defined)
1138
1139 =item sdate - start date for recurring fee
1140
1141 =item edate - end date for recurring fee
1142
1143 =back
1144
1145 If I<format> is "billco", the fields of the header CSV file are as follows:
1146
1147   +-------------------------------------------------------------------+
1148   |                        FORMAT HEADER FILE                         |
1149   |-------------------------------------------------------------------|
1150   | Field | Description                   | Name       | Type | Width |
1151   | 1     | N/A-Leave Empty               | RC         | CHAR |     2 |
1152   | 2     | N/A-Leave Empty               | CUSTID     | CHAR |    15 |
1153   | 3     | Transaction Account No        | TRACCTNUM  | CHAR |    15 |
1154   | 4     | Transaction Invoice No        | TRINVOICE  | CHAR |    15 |
1155   | 5     | Transaction Zip Code          | TRZIP      | CHAR |     5 |
1156   | 6     | Transaction Company Bill To   | TRCOMPANY  | CHAR |    30 |
1157   | 7     | Transaction Contact Bill To   | TRNAME     | CHAR |    30 |
1158   | 8     | Additional Address Unit Info  | TRADDR1    | CHAR |    30 |
1159   | 9     | Bill To Street Address        | TRADDR2    | CHAR |    30 |
1160   | 10    | Ancillary Billing Information | TRADDR3    | CHAR |    30 |
1161   | 11    | Transaction City Bill To      | TRCITY     | CHAR |    20 |
1162   | 12    | Transaction State Bill To     | TRSTATE    | CHAR |     2 |
1163   | 13    | Bill Cycle Close Date         | CLOSEDATE  | CHAR |    10 |
1164   | 14    | Bill Due Date                 | DUEDATE    | CHAR |    10 |
1165   | 15    | Previous Balance              | BALFWD     | NUM* |     9 |
1166   | 16    | Pmt/CR Applied                | CREDAPPLY  | NUM* |     9 |
1167   | 17    | Total Current Charges         | CURRENTCHG | NUM* |     9 |
1168   | 18    | Total Amt Due                 | TOTALDUE   | NUM* |     9 |
1169   | 19    | Total Amt Due                 | AMTDUE     | NUM* |     9 |
1170   | 20    | 30 Day Aging                  | AMT30      | NUM* |     9 |
1171   | 21    | 60 Day Aging                  | AMT60      | NUM* |     9 |
1172   | 22    | 90 Day Aging                  | AMT90      | NUM* |     9 |
1173   | 23    | Y/N                           | AGESWITCH  | CHAR |     1 |
1174   | 24    | Remittance automation         | SCANLINE   | CHAR |   100 |
1175   | 25    | Total Taxes & Fees            | TAXTOT     | NUM* |     9 |
1176   | 26    | Customer Reference Number     | CUSTREF    | CHAR |    15 |
1177   | 27    | Federal Tax***                | FEDTAX     | NUM* |     9 |
1178   | 28    | State Tax***                  | STATETAX   | NUM* |     9 |
1179   | 29    | Other Taxes & Fees***         | OTHERTAX   | NUM* |     9 |
1180   +-------+-------------------------------+------------+------+-------+
1181
1182 If I<format> is "billco", the fields of the detail CSV file are as follows:
1183
1184                                   FORMAT FOR DETAIL FILE
1185         |                            |           |      |
1186   Field | Description                | Name      | Type | Width
1187   1     | N/A-Leave Empty            | RC        | CHAR |     2
1188   2     | N/A-Leave Empty            | CUSTID    | CHAR |    15
1189   3     | Account Number             | TRACCTNUM | CHAR |    15
1190   4     | Invoice Number             | TRINVOICE | CHAR |    15
1191   5     | Line Sequence (sort order) | LINESEQ   | NUM  |     6
1192   6     | Transaction Detail         | DETAILS   | CHAR |   100
1193   7     | Amount                     | AMT       | NUM* |     9
1194   8     | Line Format Control**      | LNCTRL    | CHAR |     2
1195   9     | Grouping Code              | GROUP     | CHAR |     2
1196   10    | User Defined               | ACCT CODE | CHAR |    15
1197
1198 =cut
1199
1200 sub print_csv {
1201   my($self, %opt) = @_;
1202   
1203   eval "use Text::CSV_XS";
1204   die $@ if $@;
1205
1206   my $cust_main = $self->cust_main;
1207
1208   my $csv = Text::CSV_XS->new({'always_quote'=>1});
1209
1210   if ( lc($opt{'format'}) eq 'billco' ) {
1211
1212     my $taxtotal = 0;
1213     $taxtotal += $_->{'amount'} foreach $self->_items_tax;
1214
1215     my $duedate = '';
1216     if (    $conf->exists('invoice_default_terms') 
1217          && $conf->config('invoice_default_terms')=~ /^\s*Net\s*(\d+)\s*$/ ) {
1218       $duedate = time2str("%m/%d/%Y", $self->_date + ($1*86400) );
1219     }
1220
1221     my( $previous_balance, @unused ) = $self->previous; #previous balance
1222
1223     my $pmt_cr_applied = 0;
1224     $pmt_cr_applied += $_->{'amount'}
1225       foreach ( $self->_items_payments, $self->_items_credits ) ;
1226
1227     my $totaldue = sprintf('%.2f', $self->owed + $previous_balance);
1228
1229     $csv->combine(
1230       '',                         #  1 | N/A-Leave Empty               CHAR   2
1231       '',                         #  2 | N/A-Leave Empty               CHAR  15
1232       $opt{'tracctnum'},          #  3 | Transaction Account No        CHAR  15
1233       $self->invnum,              #  4 | Transaction Invoice No        CHAR  15
1234       $cust_main->zip,            #  5 | Transaction Zip Code          CHAR   5
1235       $cust_main->company,        #  6 | Transaction Company Bill To   CHAR  30
1236       #$cust_main->payname,        #  7 | Transaction Contact Bill To   CHAR  30
1237       $cust_main->contact,        #  7 | Transaction Contact Bill To   CHAR  30
1238       $cust_main->address2,       #  8 | Additional Address Unit Info  CHAR  30
1239       $cust_main->address1,       #  9 | Bill To Street Address        CHAR  30
1240       '',                         # 10 | Ancillary Billing Information CHAR  30
1241       $cust_main->city,           # 11 | Transaction City Bill To      CHAR  20
1242       $cust_main->state,          # 12 | Transaction State Bill To     CHAR   2
1243
1244       # XXX ?
1245       time2str("%m/%d/%Y", $self->_date), # 13 | Bill Cycle Close Date CHAR  10
1246
1247       # XXX ?
1248       $duedate,                   # 14 | Bill Due Date                 CHAR  10
1249
1250       $previous_balance,          # 15 | Previous Balance              NUM*   9
1251       $pmt_cr_applied,            # 16 | Pmt/CR Applied                NUM*   9
1252       sprintf("%.2f", $self->charged), # 17 | Total Current Charges    NUM*   9
1253       $totaldue,                  # 18 | Total Amt Due                 NUM*   9
1254       $totaldue,                  # 19 | Total Amt Due                 NUM*   9
1255       '',                         # 20 | 30 Day Aging                  NUM*   9
1256       '',                         # 21 | 60 Day Aging                  NUM*   9
1257       '',                         # 22 | 90 Day Aging                  NUM*   9
1258       'N',                        # 23 | Y/N                           CHAR   1
1259       '',                         # 24 | Remittance automation         CHAR 100
1260       $taxtotal,                  # 25 | Total Taxes & Fees            NUM*   9
1261       $self->custnum,             # 26 | Customer Reference Number     CHAR  15
1262       '0',                        # 27 | Federal Tax***                NUM*   9
1263       sprintf("%.2f", $taxtotal), # 28 | State Tax***                  NUM*   9
1264       '0',                        # 29 | Other Taxes & Fees***         NUM*   9
1265     );
1266
1267   } else {
1268   
1269     $csv->combine(
1270       'cust_bill',
1271       $self->invnum,
1272       $self->custnum,
1273       time2str("%x", $self->_date),
1274       sprintf("%.2f", $self->charged),
1275       ( map { $cust_main->getfield($_) }
1276           qw( first last company address1 address2 city state zip country ) ),
1277       map { '' } (1..5),
1278     ) or die "can't create csv";
1279   }
1280
1281   my $header = $csv->string. "\n";
1282
1283   my $detail = '';
1284   if ( lc($opt{'format'}) eq 'billco' ) {
1285
1286     my $lineseq = 0;
1287     foreach my $item ( $self->_items_pkg ) {
1288
1289       $csv->combine(
1290         '',                     #  1 | N/A-Leave Empty            CHAR   2
1291         '',                     #  2 | N/A-Leave Empty            CHAR  15
1292         $opt{'tracctnum'},      #  3 | Account Number             CHAR  15
1293         $self->invnum,          #  4 | Invoice Number             CHAR  15
1294         $lineseq++,             #  5 | Line Sequence (sort order) NUM    6
1295         $item->{'description'}, #  6 | Transaction Detail         CHAR 100
1296         $item->{'amount'},      #  7 | Amount                     NUM*   9
1297         '',                     #  8 | Line Format Control**      CHAR   2
1298         '',                     #  9 | Grouping Code              CHAR   2
1299         '',                     # 10 | User Defined               CHAR  15
1300       );
1301
1302       $detail .= $csv->string. "\n";
1303
1304     }
1305
1306   } else {
1307
1308     foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
1309
1310       my($pkg, $setup, $recur, $sdate, $edate);
1311       if ( $cust_bill_pkg->pkgnum ) {
1312       
1313         ($pkg, $setup, $recur, $sdate, $edate) = (
1314           $cust_bill_pkg->cust_pkg->part_pkg->pkg,
1315           ( $cust_bill_pkg->setup != 0
1316             ? sprintf("%.2f", $cust_bill_pkg->setup )
1317             : '' ),
1318           ( $cust_bill_pkg->recur != 0
1319             ? sprintf("%.2f", $cust_bill_pkg->recur )
1320             : '' ),
1321           ( $cust_bill_pkg->sdate 
1322             ? time2str("%x", $cust_bill_pkg->sdate)
1323             : '' ),
1324           ($cust_bill_pkg->edate 
1325             ?time2str("%x", $cust_bill_pkg->edate)
1326             : '' ),
1327         );
1328   
1329       } else { #pkgnum tax
1330         next unless $cust_bill_pkg->setup != 0;
1331         my $itemdesc = defined $cust_bill_pkg->dbdef_table->column('itemdesc')
1332                          ? ( $cust_bill_pkg->itemdesc || 'Tax' )
1333                          : 'Tax';
1334         ($pkg, $setup, $recur, $sdate, $edate) =
1335           ( $itemdesc, sprintf("%10.2f",$cust_bill_pkg->setup), '', '', '' );
1336       }
1337   
1338       $csv->combine(
1339         'cust_bill_pkg',
1340         $self->invnum,
1341         ( map { '' } (1..11) ),
1342         ($pkg, $setup, $recur, $sdate, $edate)
1343       ) or die "can't create csv";
1344
1345       $detail .= $csv->string. "\n";
1346
1347     }
1348
1349   }
1350
1351   ( $header, $detail );
1352
1353 }
1354
1355 =item comp
1356
1357 Pays this invoice with a compliemntary payment.  If there is an error,
1358 returns the error, otherwise returns false.
1359
1360 =cut
1361
1362 sub comp {
1363   my $self = shift;
1364   my $cust_pay = new FS::cust_pay ( {
1365     'invnum'   => $self->invnum,
1366     'paid'     => $self->owed,
1367     '_date'    => '',
1368     'payby'    => 'COMP',
1369     'payinfo'  => $self->cust_main->payinfo,
1370     'paybatch' => '',
1371   } );
1372   $cust_pay->insert;
1373 }
1374
1375 =item realtime_card
1376
1377 Attempts to pay this invoice with a credit card payment via a
1378 Business::OnlinePayment realtime gateway.  See
1379 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1380 for supported processors.
1381
1382 =cut
1383
1384 sub realtime_card {
1385   my $self = shift;
1386   $self->realtime_bop( 'CC', @_ );
1387 }
1388
1389 =item realtime_ach
1390
1391 Attempts to pay this invoice with an electronic check (ACH) payment via a
1392 Business::OnlinePayment realtime gateway.  See
1393 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1394 for supported processors.
1395
1396 =cut
1397
1398 sub realtime_ach {
1399   my $self = shift;
1400   $self->realtime_bop( 'ECHECK', @_ );
1401 }
1402
1403 =item realtime_lec
1404
1405 Attempts to pay this invoice with phone bill (LEC) payment via a
1406 Business::OnlinePayment realtime gateway.  See
1407 http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
1408 for supported processors.
1409
1410 =cut
1411
1412 sub realtime_lec {
1413   my $self = shift;
1414   $self->realtime_bop( 'LEC', @_ );
1415 }
1416
1417 sub realtime_bop {
1418   my( $self, $method ) = @_;
1419
1420   my $cust_main = $self->cust_main;
1421   my $balance = $cust_main->balance;
1422   my $amount = ( $balance < $self->owed ) ? $balance : $self->owed;
1423   $amount = sprintf("%.2f", $amount);
1424   return "not run (balance $balance)" unless $amount > 0;
1425
1426   my $description = 'Internet Services';
1427   if ( $conf->exists('business-onlinepayment-description') ) {
1428     my $dtempl = $conf->config('business-onlinepayment-description');
1429
1430     my $agent_obj = $cust_main->agent
1431       or die "can't retreive agent for $cust_main (agentnum ".
1432              $cust_main->agentnum. ")";
1433     my $agent = $agent_obj->agent;
1434     my $pkgs = join(', ',
1435       map { $_->cust_pkg->part_pkg->pkg }
1436         grep { $_->pkgnum } $self->cust_bill_pkg
1437     );
1438     $description = eval qq("$dtempl");
1439   }
1440
1441   $cust_main->realtime_bop($method, $amount,
1442     'description' => $description,
1443     'invnum'      => $self->invnum,
1444   );
1445
1446 }
1447
1448 =item batch_card OPTION => VALUE...
1449
1450 Adds a payment for this invoice to the pending credit card batch (see
1451 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
1452 runs the payment using a realtime gateway.
1453
1454 =cut
1455
1456 sub batch_card {
1457   my ($self, %options) = @_;
1458   my $cust_main = $self->cust_main;
1459
1460   $options{invnum} = $self->invnum;
1461   
1462   $cust_main->batch_card(%options);
1463 }
1464
1465 sub _agent_template {
1466   my $self = shift;
1467   $self->cust_main->agent_template;
1468 }
1469
1470 sub _agent_invoice_from {
1471   my $self = shift;
1472   $self->cust_main->agent_invoice_from;
1473 }
1474
1475 =item print_text [ TIME [ , TEMPLATE ] ]
1476
1477 Returns an text invoice, as a list of lines.
1478
1479 TIME an optional value used to control the printing of overdue messages.  The
1480 default is now.  It isn't the date of the invoice; that's the `_date' field.
1481 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1482 L<Time::Local> and L<Date::Parse> for conversion functions.
1483
1484 =cut
1485
1486 #still some false laziness w/_items stuff (and send_csv)
1487 sub print_text {
1488
1489   my( $self, $today, $template ) = @_;
1490   $today ||= time;
1491
1492 #  my $invnum = $self->invnum;
1493   my $cust_main = $self->cust_main;
1494   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
1495     unless $cust_main->payname && $cust_main->payby !~ /^(CHEK|DCHK)$/;
1496
1497   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
1498 #  my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
1499   #my $balance_due = $self->owed + $pr_total - $cr_total;
1500   my $balance_due = $self->owed + $pr_total;
1501
1502   #my @collect = ();
1503   #my($description,$amount);
1504   @buf = ();
1505
1506   #previous balance
1507   unless ($conf->exists('disable_previous_balance')) {
1508     foreach ( @pr_cust_bill ) {
1509       push @buf, [
1510         "Previous Balance, Invoice #". $_->invnum. 
1511                    " (". time2str("%x",$_->_date). ")",
1512         $money_char. sprintf("%10.2f",$_->owed)
1513       ];
1514     }
1515     if (@pr_cust_bill) {
1516       push @buf,['','-----------'];
1517       push @buf,[ 'Total Previous Balance',
1518                   $money_char. sprintf("%10.2f",$pr_total ) ];
1519       push @buf,['',''];
1520     }
1521   }
1522
1523   #new charges
1524   foreach my $cust_bill_pkg (
1525     ( grep {   $_->pkgnum } $self->cust_bill_pkg ),  #packages first
1526     ( grep { ! $_->pkgnum } $self->cust_bill_pkg ),  #then taxes
1527   ) {
1528
1529     my $desc = $cust_bill_pkg->desc;
1530
1531     if ( $cust_bill_pkg->pkgnum > 0 ) {
1532
1533       if ( $cust_bill_pkg->setup != 0 ) {
1534         my $description = $desc;
1535         $description .= ' Setup' if $cust_bill_pkg->recur != 0;
1536         push @buf, [ $description,
1537                      $money_char. sprintf("%10.2f", $cust_bill_pkg->setup) ];
1538         push @buf,
1539           map { [ "  ". $_->[0]. ": ". $_->[1], '' ] }
1540               $cust_bill_pkg->cust_pkg->h_labels($self->_date);
1541       }
1542
1543       if ( $cust_bill_pkg->recur != 0 ) {
1544         push @buf, [
1545           $desc .
1546             ( $conf->exists('disable_line_item_date_ranges')
1547               ? ''
1548               : " (" . time2str("%x", $cust_bill_pkg->sdate) . " - " .
1549                        time2str("%x", $cust_bill_pkg->edate) . ")"
1550             ),
1551           $money_char. sprintf("%10.2f", $cust_bill_pkg->recur)
1552         ];
1553         push @buf,
1554           map { [ "  ". $_->[0]. ": ". $_->[1], '' ] }
1555               $cust_bill_pkg->cust_pkg->h_labels( $cust_bill_pkg->edate,
1556                                                   $cust_bill_pkg->sdate );
1557       }
1558
1559       push @buf, map { [ "  $_", '' ] } $cust_bill_pkg->details;
1560
1561     } else { #pkgnum tax or one-shot line item
1562
1563       if ( $cust_bill_pkg->setup != 0 ) {
1564         push @buf, [ $desc,
1565                      $money_char. sprintf("%10.2f", $cust_bill_pkg->setup) ];
1566       }
1567       if ( $cust_bill_pkg->recur != 0 ) {
1568         push @buf, [ "$desc (". time2str("%x", $cust_bill_pkg->sdate). " - "
1569                               . time2str("%x", $cust_bill_pkg->edate). ")",
1570                      $money_char. sprintf("%10.2f", $cust_bill_pkg->recur)
1571                    ];
1572       }
1573
1574     }
1575
1576   }
1577
1578   push @buf,['','-----------'];
1579   push @buf,[ ( $conf->exists('disable_previous_balance')
1580                 ? 'Total Charges'
1581                 : 'Total New Charges'),
1582              $money_char. sprintf("%10.2f",$self->charged) ];
1583   push @buf,['',''];
1584
1585   unless ($conf->exists('disable_previous_balance')) {
1586     push @buf,['','-----------'];
1587     push @buf,['Total Charges',
1588                $money_char. sprintf("%10.2f",$self->charged + $pr_total) ];
1589     push @buf,['',''];
1590
1591     #credits
1592     foreach ( $self->cust_credited ) {
1593
1594       #something more elaborate if $_->amount ne $_->cust_credit->credited ?
1595
1596       my $reason = substr($_->cust_credit->reason,0,32);
1597       $reason .= '...' if length($reason) < length($_->cust_credit->reason);
1598       $reason = " ($reason) " if $reason;
1599       push @buf,[
1600         "Credit #". $_->crednum. " (". time2str("%x",$_->cust_credit->_date) .")".
1601           $reason,
1602         $money_char. sprintf("%10.2f",$_->amount)
1603       ];
1604     }
1605     #foreach ( @cr_cust_credit ) {
1606     #  push @buf,[
1607     #    "Credit #". $_->crednum. " (" . time2str("%x",$_->_date) .")",
1608     #    $money_char. sprintf("%10.2f",$_->credited)
1609     #  ];
1610     #}
1611
1612     #get & print payments
1613     foreach ( $self->cust_bill_pay ) {
1614
1615       #something more elaborate if $_->amount ne ->cust_pay->paid ?
1616
1617       push @buf,[
1618         "Payment received ". time2str("%x",$_->cust_pay->_date ),
1619         $money_char. sprintf("%10.2f",$_->amount )
1620       ];
1621     }
1622
1623     #balance due
1624     my $balance_due_msg = $self->balance_due_msg;
1625
1626     push @buf,['','-----------'];
1627     push @buf,[$balance_due_msg, $money_char. 
1628       sprintf("%10.2f", $balance_due ) ];
1629   }
1630
1631   #create the template
1632   $template ||= $self->_agent_template;
1633   my $templatefile = 'invoice_template';
1634   $templatefile .= "_$template" if length($template);
1635   my @invoice_template = $conf->config($templatefile)
1636     or die "cannot load config file $templatefile";
1637   $invoice_lines = 0;
1638   my $wasfunc = 0;
1639   foreach ( grep /invoice_lines\(\d*\)/, @invoice_template ) { #kludgy
1640     /invoice_lines\((\d*)\)/;
1641     $invoice_lines += $1 || scalar(@buf);
1642     $wasfunc=1;
1643   }
1644   die "no invoice_lines() functions in template?" unless $wasfunc;
1645   my $invoice_template = new Text::Template (
1646     TYPE   => 'ARRAY',
1647     SOURCE => [ map "$_\n", @invoice_template ],
1648   ) or die "can't create new Text::Template object: $Text::Template::ERROR";
1649   $invoice_template->compile()
1650     or die "can't compile template: $Text::Template::ERROR";
1651
1652   #setup template variables
1653   package FS::cust_bill::_template; #!
1654   use vars qw( $custnum $invnum $date $agent @address $overdue
1655                $page $total_pages @buf );
1656
1657   $custnum = $self->custnum;
1658   $invnum = $self->invnum;
1659   $date = $self->_date;
1660   $agent = $self->cust_main->agent->agent;
1661   $page = 1;
1662
1663   if ( $FS::cust_bill::invoice_lines ) {
1664     $total_pages =
1665       int( scalar(@FS::cust_bill::buf) / $FS::cust_bill::invoice_lines );
1666     $total_pages++
1667       if scalar(@FS::cust_bill::buf) % $FS::cust_bill::invoice_lines;
1668   } else {
1669     $total_pages = 1;
1670   }
1671
1672   #format address (variable for the template)
1673   my $l = 0;
1674   @address = ( '', '', '', '', '', '' );
1675   package FS::cust_bill; #!
1676   $FS::cust_bill::_template::address[$l++] =
1677     $cust_main->payname.
1678       ( ( $cust_main->payby eq 'BILL' ) && $cust_main->payinfo
1679         ? " (P.O. #". $cust_main->payinfo. ")"
1680         : ''
1681       )
1682   ;
1683   $FS::cust_bill::_template::address[$l++] = $cust_main->company
1684     if $cust_main->company;
1685   $FS::cust_bill::_template::address[$l++] = $cust_main->address1;
1686   $FS::cust_bill::_template::address[$l++] = $cust_main->address2
1687     if $cust_main->address2;
1688   $FS::cust_bill::_template::address[$l++] =
1689     $cust_main->city. ", ". $cust_main->state. "  ".  $cust_main->zip;
1690
1691   my $countrydefault = $conf->config('countrydefault') || 'US';
1692   $FS::cust_bill::_template::address[$l++] = code2country($cust_main->country)
1693     unless $cust_main->country eq $countrydefault;
1694
1695         #  #overdue? (variable for the template)
1696         #  $FS::cust_bill::_template::overdue = ( 
1697         #    $balance_due > 0
1698         #    && $today > $self->_date 
1699         ##    && $self->printed > 1
1700         #    && $self->printed > 0
1701         #  );
1702
1703   #and subroutine for the template
1704   sub FS::cust_bill::_template::invoice_lines {
1705     my $lines = shift || scalar(@buf);
1706     map { 
1707       scalar(@buf) ? shift @buf : [ '', '' ];
1708     }
1709     ( 1 .. $lines );
1710   }
1711
1712   #and fill it in
1713   $FS::cust_bill::_template::page = 1;
1714   my $lines;
1715   my @collect;
1716   while (@buf) {
1717     push @collect, split("\n",
1718       $invoice_template->fill_in( PACKAGE => 'FS::cust_bill::_template' )
1719     );
1720     $FS::cust_bill::_template::page++;
1721   }
1722
1723   map "$_\n", @collect;
1724
1725 }
1726
1727 =item print_latex [ TIME [ , TEMPLATE ] ]
1728
1729 Internal method - returns a filename of a filled-in LaTeX template for this
1730 invoice (Note: add ".tex" to get the actual filename).
1731
1732 See print_ps and print_pdf for methods that return PostScript and PDF output.
1733
1734 TIME an optional value used to control the printing of overdue messages.  The
1735 default is now.  It isn't the date of the invoice; that's the `_date' field.
1736 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
1737 L<Time::Local> and L<Date::Parse> for conversion functions.
1738
1739 =cut
1740
1741 #still some false laziness w/print_text and print_html (and send_csv) (mostly print_text should use _items stuff though)
1742 sub print_latex {
1743
1744   my( $self, $today, $template ) = @_;
1745   $today ||= time;
1746   warn "FS::cust_bill::print_latex called on $self with suffix $template\n"
1747     if $DEBUG;
1748
1749   my $cust_main = $self->cust_main;
1750   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
1751     unless $cust_main->payname && $cust_main->payby !~ /^(CHEK|DCHK)$/;
1752
1753   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
1754 #  my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
1755   #my $balance_due = $self->owed + $pr_total - $cr_total;
1756   my $balance_due = $self->owed + $pr_total;
1757
1758   #create the template
1759   $template ||= $self->_agent_template;
1760   my $templatefile = 'invoice_latex';
1761   my $suffix = length($template) ? "_$template" : '';
1762   $templatefile .= $suffix;
1763   my @invoice_template = map "$_\n", $conf->config($templatefile)
1764     or die "cannot load config file $templatefile";
1765
1766   my($format, $text_template);
1767   if ( grep { /^%%Detail/ } @invoice_template ) {
1768     #change this to a die when the old code is removed
1769     warn "old-style invoice template $templatefile; ".
1770          "patch with conf/invoice_latex.diff or use new conf/invoice_latex*\n";
1771     $format = 'old';
1772   } else {
1773     $format = 'Text::Template';
1774     $text_template = new Text::Template(
1775       TYPE => 'ARRAY',
1776       SOURCE => \@invoice_template,
1777       DELIMITERS => [ '[@--', '--@]' ],
1778     );
1779
1780     $text_template->compile()
1781       or die 'While compiling ' . $templatefile . ': ' . $Text::Template::ERROR;
1782   }
1783
1784   my $returnaddress;
1785   if ( length($conf->config_orbase('invoice_latexreturnaddress', $template)) ) {
1786     $returnaddress = join("\n",
1787       $conf->config_orbase('invoice_latexreturnaddress', $template)
1788     );
1789   } else {
1790     $returnaddress = '~';
1791   }
1792
1793   my %invoice_data = (
1794     'custnum'      => $self->custnum,
1795     'invnum'       => $self->invnum,
1796     'date'         => time2str('%b %o, %Y', $self->_date),
1797     'today'        => time2str('%b %o, %Y', $today),
1798     'agent'        => _latex_escape($cust_main->agent->agent),
1799     'agent_custid' => _latex_escape($cust_main->agent_custid),
1800     'payname'      => _latex_escape($cust_main->payname),
1801     'company'      => _latex_escape($cust_main->company),
1802     'address1'     => _latex_escape($cust_main->address1),
1803     'address2'     => _latex_escape($cust_main->address2),
1804     'city'         => _latex_escape($cust_main->city),
1805     'state'        => _latex_escape($cust_main->state),
1806     #'quantity'     => 1,
1807     'zip'          => _latex_escape($cust_main->zip),
1808     'footer'       => join("\n", $conf->config_orbase('invoice_latexfooter', $template) ),
1809     'smallfooter'  => join("\n", $conf->config_orbase('invoice_latexsmallfooter', $template) ),
1810     'returnaddress' => $returnaddress,
1811     'quantity'     => 1,
1812     'terms'        => $conf->config('invoice_default_terms') || 'Payable upon receipt',
1813     #'notes'        => join("\n", $conf->config('invoice_latexnotes') ),
1814     'conf_dir'     => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
1815     'balance'      => $balance_due,
1816     'ship_enable'  => $conf->exists('invoice-ship_address'),
1817     'unitprices'   => $conf->exists('invoice-unitprice'),
1818   );
1819
1820   my $prefix = $cust_main->has_ship_address ? 'ship_' : '';
1821   foreach ( qw( contact company address1 address2 city state zip country fax) ){
1822     my $method = $prefix.$_;
1823     $invoice_data{"ship_$_"} = _latex_escape($cust_main->$method);
1824   }
1825
1826   my $countrydefault = $conf->config('countrydefault') || 'US';
1827   if ( $cust_main->country eq $countrydefault ) {
1828     $invoice_data{'country'} = '';
1829   } else {
1830     $invoice_data{'country'} = _latex_escape(code2country($cust_main->country));
1831   }
1832
1833   $invoice_data{'notes'} =
1834     join("\n",
1835 #  #do variable substitutions in notes
1836 #      map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1837         $conf->config_orbase('invoice_latexnotes', $template)
1838     );
1839   warn "invoice notes: ". $invoice_data{'notes'}. "\n"
1840     if $DEBUG;
1841
1842   #do variable substitution in coupon
1843   foreach my $include (qw( coupon )) {
1844
1845     my @inc_src = $conf->config_orbase("invoice_latex$include", $template);
1846
1847     my $inc_tt = new Text::Template (
1848       TYPE       => 'ARRAY',
1849       SOURCE     => [ map "$_\n", @inc_src ],
1850       DELIMITERS => [ '[@--', '--@]' ],
1851     ) or die "Can't create new Text::Template object: $Text::Template::ERROR";
1852
1853     unless ( $inc_tt->compile() ) {
1854       my $error = "Can't compile $include template: $Text::Template::ERROR\n";
1855       warn $error. "Template:\n". join('', map "$_\n", @inc_src);
1856       die $error;
1857     }
1858
1859     $invoice_data{$include} = $inc_tt->fill_in( HASH => \%invoice_data );
1860
1861     $invoice_data{$include} =~ s/\n+$//
1862   }
1863
1864   $invoice_data{'footer'} =~ s/\n+$//;
1865   $invoice_data{'smallfooter'} =~ s/\n+$//;
1866   $invoice_data{'notes'} =~ s/\n+$//;
1867
1868   $invoice_data{'po_line'} =
1869     (  $cust_main->payby eq 'BILL' && $cust_main->payinfo )
1870       ? _latex_escape("Purchase Order #". $cust_main->payinfo)
1871       : '~';
1872
1873   my @filled_in = ();
1874   if ( $format eq 'old' ) {
1875   
1876     my @line_item = ();
1877     my @total_item = ();
1878     while ( @invoice_template ) {
1879       my $line = shift @invoice_template;
1880   
1881       if ( $line =~ /^%%Detail\s*$/ ) {
1882   
1883         while ( ( my $line_item_line = shift @invoice_template )
1884                 !~ /^%%EndDetail\s*$/                            ) {
1885           push @line_item, $line_item_line;
1886         }
1887         foreach my $line_item ( $self->_items ) {
1888         #foreach my $line_item ( $self->_items_pkg ) {
1889           $invoice_data{'ref'} = $line_item->{'pkgnum'};
1890           $invoice_data{'description'} =
1891             _latex_escape($line_item->{'description'});
1892           if ( exists $line_item->{'ext_description'} ) {
1893             $invoice_data{'description'} .=
1894               "\\tabularnewline\n~~".
1895               join( "\\tabularnewline\n~~",
1896                     map _latex_escape($_), @{$line_item->{'ext_description'}}
1897                   );
1898           }
1899           $invoice_data{'amount'}       = $line_item->{'amount'};
1900           $invoice_data{'unit_amount'}  = $line_item->{'unit_amount'};
1901           $invoice_data{'quantity'}     = $line_item->{'quantity'};
1902           $invoice_data{'product_code'} = $line_item->{'pkgpart'} || 'N/A';
1903           push @filled_in,
1904             map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b } @line_item;
1905         }
1906   
1907       } elsif ( $line =~ /^%%TotalDetails\s*$/ ) {
1908   
1909         while ( ( my $total_item_line = shift @invoice_template )
1910                 !~ /^%%EndTotalDetails\s*$/                      ) {
1911           push @total_item, $total_item_line;
1912         }
1913   
1914         my @total_fill = ();
1915   
1916         my $taxtotal = 0;
1917         foreach my $tax ( $self->_items_tax ) {
1918           $invoice_data{'total_item'} = _latex_escape($tax->{'description'});
1919           $taxtotal += $tax->{'amount'};
1920           $invoice_data{'total_amount'} = '\dollar '. $tax->{'amount'};
1921           push @total_fill,
1922             map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1923                 @total_item;
1924         }
1925
1926         if ( $taxtotal ) {
1927           $invoice_data{'total_item'} = 'Sub-total';
1928           $invoice_data{'total_amount'} =
1929             '\dollar '. sprintf('%.2f', $self->charged - $taxtotal );
1930           unshift @total_fill,
1931             map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1932                 @total_item;
1933         }
1934   
1935         $invoice_data{'total_item'} = '\textbf{Total}';
1936         $invoice_data{'total_amount'} =
1937           '\textbf{\dollar '. sprintf('%.2f', $self->charged + $pr_total ). '}';
1938         push @total_fill,
1939           map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1940               @total_item;
1941   
1942         #foreach my $thing ( sort { $a->_date <=> $b->_date } $self->_items_credits, $self->_items_payments
1943   
1944         # credits
1945         foreach my $credit ( $self->_items_credits ) {
1946           $invoice_data{'total_item'} = _latex_escape($credit->{'description'});
1947           #$credittotal
1948           $invoice_data{'total_amount'} = '-\dollar '. $credit->{'amount'};
1949           push @total_fill, 
1950             map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1951                 @total_item;
1952         }
1953   
1954         # payments
1955         foreach my $payment ( $self->_items_payments ) {
1956           $invoice_data{'total_item'} = _latex_escape($payment->{'description'});
1957           #$paymenttotal
1958           $invoice_data{'total_amount'} = '-\dollar '. $payment->{'amount'};
1959           push @total_fill, 
1960             map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1961                 @total_item;
1962         }
1963   
1964         $invoice_data{'total_item'} = '\textbf{'. $self->balance_due_msg. '}';
1965         $invoice_data{'total_amount'} =
1966           '\textbf{\dollar '. sprintf('%.2f', $self->owed + $pr_total ). '}';
1967         push @total_fill,
1968           map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
1969               @total_item;
1970   
1971         push @filled_in, @total_fill;
1972   
1973       } else {
1974         #$line =~ s/\$(\w+)/$invoice_data{$1}/eg;
1975         $line =~ s/\$(\w+)/exists($invoice_data{$1}) ? $invoice_data{$1} : nounder($1)/eg;
1976         push @filled_in, $line;
1977       }
1978   
1979     }
1980
1981     sub nounder {
1982       my $var = $1;
1983       $var =~ s/_/\-/g;
1984       $var;
1985     }
1986
1987   } elsif ( $format eq 'Text::Template' ) {
1988
1989     my @detail_items = ();
1990     my @total_items = ();
1991
1992     $invoice_data{'detail_items'} = \@detail_items;
1993     $invoice_data{'total_items'} = \@total_items;
1994   
1995     my %options = ( 'format' => 'latex', 'escape_function' => \&_latex_escape );
1996     foreach my $line_item ( ($conf->exists('disable_previous_balance') ? qw() : $self->_items_previous(%options)), $self->_items_pkg(%options) ) {
1997       my $detail = {
1998         ext_description => [],
1999       };
2000       $detail->{'ref'} = $line_item->{'pkgnum'};
2001       $detail->{'quantity'} = 1;
2002       $detail->{'description'} = _latex_escape($line_item->{'description'});
2003       if ( exists $line_item->{'ext_description'} ) {
2004         @{$detail->{'ext_description'}} = @{$line_item->{'ext_description'}};
2005       }
2006       $detail->{'amount'} = $line_item->{'amount'};
2007       $detail->{'unit_amount'} = $line_item->{'unit_amount'};
2008       $detail->{'product_code'} = $line_item->{'pkgpart'} || 'N/A';
2009   
2010       push @detail_items, $detail;
2011     }
2012   
2013   
2014     my $taxtotal = 0;
2015     foreach my $tax ( $self->_items_tax ) {
2016       my $total = {};
2017       $total->{'total_item'} = _latex_escape($tax->{'description'});
2018       $taxtotal += $tax->{'amount'};
2019       $total->{'total_amount'} = '\dollar '. $tax->{'amount'};
2020       push @total_items, $total;
2021     }
2022   
2023     if ( $taxtotal ) {
2024       my $total = {};
2025       $total->{'total_item'} = 'Sub-total';
2026       $total->{'total_amount'} =
2027         '\dollar '. sprintf('%.2f', $self->charged - $taxtotal );
2028       unshift @total_items, $total;
2029     }
2030   
2031     {
2032       my $total = {};
2033       $total->{'total_item'} = '\textbf{Total}';
2034       $total->{'total_amount'} =
2035         '\textbf{\dollar '.
2036         sprintf( '%.2f',
2037                  $self->charged + ( $conf->exists('disable_previous_balance')
2038                                     ? 0
2039                                     : $pr_total
2040                                   )
2041                ).
2042       '}';
2043       push @total_items, $total;
2044     }
2045   
2046     unless ($conf->exists('disable_previous_balance')) {
2047       #foreach my $thing ( sort { $a->_date <=> $b->_date } $self->_items_credits, $self->_items_payments
2048   
2049       # credits
2050       foreach my $credit ( $self->_items_credits ) {
2051         my $total;
2052         $total->{'total_item'} = _latex_escape($credit->{'description'});
2053         #$credittotal
2054         $total->{'total_amount'} = '-\dollar '. $credit->{'amount'};
2055         push @total_items, $total;
2056       }
2057   
2058       # payments
2059       foreach my $payment ( $self->_items_payments ) {
2060         my $total = {};
2061         $total->{'total_item'} = _latex_escape($payment->{'description'});
2062         #$paymenttotal
2063         $total->{'total_amount'} = '-\dollar '. $payment->{'amount'};
2064         push @total_items, $total;
2065       }
2066   
2067       { 
2068         my $total;
2069         $total->{'total_item'} = '\textbf{'. $self->balance_due_msg. '}';
2070         $total->{'total_amount'} =
2071           '\textbf{\dollar '. sprintf('%.2f', $self->owed + $pr_total ). '}';
2072         push @total_items, $total;
2073       }
2074     }
2075
2076   } else {
2077     die "guru meditation #54";
2078   }
2079
2080   my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2081   my $fh = new File::Temp( TEMPLATE => 'invoice.'. $self->invnum. '.XXXXXXXX',
2082                            DIR      => $dir,
2083                            SUFFIX   => '.tex',
2084                            UNLINK   => 0,
2085                          ) or die "can't open temp file: $!\n";
2086   if ( $format eq 'old' ) {
2087     print $fh join('', @filled_in );
2088   } elsif ( $format eq 'Text::Template' ) {
2089     $text_template->fill_in(OUTPUT => $fh, HASH => \%invoice_data);
2090   } else {
2091     die "guru meditation #32";
2092   }
2093   close $fh;
2094
2095   $fh->filename =~ /^(.*).tex$/ or die "unparsable filename: ". $fh->filename;
2096   return $1;
2097
2098 }
2099
2100 =item print_ps [ TIME [ , TEMPLATE ] ]
2101
2102 Returns an postscript invoice, as a scalar.
2103
2104 TIME an optional value used to control the printing of overdue messages.  The
2105 default is now.  It isn't the date of the invoice; that's the `_date' field.
2106 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2107 L<Time::Local> and L<Date::Parse> for conversion functions.
2108
2109 =cut
2110
2111 sub print_ps {
2112   my $self = shift;
2113
2114   my $file = $self->print_latex(@_);
2115   my $ps = generate_ps($file);
2116   
2117   $ps;
2118 }
2119
2120 =item print_pdf [ TIME [ , TEMPLATE ] ]
2121
2122 Returns an PDF invoice, as a scalar.
2123
2124 TIME an optional value used to control the printing of overdue messages.  The
2125 default is now.  It isn't the date of the invoice; that's the `_date' field.
2126 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2127 L<Time::Local> and L<Date::Parse> for conversion functions.
2128
2129 =cut
2130
2131 sub print_pdf {
2132   my $self = shift;
2133
2134   my $file = $self->print_latex(@_);
2135   my $pdf = generate_pdf($file);
2136   
2137   $pdf;
2138 }
2139
2140 =item print_html [ TIME [ , TEMPLATE [ , CID ] ] ]
2141
2142 Returns an HTML invoice, as a scalar.
2143
2144 TIME an optional value used to control the printing of overdue messages.  The
2145 default is now.  It isn't the date of the invoice; that's the `_date' field.
2146 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
2147 L<Time::Local> and L<Date::Parse> for conversion functions.
2148
2149 CID is a MIME Content-ID used to create a "cid:" URL for the logo image, used
2150 when emailing the invoice as part of a multipart/related MIME email.
2151
2152 =cut
2153
2154 #some falze laziness w/print_text and print_latex (and send_csv)
2155 sub print_html {
2156   my( $self, $today, $template, $cid ) = @_;
2157   $today ||= time;
2158
2159   my $cust_main = $self->cust_main;
2160   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
2161     unless $cust_main->payname && $cust_main->payby !~ /^(CHEK|DCHK)$/;
2162
2163   $template ||= $self->_agent_template;
2164   my $templatefile = 'invoice_html';
2165   my $suffix = length($template) ? "_$template" : '';
2166   $templatefile .= $suffix;
2167   my @html_template = map "$_\n", $conf->config($templatefile)
2168     or die "cannot load config file $templatefile";
2169
2170   my $html_template = new Text::Template(
2171     TYPE   => 'ARRAY',
2172     SOURCE => \@html_template,
2173     DELIMITERS => [ '<%=', '%>' ],
2174   );
2175
2176   $html_template->compile()
2177     or die 'While compiling ' . $templatefile . ': ' . $Text::Template::ERROR;
2178
2179   my %invoice_data = (
2180     'custnum'      => $self->custnum,
2181     'invnum'       => $self->invnum,
2182     'date'         => time2str('%b&nbsp;%o,&nbsp;%Y', $self->_date),
2183     'today'        => time2str('%b %o, %Y', $today),
2184     'agent'        => encode_entities($cust_main->agent->agent),
2185     'agent_custid' => encode_entities($cust_main->agent_custid),
2186     'payname'      => encode_entities($cust_main->payname),
2187     'company'      => encode_entities($cust_main->company),
2188     'address1'     => encode_entities($cust_main->address1),
2189     'address2'     => encode_entities($cust_main->address2),
2190     'city'         => encode_entities($cust_main->city),
2191     'state'        => encode_entities($cust_main->state),
2192     'zip'          => encode_entities($cust_main->zip),
2193     'terms'        => $conf->config('invoice_default_terms')
2194                       || 'Payable upon receipt',
2195     'cid'          => $cid,
2196     'template'     => $template,
2197     'ship_enable'  => $conf->exists('invoice-ship_address'),
2198     'unitprices'   => $conf->exists('invoice-unitprice'),
2199 #    'conf_dir'     => "$FS::UID::conf_dir/conf.$FS::UID::datasrc",
2200   );
2201
2202   my $prefix = $cust_main->has_ship_address ? 'ship_' : '';
2203   foreach ( qw( contact company address1 address2 city state zip country fax) ){
2204     my $method = $prefix.$_;
2205     $invoice_data{"ship_$_"} = encode_entities($cust_main->$method);
2206   }
2207
2208   if (
2209          defined( $conf->config_orbase('invoice_htmlreturnaddress', $template) )
2210       && length(  $conf->config_orbase('invoice_htmlreturnaddress', $template) )
2211   ) {
2212     $invoice_data{'returnaddress'} =
2213       join("\n", $conf->config_orbase('invoice_htmlreturnaddress', $template) );
2214   } else {
2215     $invoice_data{'returnaddress'} =
2216       join("\n", map { 
2217                        s/~/&nbsp;/g;
2218                        s/\\\\\*?\s*$/<BR>/;
2219                        s/\\hyphenation\{[\w\s\-]+\}//;
2220                        $_;
2221                      }
2222                      $conf->config_orbase( 'invoice_latexreturnaddress',
2223                                            $template
2224                                          )
2225           );
2226   }
2227
2228   my $countrydefault = $conf->config('countrydefault') || 'US';
2229   if ( $cust_main->country eq $countrydefault ) {
2230     $invoice_data{'country'} = '';
2231   } else {
2232     $invoice_data{'country'} =
2233       encode_entities(code2country($cust_main->country));
2234   }
2235
2236   if (
2237          defined( $conf->config_orbase('invoice_htmlnotes', $template) )
2238       && length(  $conf->config_orbase('invoice_htmlnotes', $template) )
2239   ) {
2240     $invoice_data{'notes'} =
2241       join("\n", $conf->config_orbase('invoice_htmlnotes', $template) );
2242   } else {
2243     $invoice_data{'notes'} = 
2244       join("\n", map { 
2245                        s/%%(.*)$/<!-- $1 -->/g;
2246                        s/\\section\*\{\\textsc\{(.)(.*)\}\}/<p><b><font size="+1">$1<\/font>\U$2<\/b>/g;
2247                        s/\\begin\{enumerate\}/<ol>/g;
2248                        s/\\item /  <li>/g;
2249                        s/\\end\{enumerate\}/<\/ol>/g;
2250                        s/\\textbf\{(.*)\}/<b>$1<\/b>/g;
2251                        s/\\\\\*/<br>/g;
2252                        s/\\dollar ?/\$/g;
2253                        s/\\#/#/g;
2254                        s/~/&nbsp;/g;
2255                        $_;
2256                      } 
2257                      $conf->config_orbase('invoice_latexnotes', $template)
2258           );
2259   }
2260
2261 #  #do variable substitutions in notes
2262 #  $invoice_data{'notes'} =
2263 #    join("\n",
2264 #      map { my $b=$_; $b =~ s/\$(\w+)/$invoice_data{$1}/eg; $b }
2265 #        $conf->config_orbase('invoice_latexnotes', $suffix)
2266 #    );
2267
2268   if (
2269          defined( $conf->config_orbase('invoice_htmlfooter', $template) )
2270       && length(  $conf->config_orbase('invoice_htmlfooter', $template) )
2271   ) {
2272    $invoice_data{'footer'} =
2273      join("\n", $conf->config_orbase('invoice_htmlfooter', $template) );
2274   } else {
2275    $invoice_data{'footer'} =
2276        join("\n", map { s/~/&nbsp;/g; s/\\\\\*?\s*$/<BR>/; $_; }
2277                       $conf->config_orbase('invoice_latexfooter', $template)
2278            );
2279   }
2280
2281   $invoice_data{'po_line'} =
2282     (  $cust_main->payby eq 'BILL' && $cust_main->payinfo )
2283       ? encode_entities("Purchase Order #". $cust_main->payinfo)
2284       : '';
2285
2286   my $money_char = $conf->config('money_char') || '$';
2287
2288   my %options = ( 'format' => 'html', 'escape_function' => \&encode_entities );
2289   foreach my $line_item ( ($conf->exists('disable_previous_balance') ? qw() : $self->_items_previous(%options)), $self->_items_pkg(%options) ) {
2290     my $detail = {
2291       ext_description => [],
2292     };
2293     $detail->{'ref'} = $line_item->{'pkgnum'};
2294     $detail->{'description'} = encode_entities($line_item->{'description'});
2295     if ( exists $line_item->{'ext_description'} ) {
2296       @{$detail->{'ext_description'}} = @{$line_item->{'ext_description'}};
2297     }
2298     $detail->{'amount'} = $money_char. $line_item->{'amount'};
2299     $detail->{'product_code'} = $line_item->{'pkgpart'} || 'N/A';
2300
2301     push @{$invoice_data{'detail_items'}}, $detail;
2302   }
2303
2304
2305   my $taxtotal = 0;
2306   foreach my $tax ( $self->_items_tax ) {
2307     my $total = {};
2308     $total->{'total_item'} = encode_entities($tax->{'description'});
2309     $taxtotal += $tax->{'amount'};
2310     $total->{'total_amount'} = $money_char. $tax->{'amount'};
2311     push @{$invoice_data{'total_items'}}, $total;
2312   }
2313
2314   if ( $taxtotal ) {
2315     my $total = {};
2316     $total->{'total_item'} = 'Sub-total';
2317     $total->{'total_amount'} =
2318       $money_char. sprintf('%.2f', $self->charged - $taxtotal );
2319     unshift @{$invoice_data{'total_items'}}, $total;
2320   }
2321
2322   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2323   {
2324     my $total = {};
2325     $total->{'total_item'} = '<b>Total</b>';
2326     $total->{'total_amount'} =
2327       "<b>$money_char".
2328       sprintf( '%.2f',
2329                $self->charged + ( $conf->exists('disable_previous_balance')
2330                                   ? 0
2331                                   : $pr_total
2332                                 )
2333              ).
2334       '</b>';
2335     push @{$invoice_data{'total_items'}}, $total;
2336   }
2337
2338   unless ($conf->exists('disable_previous_balance')) {
2339     #foreach my $thing ( sort { $a->_date <=> $b->_date } $self->_items_credits, $self->_items_payments
2340
2341     # credits
2342     foreach my $credit ( $self->_items_credits ) {
2343       my $total;
2344       $total->{'total_item'} = encode_entities($credit->{'description'});
2345       #$credittotal
2346       $total->{'total_amount'} = "-$money_char". $credit->{'amount'};
2347       push @{$invoice_data{'total_items'}}, $total;
2348     }
2349
2350     # payments
2351     foreach my $payment ( $self->_items_payments ) {
2352       my $total = {};
2353       $total->{'total_item'} = encode_entities($payment->{'description'});
2354       #$paymenttotal
2355       $total->{'total_amount'} = "-$money_char". $payment->{'amount'};
2356       push @{$invoice_data{'total_items'}}, $total;
2357     }
2358
2359     { 
2360       my $total;
2361       $total->{'total_item'} = '<b>'. $self->balance_due_msg. '</b>';
2362       $total->{'total_amount'} =
2363         "<b>$money_char".  sprintf('%.2f', $self->owed + $pr_total ). '</b>';
2364       push @{$invoice_data{'total_items'}}, $total;
2365     }
2366   }
2367
2368   $html_template->fill_in( HASH => \%invoice_data);
2369 }
2370
2371 # quick subroutine for print_latex
2372 #
2373 # There are ten characters that LaTeX treats as special characters, which
2374 # means that they do not simply typeset themselves: 
2375 #      # $ % & ~ _ ^ \ { }
2376 #
2377 # TeX ignores blanks following an escaped character; if you want a blank (as
2378 # in "10% of ..."), you have to "escape" the blank as well ("10\%\ of ..."). 
2379
2380 sub _latex_escape {
2381   my $value = shift;
2382   $value =~ s/([#\$%&~_\^{}])( )?/"\\$1". ( ( defined($2) && length($2) ) ? "\\$2" : '' )/ge;
2383   $value =~ s/([<>])/\$$1\$/g;
2384   $value;
2385 }
2386
2387 #utility methods for print_*
2388
2389 sub balance_due_msg {
2390   my $self = shift;
2391   my $msg = 'Balance Due';
2392   return $msg unless $conf->exists('invoice_default_terms');
2393   if ( $conf->config('invoice_default_terms') =~ /^\s*Net\s*(\d+)\s*$/ ) {
2394     $msg .= ' - Please pay by '. time2str("%x", $self->_date + ($1*86400) );
2395   } elsif ( $conf->config('invoice_default_terms') ) {
2396     $msg .= ' - '. $conf->config('invoice_default_terms');
2397   }
2398   $msg;
2399 }
2400
2401 =item invnum_date_pretty
2402
2403 Returns a string with the invoice number and date, for example:
2404 "Invoice #54 (3/20/2008)"
2405
2406 =cut
2407
2408 sub invnum_date_pretty {
2409   my $self = shift;
2410   'Invoice #'. $self->invnum. ' ('. time2str('%x', $self->_date). ')';
2411 }
2412
2413 sub _items {
2414   my $self = shift;
2415
2416   #my @display = scalar(@_)
2417   #              ? @_
2418   #              : qw( _items_previous _items_pkg );
2419   #              #: qw( _items_pkg );
2420   #              #: qw( _items_previous _items_pkg _items_tax _items_credits _items_payments );
2421   my @display = qw( _items_previous _items_pkg );
2422
2423   my @b = ();
2424   foreach my $display ( @display ) {
2425     push @b, $self->$display(@_);
2426   }
2427   @b;
2428 }
2429
2430 sub _items_previous {
2431   my $self = shift;
2432   my $cust_main = $self->cust_main;
2433   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
2434   my @b = ();
2435   foreach ( @pr_cust_bill ) {
2436     push @b, {
2437       'description' => 'Previous Balance, Invoice #'. $_->invnum. 
2438                        ' ('. time2str('%x',$_->_date). ')',
2439       #'pkgpart'     => 'N/A',
2440       'pkgnum'      => 'N/A',
2441       'amount'      => sprintf("%.2f", $_->owed),
2442     };
2443   }
2444   @b;
2445
2446   #{
2447   #    'description'     => 'Previous Balance',
2448   #    #'pkgpart'         => 'N/A',
2449   #    'pkgnum'          => 'N/A',
2450   #    'amount'          => sprintf("%10.2f", $pr_total ),
2451   #    'ext_description' => [ map {
2452   #                                 "Invoice ". $_->invnum.
2453   #                                 " (". time2str("%x",$_->_date). ") ".
2454   #                                 sprintf("%10.2f", $_->owed)
2455   #                         } @pr_cust_bill ],
2456
2457   #};
2458 }
2459
2460 sub _items_pkg {
2461   my $self = shift;
2462   my @cust_bill_pkg = grep { $_->pkgnum } $self->cust_bill_pkg;
2463   $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
2464 }
2465
2466 sub _items_tax {
2467   my $self = shift;
2468   my @cust_bill_pkg = grep { ! $_->pkgnum } $self->cust_bill_pkg;
2469   $self->_items_cust_bill_pkg(\@cust_bill_pkg, @_);
2470 }
2471
2472 sub _items_cust_bill_pkg {
2473   my $self = shift;
2474   my $cust_bill_pkg = shift;
2475   my %opt = @_;
2476
2477   my $format = $opt{format} || '';
2478   my $escape_function = $opt{escape_function} || sub { shift };
2479
2480   my @b = ();
2481   foreach my $cust_bill_pkg ( @$cust_bill_pkg ) {
2482
2483     my $cust_pkg = $cust_bill_pkg->cust_pkg;
2484
2485     my $desc = $cust_bill_pkg->desc;
2486
2487     my %details_opt = ( 'format'          => $format,
2488                         'escape_function' => $escape_function,
2489                       );
2490
2491     if ( $cust_bill_pkg->pkgnum > 0 ) {
2492
2493       if ( $cust_bill_pkg->setup != 0 ) {
2494
2495         my $description = $desc;
2496         $description .= ' Setup' if $cust_bill_pkg->recur != 0;
2497
2498         my @d = map &{$escape_function}($_),
2499                        $cust_pkg->h_labels_short($self->_date);
2500         push @d, $cust_bill_pkg->details(%details_opt)
2501           if $cust_bill_pkg->recur == 0;
2502
2503         push @b, {
2504           description     => $description,
2505           #pkgpart         => $part_pkg->pkgpart,
2506           pkgnum          => $cust_bill_pkg->pkgnum,
2507           amount          => sprintf("%.2f", $cust_bill_pkg->setup),
2508           unit_amount     => sprintf("%.2f", $cust_bill_pkg->unitsetup),
2509           quantity        => $cust_bill_pkg->quantity,
2510           ext_description => \@d,
2511         };
2512       }
2513
2514       if ( $cust_bill_pkg->recur != 0 ) {
2515
2516         my $description = $desc;
2517         unless ( $conf->exists('disable_line_item_date_ranges') ) {
2518           $desc .= " (" . time2str("%x", $cust_bill_pkg->sdate).
2519                    " - ". time2str("%x", $cust_bill_pkg->edate). ")";
2520         }
2521
2522         #at least until cust_bill_pkg has "past" ranges in addition to
2523         #the "future" sdate/edate ones... see #3032
2524         my @d = map &{$escape_function}($_),
2525                     $cust_pkg->h_labels_short($self->_date);
2526                                               #$cust_bill_pkg->edate,
2527                                               #$cust_bill_pkg->sdate),
2528         push @d, $cust_bill_pkg->details(%details_opt);
2529
2530         push @b, {
2531           description     => $description,
2532           #pkgpart         => $part_pkg->pkgpart,
2533           pkgnum          => $cust_bill_pkg->pkgnum,
2534           amount          => sprintf("%.2f", $cust_bill_pkg->recur),
2535           unit_amount     => sprintf("%.2f", $cust_bill_pkg->unitrecur),
2536           quantity        => $cust_bill_pkg->quantity,
2537           ext_description => \@d,
2538         };
2539
2540       }
2541
2542     } else { #pkgnum tax or one-shot line item (??)
2543
2544       if ( $cust_bill_pkg->setup != 0 ) {
2545         push @b, {
2546           'description' => $desc,
2547           'amount'      => sprintf("%.2f", $cust_bill_pkg->setup),
2548         };
2549       }
2550       if ( $cust_bill_pkg->recur != 0 ) {
2551         push @b, {
2552           'description' => "$desc (".
2553                            time2str("%x", $cust_bill_pkg->sdate). ' - '.
2554                            time2str("%x", $cust_bill_pkg->edate). ')',
2555           'amount'      => sprintf("%.2f", $cust_bill_pkg->recur),
2556         };
2557       }
2558
2559     }
2560
2561   }
2562
2563   @b;
2564
2565 }
2566
2567 sub _items_credits {
2568   my $self = shift;
2569
2570   my @b;
2571   #credits
2572   foreach ( $self->cust_credited ) {
2573
2574     #something more elaborate if $_->amount ne $_->cust_credit->credited ?
2575
2576     my $reason = $_->cust_credit->reason;
2577     #my $reason = substr($_->cust_credit->reason,0,32);
2578     #$reason .= '...' if length($reason) < length($_->cust_credit->reason);
2579     $reason = " ($reason) " if $reason;
2580     push @b, {
2581       #'description' => 'Credit ref\#'. $_->crednum.
2582       #                 " (". time2str("%x",$_->cust_credit->_date) .")".
2583       #                 $reason,
2584       'description' => 'Credit applied '.
2585                        time2str("%x",$_->cust_credit->_date). $reason,
2586       'amount'      => sprintf("%.2f",$_->amount),
2587     };
2588   }
2589   #foreach ( @cr_cust_credit ) {
2590   #  push @buf,[
2591   #    "Credit #". $_->crednum. " (" . time2str("%x",$_->_date) .")",
2592   #    $money_char. sprintf("%10.2f",$_->credited)
2593   #  ];
2594   #}
2595
2596   @b;
2597
2598 }
2599
2600 sub _items_payments {
2601   my $self = shift;
2602
2603   my @b;
2604   #get & print payments
2605   foreach ( $self->cust_bill_pay ) {
2606
2607     #something more elaborate if $_->amount ne ->cust_pay->paid ?
2608
2609     push @b, {
2610       'description' => "Payment received ".
2611                        time2str("%x",$_->cust_pay->_date ),
2612       'amount'      => sprintf("%.2f", $_->amount )
2613     };
2614   }
2615
2616   @b;
2617
2618 }
2619
2620
2621 =back
2622
2623 =head1 SUBROUTINES
2624
2625 =over 4
2626
2627 =item reprint
2628
2629 =cut
2630
2631 sub process_reprint {
2632   process_re_X('print', @_);
2633 }
2634
2635 =item reemail
2636
2637 =cut
2638
2639 sub process_reemail {
2640   process_re_X('email', @_);
2641 }
2642
2643 =item refax
2644
2645 =cut
2646
2647 sub process_refax {
2648   process_re_X('fax', @_);
2649 }
2650
2651 use Storable qw(thaw);
2652 use Data::Dumper;
2653 use MIME::Base64;
2654 sub process_re_X {
2655   my( $method, $job ) = ( shift, shift );
2656   warn "$me process_re_X $method for job $job\n" if $DEBUG;
2657
2658   my $param = thaw(decode_base64(shift));
2659   warn Dumper($param) if $DEBUG;
2660
2661   re_X(
2662     $method,
2663     $job,
2664     %$param,
2665   );
2666
2667 }
2668
2669 sub re_X {
2670   my($method, $job, %param ) = @_;
2671   if ( $DEBUG ) {
2672     warn "re_X $method for job $job with param:\n".
2673          join( '', map { "  $_ => ". $param{$_}. "\n" } keys %param );
2674   }
2675
2676   #some false laziness w/search/cust_bill.html
2677   my $distinct = '';
2678   my $orderby = 'ORDER BY cust_bill._date';
2679
2680   my $extra_sql = ' WHERE '. FS::cust_bill->search_sql(\%param);
2681
2682   my $addl_from = 'LEFT JOIN cust_main USING ( custnum )';
2683      
2684   my @cust_bill = qsearch( {
2685     #'select'    => "cust_bill.*",
2686     'table'     => 'cust_bill',
2687     'addl_from' => $addl_from,
2688     'hashref'   => {},
2689     'extra_sql' => $extra_sql,
2690     'order_by'  => $orderby,
2691     'debug' => 1,
2692   } );
2693
2694   warn " $me re_X $method: ". scalar(@cust_bill). " invoices found\n"
2695     if $DEBUG;
2696
2697   my( $num, $last, $min_sec ) = (0, time, 5); #progresbar foo
2698   foreach my $cust_bill ( @cust_bill ) {
2699     $cust_bill->$method();
2700
2701     if ( $job ) { #progressbar foo
2702       $num++;
2703       if ( time - $min_sec > $last ) {
2704         my $error = $job->update_statustext(
2705           int( 100 * $num / scalar(@cust_bill) )
2706         );
2707         die $error if $error;
2708         $last = time;
2709       }
2710     }
2711
2712   }
2713
2714 }
2715
2716 =back
2717
2718 =head1 CLASS METHODS
2719
2720 =over 4
2721
2722 =item owed_sql
2723
2724 Returns an SQL fragment to retreive the amount owed (charged minus credited and paid).
2725
2726 =cut
2727
2728 sub owed_sql {
2729   my $class = shift;
2730   'charged - '. $class->paid_sql. ' - '. $class->credited_sql;
2731 }
2732
2733 =item net_sql
2734
2735 Returns an SQL fragment to retreive the net amount (charged minus credited).
2736
2737 =cut
2738
2739 sub net_sql {
2740   my $class = shift;
2741   'charged - '. $class->credited_sql;
2742 }
2743
2744 =item paid_sql
2745
2746 Returns an SQL fragment to retreive the amount paid against this invoice.
2747
2748 =cut
2749
2750 sub paid_sql {
2751   #my $class = shift;
2752   "( SELECT COALESCE(SUM(amount),0) FROM cust_bill_pay
2753        WHERE cust_bill.invnum = cust_bill_pay.invnum   )";
2754 }
2755
2756 =item credited_sql
2757
2758 Returns an SQL fragment to retreive the amount credited against this invoice.
2759
2760 =cut
2761
2762 sub credited_sql {
2763   #my $class = shift;
2764   "( SELECT COALESCE(SUM(amount),0) FROM cust_credit_bill
2765        WHERE cust_bill.invnum = cust_credit_bill.invnum   )";
2766 }
2767
2768 =item search_sql HASHREF
2769
2770 Class method which returns an SQL WHERE fragment to search for parameters
2771 specified in HASHREF.  Valid parameters are
2772
2773 =over 4
2774
2775 =item begin
2776
2777 Epoch date (UNIX timestamp) setting a lower bound for _date values
2778
2779 =item end
2780
2781 Epoch date (UNIX timestamp) setting an upper bound for _date values
2782
2783 =item invnum_min
2784
2785 =item invnum_max
2786
2787 =item agentnum
2788
2789 =item owed
2790
2791 =item net
2792
2793 =item days
2794
2795 =item newest_percust
2796
2797 =back
2798
2799 Note: validates all passed-in data; i.e. safe to use with unchecked CGI params.
2800
2801 =cut
2802
2803 sub search_sql {
2804   my($class, $param) = @_;
2805   if ( $DEBUG ) {
2806     warn "$me search_sql called with params: \n".
2807          join("\n", map { "  $_: ". $param->{$_} } keys %$param ). "\n";
2808   }
2809
2810   my @search = ();
2811
2812   if ( $param->{'begin'} =~ /^(\d+)$/ ) {
2813     push @search, "cust_bill._date >= $1";
2814   }
2815   if ( $param->{'end'} =~ /^(\d+)$/ ) {
2816     push @search, "cust_bill._date < $1";
2817   }
2818   if ( $param->{'invnum_min'} =~ /^(\d+)$/ ) {
2819     push @search, "cust_bill.invnum >= $1";
2820   }
2821   if ( $param->{'invnum_max'} =~ /^(\d+)$/ ) {
2822     push @search, "cust_bill.invnum <= $1";
2823   }
2824   if ( $param->{'agentnum'} =~ /^(\d+)$/ ) {
2825     push @search, "cust_main.agentnum = $1";
2826   }
2827
2828   push @search, '0 != '. FS::cust_bill->owed_sql
2829     if $param->{'open'};
2830
2831   push @search, '0 != '. FS::cust_bill->net_sql
2832     if $param->{'net'};
2833
2834   push @search, "cust_bill._date < ". (time-86400*$param->{'days'})
2835     if $param->{'days'};
2836
2837   if ( $param->{'newest_percust'} ) {
2838
2839     #$distinct = 'DISTINCT ON ( cust_bill.custnum )';
2840     #$orderby = 'ORDER BY cust_bill.custnum ASC, cust_bill._date DESC';
2841
2842     my @newest_where = map { my $x = $_;
2843                              $x =~ s/\bcust_bill\./newest_cust_bill./g;
2844                              $x;
2845                            }
2846                            grep ! /^cust_main./, @search;
2847     my $newest_where = scalar(@newest_where)
2848                          ? ' AND '. join(' AND ', @newest_where)
2849                          : '';
2850
2851
2852     push @search, "cust_bill._date = (
2853       SELECT(MAX(newest_cust_bill._date)) FROM cust_bill AS newest_cust_bill
2854         WHERE newest_cust_bill.custnum = cust_bill.custnum
2855           $newest_where
2856     )";
2857
2858   }
2859
2860   my $curuser = $FS::CurrentUser::CurrentUser;
2861   if ( $curuser->username eq 'fs_queue'
2862        && $param->{'CurrentUser'} =~ /^(\w+)$/ ) {
2863     my $username = $1;
2864     my $newuser = qsearchs('access_user', {
2865       'username' => $username,
2866       'disabled' => '',
2867     } );
2868     if ( $newuser ) {
2869       $curuser = $newuser;
2870     } else {
2871       warn "$me WARNING: (fs_queue) can't find CurrentUser $username\n";
2872     }
2873   }
2874
2875   push @search, $curuser->agentnums_sql;
2876
2877   join(' AND ', @search );
2878
2879 }
2880
2881 =back
2882
2883 =head1 BUGS
2884
2885 The delete method.
2886
2887 =head1 SEE ALSO
2888
2889 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
2890 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base
2891 documentation.
2892
2893 =cut
2894
2895 1;
2896