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