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