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