fix payment receipts when payment_receipt_msgnum is unconfigured
[freeside.git] / FS / FS / cust_pay.pm
1 package FS::cust_pay;
2
3 use strict;
4 use base qw( FS::otaker_Mixin FS::payinfo_transaction_Mixin FS::cust_main_Mixin
5              FS::Record );
6 use vars qw( $DEBUG $me $conf @encrypted_fields
7              $unsuspendauto $ignore_noapply 
8            );
9 use Date::Format;
10 use Business::CreditCard;
11 use Text::Template;
12 use FS::UID qw( getotaker );
13 use FS::Misc qw( send_email );
14 use FS::Record qw( dbh qsearch qsearchs );
15 use FS::payby;
16 use FS::cust_main_Mixin;
17 use FS::payinfo_transaction_Mixin;
18 use FS::cust_bill;
19 use FS::cust_bill_pay;
20 use FS::cust_pay_refund;
21 use FS::cust_main;
22 use FS::cust_pkg;
23 use FS::cust_pay_void;
24
25 $DEBUG = 0;
26
27 $me = '[FS::cust_pay]';
28
29 $ignore_noapply = 0;
30
31 #ask FS::UID to run this stuff for us later
32 FS::UID->install_callback( sub { 
33   $conf = new FS::Conf;
34   $unsuspendauto = $conf->exists('unsuspendauto');
35 } );
36
37 @encrypted_fields = ('payinfo');
38
39 =head1 NAME
40
41 FS::cust_pay - Object methods for cust_pay objects
42
43 =head1 SYNOPSIS
44
45   use FS::cust_pay;
46
47   $record = new FS::cust_pay \%hash;
48   $record = new FS::cust_pay { 'column' => 'value' };
49
50   $error = $record->insert;
51
52   $error = $new_record->replace($old_record);
53
54   $error = $record->delete;
55
56   $error = $record->check;
57
58 =head1 DESCRIPTION
59
60 An FS::cust_pay object represents a payment; the transfer of money from a
61 customer.  FS::cust_pay inherits from FS::Record.  The following fields are
62 currently supported:
63
64 =over 4
65
66 =item paynum
67
68 primary key (assigned automatically for new payments)
69
70 =item custnum
71
72 customer (see L<FS::cust_main>)
73
74 =item _date
75
76 specified as a UNIX timestamp; see L<perlfunc/"time">.  Also see
77 L<Time::Local> and L<Date::Parse> for conversion functions.
78
79 =item paid
80
81 Amount of this payment
82
83 =item usernum
84
85 order taker (see L<FS::access_user>)
86
87 =item payby
88
89 Payment Type (See L<FS::payinfo_Mixin> for valid payby values)
90
91 =item payinfo
92
93 Payment Information (See L<FS::payinfo_Mixin> for data format)
94
95 =item paymask
96
97 Masked payinfo (See L<FS::payinfo_Mixin> for how this works)
98
99 =item paybatch
100
101 text field for tracking card processing or other batch grouping
102
103 =item payunique
104
105 Optional unique identifer to prevent duplicate transactions.
106
107 =item closed
108
109 books closed flag, empty or `Y'
110
111 =item pkgnum
112
113 Desired pkgnum when using experimental package balances.
114
115 =back
116
117 =head1 METHODS
118
119 =over 4 
120
121 =item new HASHREF
122
123 Creates a new payment.  To add the payment to the databse, see L<"insert">.
124
125 =cut
126
127 sub table { 'cust_pay'; }
128 sub cust_linked { $_[0]->cust_main_custnum; } 
129 sub cust_unlinked_msg {
130   my $self = shift;
131   "WARNING: can't find cust_main.custnum ". $self->custnum.
132   ' (cust_pay.paynum '. $self->paynum. ')';
133 }
134
135 =item insert [ OPTION => VALUE ... ]
136
137 Adds this payment to the database.
138
139 For backwards-compatibility and convenience, if the additional field invnum
140 is defined, an FS::cust_bill_pay record for the full amount of the payment
141 will be created.  In this case, custnum is optional.
142
143 A hash of optional arguments may be passed.  Currently "manual" is supported.
144 If true, a payment receipt is sent instead of a statement when
145 'payment_receipt_email' configuration option is set.
146
147 =cut
148
149 sub insert {
150   my($self, %options) = @_;
151
152   local $SIG{HUP} = 'IGNORE';
153   local $SIG{INT} = 'IGNORE';
154   local $SIG{QUIT} = 'IGNORE';
155   local $SIG{TERM} = 'IGNORE';
156   local $SIG{TSTP} = 'IGNORE';
157   local $SIG{PIPE} = 'IGNORE';
158
159   my $oldAutoCommit = $FS::UID::AutoCommit;
160   local $FS::UID::AutoCommit = 0;
161   my $dbh = dbh;
162
163   my $cust_bill;
164   if ( $self->invnum ) {
165     $cust_bill = qsearchs('cust_bill', { 'invnum' => $self->invnum } )
166       or do {
167         $dbh->rollback if $oldAutoCommit;
168         return "Unknown cust_bill.invnum: ". $self->invnum;
169       };
170     $self->custnum($cust_bill->custnum );
171   }
172
173   my $error = $self->check;
174   return $error if $error;
175
176   my $cust_main = $self->cust_main;
177   my $old_balance = $cust_main->balance;
178
179   $error = $self->SUPER::insert;
180   if ( $error ) {
181     $dbh->rollback if $oldAutoCommit;
182     return "error inserting cust_pay: $error";
183   }
184
185   if ( $self->invnum ) {
186     my $cust_bill_pay = new FS::cust_bill_pay {
187       'invnum' => $self->invnum,
188       'paynum' => $self->paynum,
189       'amount' => $self->paid,
190       '_date'  => $self->_date,
191     };
192     $error = $cust_bill_pay->insert(%options);
193     if ( $error ) {
194       if ( $ignore_noapply ) {
195         warn "warning: error inserting cust_bill_pay: $error ".
196              "(ignore_noapply flag set; inserting cust_pay record anyway)\n";
197       } else {
198         $dbh->rollback if $oldAutoCommit;
199         return "error inserting cust_bill_pay: $error";
200       }
201     }
202   }
203
204   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
205
206   #false laziness w/ cust_credit::insert
207   if ( $unsuspendauto && $old_balance && $cust_main->balance <= 0 ) {
208     my @errors = $cust_main->unsuspend;
209     #return 
210     # side-fx with nested transactions?  upstack rolls back?
211     warn "WARNING:Errors unsuspending customer ". $cust_main->custnum. ": ".
212          join(' / ', @errors)
213       if @errors;
214   }
215   #eslaf
216
217   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
218
219   #payment receipt
220   my $trigger = $conf->config('payment_receipt-trigger') || 'cust_pay';
221   if ( $trigger eq 'cust_pay' ) {
222     my $error = $self->send_receipt(
223       'manual'    => $options{'manual'},
224       'cust_bill' => $cust_bill,
225       'cust_main' => $cust_main,
226     );
227     warn "can't send payment receipt/statement: $error" if $error;
228   }
229
230   '';
231
232 }
233
234 =item void [ REASON ]
235
236 Voids this payment: deletes the payment and all associated applications and
237 adds a record of the voided payment to the FS::cust_pay_void table.
238
239 =cut
240
241 sub void {
242   my $self = shift;
243
244   local $SIG{HUP} = 'IGNORE';
245   local $SIG{INT} = 'IGNORE';
246   local $SIG{QUIT} = 'IGNORE';
247   local $SIG{TERM} = 'IGNORE';
248   local $SIG{TSTP} = 'IGNORE';
249   local $SIG{PIPE} = 'IGNORE';
250
251   my $oldAutoCommit = $FS::UID::AutoCommit;
252   local $FS::UID::AutoCommit = 0;
253   my $dbh = dbh;
254
255   my $cust_pay_void = new FS::cust_pay_void ( {
256     map { $_ => $self->get($_) } $self->fields
257   } );
258   $cust_pay_void->reason(shift) if scalar(@_);
259   my $error = $cust_pay_void->insert;
260   if ( $error ) {
261     $dbh->rollback if $oldAutoCommit;
262     return $error;
263   }
264
265   $error = $self->delete;
266   if ( $error ) {
267     $dbh->rollback if $oldAutoCommit;
268     return $error;
269   }
270
271   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
272
273   '';
274
275 }
276
277 =item delete
278
279 Unless the closed flag is set, deletes this payment and all associated
280 applications (see L<FS::cust_bill_pay> and L<FS::cust_pay_refund>).  In most
281 cases, you want to use the void method instead to leave a record of the
282 deleted payment.
283
284 =cut
285
286 # very similar to FS::cust_credit::delete
287 sub delete {
288   my $self = shift;
289   return "Can't delete closed payment" if $self->closed =~ /^Y/i;
290
291   local $SIG{HUP} = 'IGNORE';
292   local $SIG{INT} = 'IGNORE';
293   local $SIG{QUIT} = 'IGNORE';
294   local $SIG{TERM} = 'IGNORE';
295   local $SIG{TSTP} = 'IGNORE';
296   local $SIG{PIPE} = 'IGNORE';
297
298   my $oldAutoCommit = $FS::UID::AutoCommit;
299   local $FS::UID::AutoCommit = 0;
300   my $dbh = dbh;
301
302   foreach my $app ( $self->cust_bill_pay, $self->cust_pay_refund ) {
303     my $error = $app->delete;
304     if ( $error ) {
305       $dbh->rollback if $oldAutoCommit;
306       return $error;
307     }
308   }
309
310   my $error = $self->SUPER::delete(@_);
311   if ( $error ) {
312     $dbh->rollback if $oldAutoCommit;
313     return $error;
314   }
315
316   if (    $conf->exists('deletepayments')
317        && $conf->config('deletepayments') ne '' ) {
318
319     my $cust_main = $self->cust_main;
320
321     my $error = send_email(
322       'from'    => $conf->config('invoice_from', $self->cust_main->agentnum),
323                                  #invoice_from??? well as good as any
324       'to'      => $conf->config('deletepayments'),
325       'subject' => 'FREESIDE NOTIFICATION: Payment deleted',
326       'body'    => [
327         "This is an automatic message from your Freeside installation\n",
328         "informing you that the following payment has been deleted:\n",
329         "\n",
330         'paynum: '. $self->paynum. "\n",
331         'custnum: '. $self->custnum.
332           " (". $cust_main->last. ", ". $cust_main->first. ")\n",
333         'paid: $'. sprintf("%.2f", $self->paid). "\n",
334         'date: '. time2str("%a %b %e %T %Y", $self->_date). "\n",
335         'payby: '. $self->payby. "\n",
336         'payinfo: '. $self->paymask. "\n",
337         'paybatch: '. $self->paybatch. "\n",
338       ],
339     );
340
341     if ( $error ) {
342       $dbh->rollback if $oldAutoCommit;
343       return "can't send payment deletion notification: $error";
344     }
345
346   }
347
348   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
349
350   '';
351
352 }
353
354 =item replace OLD_RECORD
355
356 You can, but probably shouldn't modify payments...
357
358 =cut
359
360 sub replace {
361   #return "Can't modify payment!"
362   my $self = shift;
363   return "Can't modify closed payment" if $self->closed =~ /^Y/i;
364   $self->SUPER::replace(@_);
365 }
366
367 =item check
368
369 Checks all fields to make sure this is a valid payment.  If there is an error,
370 returns the error, otherwise returns false.  Called by the insert method.
371
372 =cut
373
374 sub check {
375   my $self = shift;
376
377   $self->otaker(getotaker) unless ($self->otaker);
378
379   my $error =
380     $self->ut_numbern('paynum')
381     || $self->ut_numbern('custnum')
382     || $self->ut_numbern('_date')
383     || $self->ut_money('paid')
384     || $self->ut_alphan('otaker')
385     || $self->ut_textn('paybatch')
386     || $self->ut_textn('payunique')
387     || $self->ut_enum('closed', [ '', 'Y' ])
388     || $self->ut_foreign_keyn('pkgnum', 'cust_pkg', 'pkgnum')
389     || $self->payinfo_check()
390   ;
391   return $error if $error;
392
393   return "paid must be > 0 " if $self->paid <= 0;
394
395   return "unknown cust_main.custnum: ". $self->custnum
396     unless $self->invnum
397            || qsearchs( 'cust_main', { 'custnum' => $self->custnum } );
398
399   $self->_date(time) unless $self->_date;
400
401 #i guess not now, with cust_pay_pending, if we actually make it here, we _do_ want to record it
402 #  # UNIQUE index should catch this too, without race conditions, but this
403 #  # should give a better error message the other 99.9% of the time...
404 #  if ( length($self->payunique)
405 #       && qsearchs('cust_pay', { 'payunique' => $self->payunique } ) ) {
406 #    #well, it *could* be a better error message
407 #    return "duplicate transaction".
408 #           " - a payment with unique identifer ". $self->payunique.
409 #           " already exists";
410 #  }
411
412   $self->SUPER::check;
413 }
414
415 =item send_receipt HASHREF | OPTION => VALUE ...
416
417 Sends a payment receipt for this payment..
418
419 Available options:
420
421 =over 4
422
423 =item manual
424
425 Flag indicating the payment is being made manually.
426
427 =item cust_bill
428
429 Invoice (FS::cust_bill) object.  If not specified, the most recent invoice
430 will be assumed.
431
432 =item cust_main
433
434 Customer (FS::cust_main) object (for efficiency).
435
436 =back
437
438 =cut
439
440 sub send_receipt {
441   my $self = shift;
442   my $opt = ref($_[0]) ? shift : { @_ };
443
444   my $cust_bill = $opt->{'cust_bill'};
445   my $cust_main = $opt->{'cust_main'} || $self->cust_main;
446
447   my $conf = new FS::Conf;
448
449   my @invoicing_list = $cust_main->invoicing_list_emailonly;
450   return '' unless @invoicing_list;
451
452   $cust_bill ||= ($cust_main->cust_bill)[-1]; #rather inefficient though?
453
454   if (    ( exists($opt->{'manual'}) && $opt->{'manual'} )
455        || ! $conf->exists('invoice_html_statement') # XXX msg_template
456        || ! $cust_bill
457      ) {
458
459     my $error = '';
460
461     if ( $conf->exists('payment_receipt_msgnum')
462          && $conf->config('payment_receipt_msgnum')
463        )
464     {
465       my $msg_template = 
466           FS::msg_template->by_key($conf->config('payment_receipt_msgnum'));
467       $error = $msg_template->send('cust_main'=> $cust_main, 'object'=> $self);
468
469     } elsif ( $conf->exists('payment_receipt_email') ) {
470       my $receipt_template = new Text::Template (
471         TYPE   => 'ARRAY',
472         SOURCE => [ map "$_\n", $conf->config('payment_receipt_email') ],
473       ) or do {
474         warn "can't create payment receipt template: $Text::Template::ERROR";
475         return '';
476       };
477
478       my $payby = $self->payby;
479       my $payinfo = $self->payinfo;
480       $payby =~ s/^BILL$/Check/ if $payinfo;
481       if ( $payby eq 'CARD' || $payby eq 'CHEK' ) {
482         $payinfo = $self->paymask
483       } else {
484         $payinfo = $self->decrypt($payinfo);
485       }
486       $payby =~ s/^CHEK$/Electronic check/;
487
488       my %fill_in = (
489         'date'         => time2str("%a %B %o, %Y", $self->_date),
490         'name'         => $cust_main->name,
491         'paynum'       => $self->paynum,
492         'paid'         => sprintf("%.2f", $self->paid),
493         'payby'        => ucfirst(lc($payby)),
494         'payinfo'      => $payinfo,
495         'balance'      => $cust_main->balance,
496         'company_name' => $conf->config('company_name', $cust_main->agentnum),
497       );
498
499       if ( $opt->{'cust_pkg'} ) {
500         $fill_in{'pkg'} = $opt->{'cust_pkg'}->part_pkg->pkg;
501         #setup date, other things?
502       }
503
504       $error = send_email(
505         'from'    => $conf->config('invoice_from', $cust_main->agentnum),
506                                    #invoice_from??? well as good as any
507         'to'      => \@invoicing_list,
508         'subject' => 'Payment receipt',
509         'body'    => [ $receipt_template->fill_in( HASH => \%fill_in ) ],
510       );
511
512     } else { # no payment_receipt_msgnum or payment_receipt_email
513
514       my $queue = new FS::queue {
515          'paynum' => $self->paynum,
516          'job'    => 'FS::cust_bill::queueable_email',
517       };
518
519       $queue->insert(
520         'invnum'   => $cust_bill->invnum,
521         'template' => 'statement',
522       );
523     }
524   
525     warn "send_receipt: $error\n" if $error;
526   } #$opt{manual} || no invoice_html_statement || customer has no invoices
527 }
528
529 =item cust_bill_pay
530
531 Returns all applications to invoices (see L<FS::cust_bill_pay>) for this
532 payment.
533
534 =cut
535
536 sub cust_bill_pay {
537   my $self = shift;
538   map { $_ } #return $self->num_cust_bill_pay unless wantarray;
539   sort {    $a->_date  <=> $b->_date
540          || $a->invnum <=> $b->invnum }
541     qsearch( 'cust_bill_pay', { 'paynum' => $self->paynum } )
542   ;
543 }
544
545 =item cust_pay_refund
546
547 Returns all applications of refunds (see L<FS::cust_pay_refund>) to this
548 payment.
549
550 =cut
551
552 sub cust_pay_refund {
553   my $self = shift;
554   map { $_ } #return $self->num_cust_pay_refund unless wantarray;
555   sort { $a->_date <=> $b->_date }
556     qsearch( 'cust_pay_refund', { 'paynum' => $self->paynum } )
557   ;
558 }
559
560
561 =item unapplied
562
563 Returns the amount of this payment that is still unapplied; which is
564 paid minus all payment applications (see L<FS::cust_bill_pay>) and refund
565 applications (see L<FS::cust_pay_refund>).
566
567 =cut
568
569 sub unapplied {
570   my $self = shift;
571   my $amount = $self->paid;
572   $amount -= $_->amount foreach ( $self->cust_bill_pay );
573   $amount -= $_->amount foreach ( $self->cust_pay_refund );
574   sprintf("%.2f", $amount );
575 }
576
577 =item unrefunded
578
579 Returns the amount of this payment that has not been refuned; which is
580 paid minus all  refund applications (see L<FS::cust_pay_refund>).
581
582 =cut
583
584 sub unrefunded {
585   my $self = shift;
586   my $amount = $self->paid;
587   $amount -= $_->amount foreach ( $self->cust_pay_refund );
588   sprintf("%.2f", $amount );
589 }
590
591 =item amount
592
593 Returns the "paid" field.
594
595 =cut
596
597 sub amount {
598   my $self = shift;
599   $self->paid();
600 }
601
602 =back
603
604 =head1 CLASS METHODS
605
606 =over 4
607
608 =item batch_insert CUST_PAY_OBJECT, ...
609
610 Class method which inserts multiple payments.  Takes a list of FS::cust_pay
611 objects.  Returns a list, each element representing the status of inserting the
612 corresponding payment - empty.  If there is an error inserting any payment, the
613 entire transaction is rolled back, i.e. all payments are inserted or none are.
614
615 For example:
616
617   my @errors = FS::cust_pay->batch_insert(@cust_pay);
618   my $num_errors = scalar(grep $_, @errors);
619   if ( $num_errors == 0 ) {
620     #success; all payments were inserted
621   } else {
622     #failure; no payments were inserted.
623   }
624
625 =cut
626
627 sub batch_insert {
628   my $self = shift; #class method
629
630   local $SIG{HUP} = 'IGNORE';
631   local $SIG{INT} = 'IGNORE';
632   local $SIG{QUIT} = 'IGNORE';
633   local $SIG{TERM} = 'IGNORE';
634   local $SIG{TSTP} = 'IGNORE';
635   local $SIG{PIPE} = 'IGNORE';
636
637   my $oldAutoCommit = $FS::UID::AutoCommit;
638   local $FS::UID::AutoCommit = 0;
639   my $dbh = dbh;
640
641   my $errors = 0;
642   
643   my @errors = map {
644     my $error = $_->insert( 'manual' => 1 );
645     if ( $error ) { 
646       $errors++;
647     } else {
648       $_->cust_main->apply_payments;
649     }
650     $error;
651   } @_;
652
653   if ( $errors ) {
654     $dbh->rollback if $oldAutoCommit;
655   } else {
656     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
657   }
658
659   @errors;
660
661 }
662
663 =item unapplied_sql
664
665 Returns an SQL fragment to retreive the unapplied amount.
666
667 =cut 
668
669 sub unapplied_sql {
670   my ($class, $start, $end) = @_;
671   my $bill_start   = $start ? "AND cust_bill_pay._date <= $start"   : '';
672   my $bill_end     = $end   ? "AND cust_bill_pay._date > $end"     : '';
673   my $refund_start = $start ? "AND cust_pay_refund._date <= $start" : '';
674   my $refund_end   = $end   ? "AND cust_pay_refund._date > $end"   : '';
675
676   "paid
677         - COALESCE( 
678                     ( SELECT SUM(amount) FROM cust_bill_pay
679                         WHERE cust_pay.paynum = cust_bill_pay.paynum
680                         $bill_start $bill_end )
681                     ,0
682                   )
683         - COALESCE(
684                     ( SELECT SUM(amount) FROM cust_pay_refund
685                         WHERE cust_pay.paynum = cust_pay_refund.paynum
686                         $refund_start $refund_end )
687                     ,0
688                   )
689   ";
690
691 }
692
693 # _upgrade_data
694 #
695 # Used by FS::Upgrade to migrate to a new database.
696
697 use FS::h_cust_pay;
698
699 sub _upgrade_data {  #class method
700   my ($class, %opts) = @_;
701
702   warn "$me upgrading $class\n" if $DEBUG;
703
704   ##
705   # otaker/ivan upgrade
706   ##
707
708   #not the most efficient, but hey, it only has to run once
709
710   my $where = "WHERE ( otaker IS NULL OR otaker = '' OR otaker = 'ivan' ) ".
711               "  AND usernum IS NULL ".
712               "  AND 0 < ( SELECT COUNT(*) FROM cust_main                 ".
713               "              WHERE cust_main.custnum = cust_pay.custnum ) ";
714
715   my $count_sql = "SELECT COUNT(*) FROM cust_pay $where";
716
717   my $sth = dbh->prepare($count_sql) or die dbh->errstr;
718   $sth->execute or die $sth->errstr;
719   my $total = $sth->fetchrow_arrayref->[0];
720   #warn "$total cust_pay records to update\n"
721   #  if $DEBUG;
722   local($DEBUG) = 2 if $total > 1000; #could be a while, force progress info
723
724   my $count = 0;
725   my $lastprog = 0;
726
727   my @cust_pay = qsearch( {
728       'table'     => 'cust_pay',
729       'hashref'   => {},
730       'extra_sql' => $where,
731       'order_by'  => 'ORDER BY paynum',
732   } );
733
734   foreach my $cust_pay (@cust_pay) {
735
736     my $h_cust_pay = $cust_pay->h_search('insert');
737     if ( $h_cust_pay ) {
738       next if $cust_pay->otaker eq $h_cust_pay->history_user;
739       $cust_pay->otaker($h_cust_pay->history_user);
740     } else {
741       $cust_pay->otaker('legacy');
742     }
743
744     delete $FS::payby::hash{'COMP'}->{cust_pay}; #quelle kludge
745     my $error = $cust_pay->replace;
746
747     if ( $error ) {
748       warn " *** WARNING: Error updating order taker for payment paynum ".
749            $cust_pay->paynun. ": $error\n";
750       next;
751     }
752
753     $FS::payby::hash{'COMP'}->{cust_pay} = ''; #restore it
754
755     $count++;
756     if ( $DEBUG > 1 && $lastprog + 30 < time ) {
757       warn "$me $count/$total (". sprintf('%.2f',100*$count/$total). '%)'. "\n";
758       $lastprog = time;
759     }
760
761   }
762
763   ###
764   # payinfo N/A upgrade
765   ###
766
767   #XXX remove the 'N/A (tokenized)' part (or just this entire thing)
768
769   my @na_cust_pay = qsearch( {
770     'table'     => 'cust_pay',
771     'hashref'   => {}, #could be encrypted# { 'payinfo' => 'N/A' },
772     'extra_sql' => "WHERE ( payinfo = 'N/A' OR paymask = 'N/AA' OR paymask = 'N/A (tokenized)' ) AND payby IN ( 'CARD', 'CHEK' )",
773   } );
774
775   foreach my $na ( @na_cust_pay ) {
776
777     next unless $na->payinfo eq 'N/A';
778
779     my $cust_pay_pending =
780       qsearchs('cust_pay_pending', { 'paynum' => $na->paynum } );
781     unless ( $cust_pay_pending ) {
782       warn " *** WARNING: not-yet recoverable N/A card for payment ".
783            $na->paynum. " (no cust_pay_pending)\n";
784       next;
785     }
786     $na->$_($cust_pay_pending->$_) for qw( payinfo paymask );
787     my $error = $na->replace;
788     if ( $error ) {
789       warn " *** WARNING: Error updating payinfo for payment paynum ".
790            $na->paynun. ": $error\n";
791       next;
792     }
793
794   }
795
796   ###
797   # otaker->usernum upgrade
798   ###
799
800   $class->_upgrade_otaker(%opts);
801
802 }
803
804 =back
805
806 =head1 SUBROUTINES
807
808 =over 4 
809
810 =item batch_import HASHREF
811
812 Inserts new payments.
813
814 =cut
815
816 sub batch_import {
817   my $param = shift;
818
819   my $fh = $param->{filehandle};
820   my $agentnum = $param->{agentnum};
821   my $format = $param->{'format'};
822   my $paybatch = $param->{'paybatch'};
823
824   # here is the agent virtualization
825   my $extra_sql = ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
826
827   my @fields;
828   my $payby;
829   if ( $format eq 'simple' ) {
830     @fields = qw( custnum agent_custid paid payinfo );
831     $payby = 'BILL';
832   } elsif ( $format eq 'extended' ) {
833     die "unimplemented\n";
834     @fields = qw( );
835     $payby = 'BILL';
836   } else {
837     die "unknown format $format";
838   }
839
840   eval "use Text::CSV_XS;";
841   die $@ if $@;
842
843   my $csv = new Text::CSV_XS;
844
845   my $imported = 0;
846
847   local $SIG{HUP} = 'IGNORE';
848   local $SIG{INT} = 'IGNORE';
849   local $SIG{QUIT} = 'IGNORE';
850   local $SIG{TERM} = 'IGNORE';
851   local $SIG{TSTP} = 'IGNORE';
852   local $SIG{PIPE} = 'IGNORE';
853
854   my $oldAutoCommit = $FS::UID::AutoCommit;
855   local $FS::UID::AutoCommit = 0;
856   my $dbh = dbh;
857   
858   my $line;
859   while ( defined($line=<$fh>) ) {
860
861     $csv->parse($line) or do {
862       $dbh->rollback if $oldAutoCommit;
863       return "can't parse: ". $csv->error_input();
864     };
865
866     my @columns = $csv->fields();
867
868     my %cust_pay = (
869       payby    => $payby,
870       paybatch => $paybatch,
871     );
872
873     my $cust_main;
874     foreach my $field ( @fields ) {
875
876       if ( $field eq 'agent_custid'
877         && $agentnum
878         && $columns[0] =~ /\S+/ )
879       {
880
881         my $agent_custid = $columns[0];
882         my %hash = ( 'agent_custid' => $agent_custid,
883                      'agentnum'     => $agentnum,
884                    );
885
886         if ( $cust_pay{'custnum'} !~ /^\s*$/ ) {
887           $dbh->rollback if $oldAutoCommit;
888           return "can't specify custnum with agent_custid $agent_custid";
889         }
890
891         $cust_main = qsearchs({
892                                 'table'     => 'cust_main',
893                                 'hashref'   => \%hash,
894                                 'extra_sql' => $extra_sql,
895                              });
896
897         unless ( $cust_main ) {
898           $dbh->rollback if $oldAutoCommit;
899           return "can't find customer with agent_custid $agent_custid";
900         }
901
902         $field = 'custnum';
903         $columns[0] = $cust_main->custnum;
904       }
905
906       $cust_pay{$field} = shift @columns; 
907     }
908
909     my $cust_pay = new FS::cust_pay( \%cust_pay );
910     my $error = $cust_pay->insert;
911
912     if ( $error ) {
913       $dbh->rollback if $oldAutoCommit;
914       return "can't insert payment for $line: $error";
915     }
916
917     if ( $format eq 'simple' ) {
918       # include agentnum for less surprise?
919       $cust_main = qsearchs({
920                              'table'     => 'cust_main',
921                              'hashref'   => { 'custnum' => $cust_pay->custnum },
922                              'extra_sql' => $extra_sql,
923                            })
924         unless $cust_main;
925
926       unless ( $cust_main ) {
927         $dbh->rollback if $oldAutoCommit;
928         return "can't find customer to which payments apply at line: $line";
929       }
930
931       $error = $cust_main->apply_payments_and_credits;
932       if ( $error ) {
933         $dbh->rollback if $oldAutoCommit;
934         return "can't apply payments to customer for $line: $error";
935       }
936
937     }
938
939     $imported++;
940   }
941
942   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
943
944   return "Empty file!" unless $imported;
945
946   ''; #no error
947
948 }
949
950 =back
951
952 =head1 BUGS
953
954 Delete and replace methods.  
955
956 =head1 SEE ALSO
957
958 L<FS::cust_pay_pending>, L<FS::cust_bill_pay>, L<FS::cust_bill>, L<FS::Record>,
959 schema.html from the base documentation.
960
961 =cut
962
963 1;
964