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