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