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