new invoice event: upload a CSV file
[freeside.git] / FS / FS / cust_bill.pm
1 package FS::cust_bill;
2
3 use strict;
4 use vars qw( @ISA $conf $money_char );
5 use vars qw( $lpr $invoice_from $smtpmachine );
6 use vars qw( $processor );
7 use vars qw( $xaction $E_NoErr );
8 use vars qw( $bop_processor $bop_login $bop_password $bop_action @bop_options );
9 use vars qw( $invoice_lines @buf ); #yuck
10 use Date::Format;
11 use Mail::Internet 1.44;
12 use Mail::Header;
13 use Text::Template;
14 use FS::UID qw( datasrc );
15 use FS::Record qw( qsearch qsearchs );
16 use FS::cust_main;
17 use FS::cust_bill_pkg;
18 use FS::cust_credit;
19 use FS::cust_pay;
20 use FS::cust_pkg;
21 use FS::cust_credit_bill;
22 use FS::cust_pay_batch;
23 use FS::cust_bill_event;
24
25 @ISA = qw( FS::Record );
26
27 #ask FS::UID to run this stuff for us later
28 $FS::UID::callback{'FS::cust_bill'} = sub { 
29
30   $conf = new FS::Conf;
31
32   $money_char = $conf->config('money_char') || '$';  
33
34   $lpr = $conf->config('lpr');
35   $invoice_from = $conf->config('invoice_from');
36   $smtpmachine = $conf->config('smtpmachine');
37
38   if ( $conf->exists('cybercash3.2') ) {
39     require CCMckLib3_2;
40       #qw($MCKversion %Config InitConfig CCError CCDebug CCDebug2);
41     require CCMckDirectLib3_2;
42       #qw(SendCC2_1Server);
43     require CCMckErrno3_2;
44       #qw(MCKGetErrorMessage $E_NoErr);
45     import CCMckErrno3_2 qw($E_NoErr);
46
47     my $merchant_conf;
48     ($merchant_conf,$xaction)= $conf->config('cybercash3.2');
49     my $status = &CCMckLib3_2::InitConfig($merchant_conf);
50     if ( $status != $E_NoErr ) {
51       warn "CCMckLib3_2::InitConfig error:\n";
52       foreach my $key (keys %CCMckLib3_2::Config) {
53         warn "  $key => $CCMckLib3_2::Config{$key}\n"
54       }
55       my($errmsg) = &CCMckErrno3_2::MCKGetErrorMessage($status);
56       die "CCMckLib3_2::InitConfig fatal error: $errmsg\n";
57     }
58     $processor='cybercash3.2';
59   } elsif ( $conf->exists('business-onlinepayment') ) {
60     ( $bop_processor,
61       $bop_login,
62       $bop_password,
63       $bop_action,
64       @bop_options
65     ) = $conf->config('business-onlinepayment');
66     $bop_action ||= 'normal authorization';
67     eval "use Business::OnlinePayment";  
68     $processor="Business::OnlinePayment::$bop_processor";
69   }
70
71 };
72
73 =head1 NAME
74
75 FS::cust_bill - Object methods for cust_bill records
76
77 =head1 SYNOPSIS
78
79   use FS::cust_bill;
80
81   $record = new FS::cust_bill \%hash;
82   $record = new FS::cust_bill { 'column' => 'value' };
83
84   $error = $record->insert;
85
86   $error = $new_record->replace($old_record);
87
88   $error = $record->delete;
89
90   $error = $record->check;
91
92   ( $total_previous_balance, @previous_cust_bill ) = $record->previous;
93
94   @cust_bill_pkg_objects = $cust_bill->cust_bill_pkg;
95
96   ( $total_previous_credits, @previous_cust_credit ) = $record->cust_credit;
97
98   @cust_pay_objects = $cust_bill->cust_pay;
99
100   $tax_amount = $record->tax;
101
102   @lines = $cust_bill->print_text;
103   @lines = $cust_bill->print_text $time;
104
105 =head1 DESCRIPTION
106
107 An FS::cust_bill object represents an invoice; a declaration that a customer
108 owes you money.  The specific charges are itemized as B<cust_bill_pkg> records
109 (see L<FS::cust_bill_pkg>).  FS::cust_bill inherits from FS::Record.  The
110 following fields are currently supported:
111
112 =over 4
113
114 =item invnum - primary key (assigned automatically for new invoices)
115
116 =item custnum - customer (see L<FS::cust_main>)
117
118 =item _date - specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
119 L<Time::Local> and L<Date::Parse> for conversion functions.
120
121 =item charged - amount of this invoice
122
123 =item printed - deprecated
124
125 =item closed - books closed flag, empty or `Y'
126
127 =back
128
129 =head1 METHODS
130
131 =over 4
132
133 =item new HASHREF
134
135 Creates a new invoice.  To add the invoice to the database, see L<"insert">.
136 Invoices are normally created by calling the bill method of a customer object
137 (see L<FS::cust_main>).
138
139 =cut
140
141 sub table { 'cust_bill'; }
142
143 =item insert
144
145 Adds this invoice to the database ("Posts" the invoice).  If there is an error,
146 returns the error, otherwise returns false.
147
148 =item delete
149
150 Currently unimplemented.  I don't remove invoices because there would then be
151 no record you ever posted this invoice (which is bad, no?)
152
153 =cut
154
155 sub delete {
156   my $self = shift;
157   return "Can't delete closed invoice" if $self->closed =~ /^Y/i;
158   $self->SUPER::delete(@_);
159 }
160
161 =item replace OLD_RECORD
162
163 Replaces the OLD_RECORD with this one in the database.  If there is an error,
164 returns the error, otherwise returns false.
165
166 Only printed may be changed.  printed is normally updated by calling the
167 collect method of a customer object (see L<FS::cust_main>).
168
169 =cut
170
171 sub replace {
172   my( $new, $old ) = ( shift, shift );
173   return "Can't change custnum!" unless $old->custnum == $new->custnum;
174   #return "Can't change _date!" unless $old->_date eq $new->_date;
175   return "Can't change _date!" unless $old->_date == $new->_date;
176   return "Can't change charged!" unless $old->charged == $new->charged;
177
178   $new->SUPER::replace($old);
179 }
180
181 =item check
182
183 Checks all fields to make sure this is a valid invoice.  If there is an error,
184 returns the error, otherwise returns false.  Called by the insert and replace
185 methods.
186
187 =cut
188
189 sub check {
190   my $self = shift;
191
192   my $error =
193     $self->ut_numbern('invnum')
194     || $self->ut_number('custnum')
195     || $self->ut_numbern('_date')
196     || $self->ut_money('charged')
197     || $self->ut_numbern('printed')
198     || $self->ut_enum('closed', [ '', 'Y' ])
199   ;
200   return $error if $error;
201
202   return "Unknown customer"
203     unless qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
204
205   $self->_date(time) unless $self->_date;
206
207   $self->printed(0) if $self->printed eq '';
208
209   ''; #no error
210 }
211
212 =item previous
213
214 Returns a list consisting of the total previous balance for this customer, 
215 followed by the previous outstanding invoices (as FS::cust_bill objects also).
216
217 =cut
218
219 sub previous {
220   my $self = shift;
221   my $total = 0;
222   my @cust_bill = sort { $a->_date <=> $b->_date }
223     grep { $_->owed != 0 && $_->_date < $self->_date }
224       qsearch( 'cust_bill', { 'custnum' => $self->custnum } ) 
225   ;
226   foreach ( @cust_bill ) { $total += $_->owed; }
227   $total, @cust_bill;
228 }
229
230 =item cust_bill_pkg
231
232 Returns the line items (see L<FS::cust_bill_pkg>) for this invoice.
233
234 =cut
235
236 sub cust_bill_pkg {
237   my $self = shift;
238   qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum } );
239 }
240
241 =item cust_bill_event
242
243 Returns the completed invoice events (see L<FS::cust_bill_event>) for this
244 invoice.
245
246 =cut
247
248 sub cust_bill_event {
249   my $self = shift;
250   qsearch( 'cust_bill_event', { 'invnum' => $self->invnum } );
251 }
252
253
254 =item cust_main
255
256 Returns the customer (see L<FS::cust_main>) for this invoice.
257
258 =cut
259
260 sub cust_main {
261   my $self = shift;
262   qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
263 }
264
265 =item cust_credit
266
267 Depreciated.  See the cust_credited method.
268
269  #Returns a list consisting of the total previous credited (see
270  #L<FS::cust_credit>) and unapplied for this customer, followed by the previous
271  #outstanding credits (FS::cust_credit objects).
272
273 =cut
274
275 sub cust_credit {
276   use Carp;
277   croak "FS::cust_bill->cust_credit depreciated; see ".
278         "FS::cust_bill->cust_credit_bill";
279   #my $self = shift;
280   #my $total = 0;
281   #my @cust_credit = sort { $a->_date <=> $b->_date }
282   #  grep { $_->credited != 0 && $_->_date < $self->_date }
283   #    qsearch('cust_credit', { 'custnum' => $self->custnum } )
284   #;
285   #foreach (@cust_credit) { $total += $_->credited; }
286   #$total, @cust_credit;
287 }
288
289 =item cust_pay
290
291 Depreciated.  See the cust_bill_pay method.
292
293 #Returns all payments (see L<FS::cust_pay>) for this invoice.
294
295 =cut
296
297 sub cust_pay {
298   use Carp;
299   croak "FS::cust_bill->cust_pay depreciated; see FS::cust_bill->cust_bill_pay";
300   #my $self = shift;
301   #sort { $a->_date <=> $b->_date }
302   #  qsearch( 'cust_pay', { 'invnum' => $self->invnum } )
303   #;
304 }
305
306 =item cust_bill_pay
307
308 Returns all payment applications (see L<FS::cust_bill_pay>) for this invoice.
309
310 =cut
311
312 sub cust_bill_pay {
313   my $self = shift;
314   sort { $a->_date <=> $b->_date }
315     qsearch( 'cust_bill_pay', { 'invnum' => $self->invnum } );
316 }
317
318 =item cust_credited
319
320 Returns all applied credits (see L<FS::cust_credit_bill>) for this invoice.
321
322 =cut
323
324 sub cust_credited {
325   my $self = shift;
326   sort { $a->_date <=> $b->_date }
327     qsearch( 'cust_credit_bill', { 'invnum' => $self->invnum } )
328   ;
329 }
330
331 =item tax
332
333 Returns the tax amount (see L<FS::cust_bill_pkg>) for this invoice.
334
335 =cut
336
337 sub tax {
338   my $self = shift;
339   my $total = 0;
340   my @taxlines = qsearch( 'cust_bill_pkg', { 'invnum' => $self->invnum ,
341                                              'pkgnum' => 0 } );
342   foreach (@taxlines) { $total += $_->setup; }
343   $total;
344 }
345
346 =item owed
347
348 Returns the amount owed (still outstanding) on this invoice, which is charged
349 minus all payment applications (see L<FS::cust_bill_pay>) and credit
350 applications (see L<FS::cust_credit_bill>).
351
352 =cut
353
354 sub owed {
355   my $self = shift;
356   my $balance = $self->charged;
357   $balance -= $_->amount foreach ( $self->cust_bill_pay );
358   $balance -= $_->amount foreach ( $self->cust_credited );
359   $balance = sprintf( "%.2f", $balance);
360   $balance =~ s/^\-0\.00$/0.00/; #yay ieee fp
361   $balance;
362 }
363
364 =item send
365
366 Sends this invoice to the destinations configured for this customer: send
367 emails or print.  See L<FS::cust_main_invoice>.
368
369 =cut
370
371 sub send {
372   my($self,$template) = @_;
373   my @print_text = $self->print_text('', $template);
374   my @invoicing_list = $self->cust_main->invoicing_list;
375
376   if ( grep { $_ ne 'POST' } @invoicing_list ) { #email invoice
377     #false laziness w/FS::cust_pay::delete & fs_signup_server && ::realtime_card
378     #$ENV{SMTPHOSTS} = $smtpmachine;
379     $ENV{MAILADDRESS} = $invoice_from;
380     my $header = new Mail::Header ( [
381       "From: $invoice_from",
382       "To: ". join(', ', grep { $_ ne 'POST' } @invoicing_list ),
383       "Sender: $invoice_from",
384       "Reply-To: $invoice_from",
385       "Date: ". time2str("%a, %d %b %Y %X %z", time),
386       "Subject: Invoice",
387     ] );
388     my $message = new Mail::Internet (
389       'Header' => $header,
390       'Body' => [ @print_text ], #( date)
391     );
392     $!=0;
393     $message->smtpsend( Host => $smtpmachine )
394       or $message->smtpsend( Host => $smtpmachine, Debug => 1 )
395         or return "(customer # ". $self->custnum. ") can't send invoice email".
396                   " to ". join(', ', grep { $_ ne 'POST' } @invoicing_list ).
397                   " via server $smtpmachine with SMTP: $!";
398
399   }
400
401   if ( ! @invoicing_list || grep { $_ eq 'POST' } @invoicing_list ) { #postal
402     open(LPR, "|$lpr")
403       or return "Can't open pipe to $lpr: $!";
404     print LPR @print_text;
405     close LPR
406       or return $! ? "Error closing $lpr: $!"
407                    : "Exit status $? from $lpr";
408   }
409
410   '';
411
412 }
413
414 =item send_csv OPTIONS
415
416 Sends invoice as a CSV data-file to a remote host with the specified protocol.
417
418 Options are:
419
420 protocol - currently only "ftp"
421 server
422 username
423 password
424 dir
425
426 The file will be named "N-YYYYMMDDHHMMSS.csv" where N is the invoice number
427 and YYMMDDHHMMSS is a timestamp.
428
429 The fields of the CSV file is as follows:
430
431 record_type, invnum, custnum, _date, charged, first, last, company, address1, address2, city, state, zip, country, pkg, setup, recur, sdate, edate
432
433 =over 4
434
435 =item record type - B<record_type> is either C<cust_bill> or C<cust_bill_pkg>
436
437 If B<record_type> is C<cust_bill>, this is a primary invoice record.  The
438 last five fields (B<pkg> through B<edate>) are irrelevant, and all other
439 fields are filled in.
440
441 If B<record_type> is C<cust_bill_pkg>, this is a line item record.  Only the
442 first two fields (B<record_type> and B<invnum>) and the last five fields
443 (B<pkg> through B<edate>) are filled in.
444
445 =item invnum - invoice number
446 =item custnum - customer number
447 =item _date - invoice date
448 =item charged - total invoice amount
449 =item first - customer first name
450 =item last - customer first name
451 =item company - company name
452 =item address1 - address line 1
453 =item address2 - address line 1
454 =item city
455 =item state
456 =item zip
457 =item country
458
459 =item pkg - line item description
460 =item setup - line item setup fee (only or both of B<setup> and B<recur> will be defined)
461 =item recur - line item recurring fee (only or both of B<setup> and B<recur> will be defined)
462 =item sdate - start date for recurring fee
463 =item edate - end date for recurring fee
464
465 =back
466
467 =cut
468
469 sub send_csv {
470   my($self, %opt) = @_;
471
472   #part one: create file
473
474   my $spooldir = "/usr/local/etc/freeside/export.". datasrc. "/cust_bill";
475   mkdir $spooldir, 0700 unless -d $spooldir;
476
477   my $file = $spooldir. '/'. $self->invnum. time2str('-%Y%m%d%H%M%S.csv', time);
478
479   open(CSV, ">$file") or die "can't open $file: $!";
480
481   eval "use Text::CSV_XS";
482   die $@ if $@;
483
484   my $csv = Text::CSV_XS->new({'always_quote'=>1});
485
486   my $cust_main = $self->cust_main;
487
488   $csv->combine(
489     'cust_bill',
490     $self->invnum,
491     $self->custnum,
492     time2str("%x", $self->_date),
493     ( map { $cust_main->getfield($_) }
494         qw( first last company address1 address2 city state zip country ) ),
495     map { '' } (1..5),
496   ) or die "can't create csv";
497   print CSV $csv->string. "\n";
498
499   #new charges (false laziness w/print_text)
500   foreach my $cust_bill_pkg ( $self->cust_bill_pkg ) {
501
502     my($pkg, $setup, $recur, $sdate, $edate);
503     if ( $cust_bill_pkg->pkgnum ) {
504     
505       ($pkg, $setup, $recur, $sdate, $edate) = (
506         $cust_bill_pkg->cust_pkg->part_pkg->pkg,
507         ( $cust_bill_pkg->setup != 0
508           ? sprintf("%.2f", $cust_bill_pkg->setup )
509           : '' ),
510         ( $cust_bill_pkg->recur != 0
511           ? sprintf("%.2f", $cust_bill_pkg->recur )
512           : '' ),
513         time2str("%x", $cust_bill_pkg->sdate),
514         time2str("%x", $cust_bill_pkg->edate),
515       );
516
517     } else { #pkgnum Tax
518       next unless $cust_bill_pkg->setup != 0;
519       ($pkg, $setup, $recur, $sdate, $edate) =
520         ( 'Tax', sprintf("%10.2f",$cust_bill_pkg->setup), '', '', '' );
521     }
522
523     $csv->combine(
524       'cust_bill_pkg',
525       $self->invnum,
526       ( map { '' } (1..11) ),
527       ($pkg, $setup, $recur, $sdate, $edate)
528     ) or die "can't create csv";
529     print CSV $csv->string. "\n";
530
531   }
532
533   close CSV or die "can't close CSV: $!";
534
535   #part two: upload it
536
537   my $net;
538   if ( $opt{protocol} eq 'ftp' ) {
539     eval "use Net::FTP;";
540     die $@ if $@;
541     $net = Net::FTP->new($opt{server}) or die @$;
542   } else {
543     die "unknown protocol: $opt{protocol}";
544   }
545
546   $net->login( $opt{username}, $opt{password} )
547     or die "can't FTP to $opt{username}\@$opt{server}: login error: $@";
548
549   $net->binary or die "can't set binary mode";
550
551   $net->cwd($opt{dir}) or die "can't cwd to $opt{dir}";
552
553   $net->put($file) or die "can't put $file: $!";
554
555   $net->quit;
556
557   unlink $file;
558
559 }
560
561 =item comp
562
563 Pays this invoice with a compliemntary payment.  If there is an error,
564 returns the error, otherwise returns false.
565
566 =cut
567
568 sub comp {
569   my $self = shift;
570   my $cust_pay = new FS::cust_pay ( {
571     'invnum'   => $self->invnum,
572     'paid'     => $self->owed,
573     '_date'    => '',
574     'payby'    => 'COMP',
575     'payinfo'  => $self->cust_main->payinfo,
576     'paybatch' => '',
577   } );
578   $cust_pay->insert;
579 }
580
581 =item realtime_card
582
583 Attempts to pay this invoice with a Business::OnlinePayment realtime gateway.
584 See http://search.cpan.org/search?mode=module&query=Business%3A%3AOnlinePayment
585 for supproted processors.
586
587 =cut
588
589 sub realtime_card {
590   my $self = shift;
591   my $cust_main = $self->cust_main;
592   my $amount = $self->owed;
593
594   unless ( $processor =~ /^Business::OnlinePayment::(.*)$/ ) {
595     return "Real-time card processing not enabled (processor $processor)";
596   }
597   my $bop_processor = $1; #hmm?
598
599   my $address = $cust_main->address1;
600   $address .= ", ". $cust_main->address2 if $cust_main->address2;
601
602   #fix exp. date
603   #$cust_main->paydate =~ /^(\d+)\/\d*(\d{2})$/;
604   $cust_main->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
605   my $exp = "$2/$1";
606
607   my($payname, $payfirst, $paylast);
608   if ( $cust_main->payname ) {
609     $payname = $cust_main->payname;
610     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
611       or do {
612               #$dbh->rollback if $oldAutoCommit;
613               return "Illegal payname $payname";
614             };
615     ($payfirst, $paylast) = ($1, $2);
616   } else {
617     $payfirst = $cust_main->getfield('first');
618     $paylast = $cust_main->getfield('last');
619     $payname =  "$payfirst $paylast";
620   }
621
622   my @invoicing_list = grep { $_ ne 'POST' } $cust_main->invoicing_list;
623   if ( $conf->exists('emailinvoiceauto')
624        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
625     push @invoicing_list, $cust_main->default_invoicing_list;
626   }
627   my $email = $invoicing_list[0];
628
629   my( $action1, $action2 ) = split(/\s*\,\s*/, $bop_action );
630
631   my $description = 'Internet Services';
632   if ( $conf->exists('business-onlinepayment-description') ) {
633     my $dtempl = $conf->config('business-onlinepayment-description');
634
635     my $agent_obj = $cust_main->agent
636       or die "can't retreive agent for $cust_main (agentnum ".
637              $cust_main->agentnum. ")";
638     my $agent = $agent_obj->agent;
639     my $pkgs = join(', ',
640       map { $_->cust_pkg->part_pkg->pkg }
641         grep { $_->pkgnum } $self->cust_bill_pkg
642     );
643     $description = eval qq("$dtempl");
644
645   }
646   
647   my $transaction =
648     new Business::OnlinePayment( $bop_processor, @bop_options );
649   $transaction->content(
650     'type'           => 'CC',
651     'login'          => $bop_login,
652     'password'       => $bop_password,
653     'action'         => $action1,
654     'description'    => $description,
655     'amount'         => $amount,
656     'invoice_number' => $self->invnum,
657     'customer_id'    => $self->custnum,
658     'last_name'      => $paylast,
659     'first_name'     => $payfirst,
660     'name'           => $payname,
661     'address'        => $address,
662     'city'           => $cust_main->city,
663     'state'          => $cust_main->state,
664     'zip'            => $cust_main->zip,
665     'country'        => $cust_main->country,
666     'card_number'    => $cust_main->payinfo,
667     'expiration'     => $exp,
668     'referer'        => 'http://cleanwhisker.420.am/',
669     'email'          => $email,
670     'phone'          => $cust_main->daytime || $cust_main->night,
671   );
672   $transaction->submit();
673
674   if ( $transaction->is_success() && $action2 ) {
675     my $auth = $transaction->authorization;
676     my $ordernum = $transaction->order_number;
677
678     #warn "********* $auth ***********\n";
679     #warn "********* $ordernum ***********\n";
680     my $capture =
681       new Business::OnlinePayment( $bop_processor, @bop_options );
682
683     $capture->content(
684       action         => $action2,
685       login          => $bop_login,
686       password       => $bop_password,
687       order_number   => $ordernum,
688       amount         => $amount,
689       authorization  => $auth,
690       description    => $description,
691     );
692
693     $capture->submit();
694
695     unless ( $capture->is_success ) {
696       my $e = "Authorization sucessful but capture failed, invnum #".
697               $self->invnum. ': '.  $capture->result_code.
698               ": ". $capture->error_message;
699       warn $e;
700       return $e;
701     }
702
703   }
704
705   if ( $transaction->is_success() ) {
706
707     my $cust_pay = new FS::cust_pay ( {
708        'invnum'   => $self->invnum,
709        'paid'     => $amount,
710        '_date'     => '',
711        'payby'    => 'CARD',
712        'payinfo'  => $cust_main->payinfo,
713        'paybatch' => "$processor:". $transaction->authorization,
714     } );
715     my $error = $cust_pay->insert;
716     if ( $error ) {
717       # gah, even with transactions.
718       my $e = 'WARNING: Card debited but database not updated - '.
719               'error applying payment, invnum #' . $self->invnum.
720               " ($processor): $error";
721       warn $e;
722       return $e;
723     } else {
724       return '';
725     }
726   #} elsif ( $options{'report_badcard'} ) {
727   } else {
728
729     my $perror = "$processor error, invnum #". $self->invnum. ': '.
730                  $transaction->result_code. ": ". $transaction->error_message;
731
732     if ( $conf->exists('emaildecline')
733          && grep { $_ ne 'POST' } $cust_main->invoicing_list
734     ) {
735       my @templ = $conf->config('declinetemplate');
736       my $template = new Text::Template (
737         TYPE   => 'ARRAY',
738         SOURCE => [ map "$_\n", @templ ],
739       ) or return "($perror) can't create template: $Text::Template::ERROR";
740       $template->compile()
741         or return "($perror) can't compile template: $Text::Template::ERROR";
742
743       my $templ_hash = { error => $transaction->error_message };
744
745       #false laziness w/FS::cust_pay::delete & fs_signup_server && ::send
746       $ENV{MAILADDRESS} = $invoice_from;
747       my $header = new Mail::Header ( [
748         "From: $invoice_from",
749         "To: ". join(', ', grep { $_ ne 'POST' } $cust_main->invoicing_list ),
750         "Sender: $invoice_from",
751         "Reply-To: $invoice_from",
752         "Date: ". time2str("%a, %d %b %Y %X %z", time),
753         "Subject: Your credit card could not be processed",
754       ] );
755       my $message = new Mail::Internet (
756         'Header' => $header,
757         'Body' => [ $template->fill_in(HASH => $templ_hash) ],
758       );
759       $!=0;
760       $message->smtpsend( Host => $smtpmachine )
761         or $message->smtpsend( Host => $smtpmachine, Debug => 1 )
762           or return "($perror) (customer # ". $self->custnum.
763             ") can't send card decline email to ".
764             join(', ', grep { $_ ne 'POST' } $cust_main->invoicing_list ).
765             " via server $smtpmachine with SMTP: $!";
766     }
767   
768     return $perror;
769   }
770
771 }
772
773 =item realtime_card_cybercash
774
775 Attempts to pay this invoice with the CyberCash CashRegister realtime gateway.
776
777 =cut
778
779 sub realtime_card_cybercash {
780   my $self = shift;
781   my $cust_main = $self->cust_main;
782   my $amount = $self->owed;
783
784   return "CyberCash CashRegister real-time card processing not enabled!"
785     unless $processor eq 'cybercash3.2';
786
787   my $address = $cust_main->address1;
788   $address .= ", ". $cust_main->address2 if $cust_main->address2;
789
790   #fix exp. date
791   #$cust_main->paydate =~ /^(\d+)\/\d*(\d{2})$/;
792   $cust_main->paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
793   my $exp = "$2/$1";
794
795   #
796
797   my $paybatch = $self->invnum. 
798                   '-' . time2str("%y%m%d%H%M%S", time);
799
800   my $payname = $cust_main->payname ||
801                 $cust_main->getfield('first').' '.$cust_main->getfield('last');
802
803   my $country = $cust_main->country eq 'US' ? 'USA' : $cust_main->country;
804
805   my @full_xaction = ( $xaction,
806     'Order-ID'     => $paybatch,
807     'Amount'       => "usd $amount",
808     'Card-Number'  => $cust_main->getfield('payinfo'),
809     'Card-Name'    => $payname,
810     'Card-Address' => $address,
811     'Card-City'    => $cust_main->getfield('city'),
812     'Card-State'   => $cust_main->getfield('state'),
813     'Card-Zip'     => $cust_main->getfield('zip'),
814     'Card-Country' => $country,
815     'Card-Exp'     => $exp,
816   );
817
818   my %result;
819   %result = &CCMckDirectLib3_2::SendCC2_1Server(@full_xaction);
820   
821   if ( $result{'MStatus'} eq 'success' ) { #cybercash smps v.2 or 3
822     my $cust_pay = new FS::cust_pay ( {
823        'invnum'   => $self->invnum,
824        'paid'     => $amount,
825        '_date'     => '',
826        'payby'    => 'CARD',
827        'payinfo'  => $cust_main->payinfo,
828        'paybatch' => "$processor:$paybatch",
829     } );
830     my $error = $cust_pay->insert;
831     if ( $error ) {
832       # gah, even with transactions.
833       my $e = 'WARNING: Card debited but database not updated - '.
834               'error applying payment, invnum #' . $self->invnum.
835               " (CyberCash Order-ID $paybatch): $error";
836       warn $e;
837       return $e;
838     } else {
839       return '';
840     }
841 #  } elsif ( $result{'Mstatus'} ne 'failure-bad-money'
842 #            || $options{'report_badcard'}
843 #          ) {
844   } else {
845      return 'Cybercash error, invnum #' . 
846        $self->invnum. ':'. $result{'MErrMsg'};
847   }
848
849 }
850
851 =item batch_card
852
853 Adds a payment for this invoice to the pending credit card batch (see
854 L<FS::cust_pay_batch>).
855
856 =cut
857
858 sub batch_card {
859   my $self = shift;
860   my $cust_main = $self->cust_main;
861
862   my $cust_pay_batch = new FS::cust_pay_batch ( {
863     'invnum'   => $self->getfield('invnum'),
864     'custnum'  => $cust_main->getfield('custnum'),
865     'last'     => $cust_main->getfield('last'),
866     'first'    => $cust_main->getfield('first'),
867     'address1' => $cust_main->getfield('address1'),
868     'address2' => $cust_main->getfield('address2'),
869     'city'     => $cust_main->getfield('city'),
870     'state'    => $cust_main->getfield('state'),
871     'zip'      => $cust_main->getfield('zip'),
872     'country'  => $cust_main->getfield('country'),
873     'trancode' => 77,
874     'cardnum'  => $cust_main->getfield('payinfo'),
875     'exp'      => $cust_main->getfield('paydate'),
876     'payname'  => $cust_main->getfield('payname'),
877     'amount'   => $self->owed,
878   } );
879   my $error = $cust_pay_batch->insert;
880   die $error if $error;
881
882   '';
883 }
884
885 =item print_text [TIME];
886
887 Returns an text invoice, as a list of lines.
888
889 TIME an optional value used to control the printing of overdue messages.  The
890 default is now.  It isn't the date of the invoice; that's the `_date' field.
891 It is specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
892 L<Time::Local> and L<Date::Parse> for conversion functions.
893
894 =cut
895
896 sub print_text {
897
898   my( $self, $today, $template ) = @_;
899   $today ||= time;
900 #  my $invnum = $self->invnum;
901   my $cust_main = qsearchs('cust_main', { 'custnum', $self->custnum } );
902   $cust_main->payname( $cust_main->first. ' '. $cust_main->getfield('last') )
903     unless $cust_main->payname;
904
905   my( $pr_total, @pr_cust_bill ) = $self->previous; #previous balance
906 #  my( $cr_total, @cr_cust_credit ) = $self->cust_credit; #credits
907   #my $balance_due = $self->owed + $pr_total - $cr_total;
908   my $balance_due = $self->owed + $pr_total;
909
910   #my @collect = ();
911   #my($description,$amount);
912   @buf = ();
913
914   #previous balance
915   foreach ( @pr_cust_bill ) {
916     push @buf, [
917       "Previous Balance, Invoice #". $_->invnum. 
918                  " (". time2str("%x",$_->_date). ")",
919       $money_char. sprintf("%10.2f",$_->owed)
920     ];
921   }
922   if (@pr_cust_bill) {
923     push @buf,['','-----------'];
924     push @buf,[ 'Total Previous Balance',
925                 $money_char. sprintf("%10.2f",$pr_total ) ];
926     push @buf,['',''];
927   }
928
929   #new charges
930   foreach ( $self->cust_bill_pkg ) {
931
932     if ( $_->pkgnum ) {
933
934       my($cust_pkg)=qsearchs('cust_pkg', { 'pkgnum', $_->pkgnum } );
935       my($part_pkg)=qsearchs('part_pkg',{'pkgpart'=>$cust_pkg->pkgpart});
936       my($pkg)=$part_pkg->pkg;
937
938       if ( $_->setup != 0 ) {
939         push @buf, [ "$pkg Setup", $money_char. sprintf("%10.2f",$_->setup) ];
940         push @buf,
941           map { [ "  ". $_->[0]. ": ". $_->[1], '' ] } $cust_pkg->labels;
942       }
943
944       if ( $_->recur != 0 ) {
945         push @buf, [
946           "$pkg (" . time2str("%x",$_->sdate) . " - " .
947                                 time2str("%x",$_->edate) . ")",
948           $money_char. sprintf("%10.2f",$_->recur)
949         ];
950         push @buf,
951           map { [ "  ". $_->[0]. ": ". $_->[1], '' ] } $cust_pkg->labels;
952       }
953
954     } else { #pkgnum Tax
955       push @buf,["Tax", $money_char. sprintf("%10.2f",$_->setup) ] 
956         if $_->setup != 0;
957     }
958   }
959
960   push @buf,['','-----------'];
961   push @buf,['Total New Charges',
962              $money_char. sprintf("%10.2f",$self->charged) ];
963   push @buf,['',''];
964
965   push @buf,['','-----------'];
966   push @buf,['Total Charges',
967              $money_char. sprintf("%10.2f",$self->charged + $pr_total) ];
968   push @buf,['',''];
969
970   #credits
971   foreach ( $self->cust_credited ) {
972
973     #something more elaborate if $_->amount ne $_->cust_credit->credited ?
974
975     my $reason = substr($_->cust_credit->reason,0,32);
976     $reason .= '...' if length($reason) < length($_->cust_credit->reason);
977     $reason = " ($reason) " if $reason;
978     push @buf,[
979       "Credit #". $_->crednum. " (". time2str("%x",$_->cust_credit->_date) .")".
980         $reason,
981       $money_char. sprintf("%10.2f",$_->amount)
982     ];
983   }
984   #foreach ( @cr_cust_credit ) {
985   #  push @buf,[
986   #    "Credit #". $_->crednum. " (" . time2str("%x",$_->_date) .")",
987   #    $money_char. sprintf("%10.2f",$_->credited)
988   #  ];
989   #}
990
991   #get & print payments
992   foreach ( $self->cust_bill_pay ) {
993
994     #something more elaborate if $_->amount ne ->cust_pay->paid ?
995
996     push @buf,[
997       "Payment received ". time2str("%x",$_->cust_pay->_date ),
998       $money_char. sprintf("%10.2f",$_->amount )
999     ];
1000   }
1001
1002   #balance due
1003   push @buf,['','-----------'];
1004   push @buf,['Balance Due', $money_char. 
1005     sprintf("%10.2f", $balance_due ) ];
1006
1007   #create the template
1008   my $templatefile = 'invoice_template';
1009   $templatefile .= "_$template" if $template;
1010   my @invoice_template = $conf->config($templatefile)
1011   or die "cannot load config file $templatefile";
1012   $invoice_lines = 0;
1013   my $wasfunc = 0;
1014   foreach ( grep /invoice_lines\(\d+\)/, @invoice_template ) { #kludgy
1015     /invoice_lines\((\d+)\)/;
1016     $invoice_lines += $1;
1017     $wasfunc=1;
1018   }
1019   die "no invoice_lines() functions in template?" unless $wasfunc;
1020   my $invoice_template = new Text::Template (
1021     TYPE   => 'ARRAY',
1022     SOURCE => [ map "$_\n", @invoice_template ],
1023   ) or die "can't create new Text::Template object: $Text::Template::ERROR";
1024   $invoice_template->compile()
1025     or die "can't compile template: $Text::Template::ERROR";
1026
1027   #setup template variables
1028   package FS::cust_bill::_template; #!
1029   use vars qw( $invnum $date $page $total_pages @address $overdue @buf );
1030
1031   $invnum = $self->invnum;
1032   $date = $self->_date;
1033   $page = 1;
1034
1035   if ( $FS::cust_bill::invoice_lines ) {
1036     $total_pages =
1037       int( scalar(@FS::cust_bill::buf) / $FS::cust_bill::invoice_lines );
1038     $total_pages++
1039       if scalar(@FS::cust_bill::buf) % $FS::cust_bill::invoice_lines;
1040   } else {
1041     $total_pages = 1;
1042   }
1043
1044   #format address (variable for the template)
1045   my $l = 0;
1046   @address = ( '', '', '', '', '', '' );
1047   package FS::cust_bill; #!
1048   $FS::cust_bill::_template::address[$l++] =
1049     $cust_main->payname.
1050       ( ( $cust_main->payby eq 'BILL' ) && $cust_main->payinfo
1051         ? " (P.O. #". $cust_main->payinfo. ")"
1052         : ''
1053       )
1054   ;
1055   $FS::cust_bill::_template::address[$l++] = $cust_main->company
1056     if $cust_main->company;
1057   $FS::cust_bill::_template::address[$l++] = $cust_main->address1;
1058   $FS::cust_bill::_template::address[$l++] = $cust_main->address2
1059     if $cust_main->address2;
1060   $FS::cust_bill::_template::address[$l++] =
1061     $cust_main->city. ", ". $cust_main->state. "  ".  $cust_main->zip;
1062   $FS::cust_bill::_template::address[$l++] = $cust_main->country
1063     unless $cust_main->country eq 'US';
1064
1065         #  #overdue? (variable for the template)
1066         #  $FS::cust_bill::_template::overdue = ( 
1067         #    $balance_due > 0
1068         #    && $today > $self->_date 
1069         ##    && $self->printed > 1
1070         #    && $self->printed > 0
1071         #  );
1072
1073   #and subroutine for the template
1074
1075   sub FS::cust_bill::_template::invoice_lines {
1076     my $lines = shift or return @buf;
1077     map { 
1078       scalar(@buf) ? shift @buf : [ '', '' ];
1079     }
1080     ( 1 .. $lines );
1081   }
1082
1083
1084   #and fill it in
1085   $FS::cust_bill::_template::page = 1;
1086   my $lines;
1087   my @collect;
1088   while (@buf) {
1089     push @collect, split("\n",
1090       $invoice_template->fill_in( PACKAGE => 'FS::cust_bill::_template' )
1091     );
1092     $FS::cust_bill::_template::page++;
1093   }
1094
1095   map "$_\n", @collect;
1096
1097 }
1098
1099 =back
1100
1101 =head1 VERSION
1102
1103 $Id: cust_bill.pm,v 1.39 2002-08-30 23:42:47 ivan Exp $
1104
1105 =head1 BUGS
1106
1107 The delete method.
1108
1109 print_text formatting (and some logic :/) is in source, but needs to be
1110 slurped in from a file.  Also number of lines ($=).
1111
1112 missing print_ps for a nice postscript copy (maybe HylaFAX-cover-page-style
1113 or something similar so the look can be completely customized?)
1114
1115 =head1 SEE ALSO
1116
1117 L<FS::Record>, L<FS::cust_main>, L<FS::cust_bill_pay>, L<FS::cust_pay>,
1118 L<FS::cust_bill_pkg>, L<FS::cust_bill_credit>, schema.html from the base
1119 documentation.
1120
1121 =cut
1122
1123 1;
1124