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