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