RT#34295: Error when attempting to create batch payments
[freeside.git] / FS / FS / cust_main / Billing_Batch.pm
1 package FS::cust_main::Billing_Batch;
2
3 use strict;
4 use vars qw( $conf );
5 use FS::Record qw( qsearch qsearchs dbh );
6 use FS::pay_batch;
7 use FS::cust_pay_batch;
8 use FS::cust_bill_pay_batch;
9
10 install_callback FS::UID sub { 
11   $conf = new FS::Conf;
12   #yes, need it for stuff below (prolly should be cached)
13 };
14
15 =item batch_card OPTION => VALUE...
16
17 Adds a payment for this invoice to the pending credit card batch (see
18 L<FS::cust_pay_batch>), or, if the B<realtime> option is set to a true value,
19 runs the payment using a realtime gateway.
20
21 Options may include:
22
23 B<amount>: the amount to be paid; defaults to the customer's balance minus
24 any payments in transit.
25
26 B<payby>: the payment method; defaults to cust_main.payby
27
28 B<realtime>: runs this as a realtime payment instead of adding it to a 
29 batch.  Deprecated.
30
31 B<invnum>: sets cust_pay_batch.invnum.
32
33 B<address1>, B<address2>, B<city>, B<state>, B<zip>, B<country>: sets 
34 the billing address for the payment; defaults to the customer's billing
35 location.
36
37 B<payinfo>, B<paydate>, B<payname>: sets the payment account, expiration
38 date, and name; defaults to those fields in cust_main.
39
40 =cut
41
42 sub batch_card {
43   my ($self, %options) = @_;
44
45   my $amount;
46   if (exists($options{amount})) {
47     $amount = $options{amount};
48   }else{
49     $amount = sprintf("%.2f", $self->balance - $self->in_transit_payments);
50   }
51   return '' unless $amount > 0;
52   
53   my $invnum = delete $options{invnum};
54
55   #false laziness with Billing_Realtime
56   my @cust_payby = qsearch({
57     'table'     => 'cust_payby',
58     'hashref'   => { 'custnum' => $self->custnum, },
59     'extra_sql' => " AND payby IN ( 'CARD', 'CHEK' ) ",
60     'order_by'  => 'ORDER BY weight ASC',
61   });
62
63   # batch can't try out every one like realtime, just use first one
64   my $cust_payby = $cust_payby[0] || $self; # somewhat dubious
65                                                    
66   my $payby = $options{payby} || $cust_payby->payby;
67
68   if ($options{'realtime'}) {
69     return $self->realtime_bop( FS::payby->payby2bop($payby),
70                                 $amount,
71                                 %options,
72                               );
73   }
74
75   my $oldAutoCommit = $FS::UID::AutoCommit;
76   local $FS::UID::AutoCommit = 0;
77   my $dbh = dbh;
78
79   #this needs to handle mysql as well as Pg, like svc_acct.pm
80   #(make it into a common function if folks need to do batching with mysql)
81   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
82     or return "Cannot lock pay_batch: " . $dbh->errstr;
83
84   my %pay_batch = (
85     'status' => 'O',
86     'payby'  => FS::payby->payby2payment($payby),
87   );
88   $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
89
90   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
91
92   unless ( $pay_batch ) {
93     $pay_batch = new FS::pay_batch \%pay_batch;
94     my $error = $pay_batch->insert;
95     if ( $error ) {
96       $dbh->rollback if $oldAutoCommit;
97       die "error creating new batch: $error\n";
98     }
99   }
100
101   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
102       'batchnum' => $pay_batch->batchnum,
103       'custnum'  => $self->custnum,
104   } );
105
106   foreach (qw( address1 address2 city state zip country latitude longitude
107                payby payinfo paydate payname ))
108   {
109     $options{$_} = '' unless exists($options{$_});
110   }
111
112   my $loc = $self->bill_location;
113
114   my $cust_pay_batch = new FS::cust_pay_batch ( {
115     'batchnum' => $pay_batch->batchnum,
116     'invnum'   => $invnum || 0,                    # is there a better value?
117                                                    # this field should be
118                                                    # removed...
119                                                    # cust_bill_pay_batch now
120     'custnum'  => $self->custnum,
121     'last'     => $self->getfield('last'),
122     'first'    => $self->getfield('first'),
123     'address1' => $options{address1} || $loc->address1,
124     'address2' => $options{address2} || $loc->address2,
125     'city'     => $options{city}     || $loc->city,
126     'state'    => $options{state}    || $loc->state,
127     'zip'      => $options{zip}      || $loc->zip,
128     'country'  => $options{country}  || $loc->country,
129     'payby'    => $options{payby}    || $cust_payby->payby,
130     'payinfo'  => $options{payinfo}  || $cust_payby->payinfo,
131     'exp'      => $options{paydate}  || $cust_payby->paydate,
132     'payname'  => $options{payname}  || $cust_payby->payname,
133     'amount'   => $amount,                         # consolidating
134   } );
135   
136   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
137     if $old_cust_pay_batch;
138
139   my $error;
140   if ($old_cust_pay_batch) {
141     $error = $cust_pay_batch->replace($old_cust_pay_batch)
142   } else {
143     $error = $cust_pay_batch->insert;
144   }
145
146   if ( $error ) {
147     $dbh->rollback if $oldAutoCommit;
148     die $error;
149   }
150
151   my $unapplied =   $self->total_unapplied_credits
152                   + $self->total_unapplied_payments
153                   + $self->in_transit_payments;
154   foreach my $cust_bill ($self->open_cust_bill) {
155     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
156     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
157       'invnum' => $cust_bill->invnum,
158       'paybatchnum' => $cust_pay_batch->paybatchnum,
159       'amount' => $cust_bill->owed,
160       '_date' => time,
161     };
162     if ($unapplied >= $cust_bill_pay_batch->amount){
163       $unapplied -= $cust_bill_pay_batch->amount;
164       next;
165     }else{
166       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
167                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
168     }
169     $error = $cust_bill_pay_batch->insert;
170     if ( $error ) {
171       $dbh->rollback if $oldAutoCommit;
172       die $error;
173     }
174   }
175
176   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
177   '';
178 }
179
180 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
181
182 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
183
184 Optionally, a list or hashref of additional arguments to the qsearch call can
185 be passed.
186
187 =cut
188
189 sub cust_pay_batch {
190   my $self = shift;
191   my $opt = ref($_[0]) ? shift : { @_ };
192
193   #return $self->num_cust_statement unless wantarray || keys %$opt;
194
195   $opt->{'table'} = 'cust_pay_batch';
196   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
197   $opt->{'hashref'}{'custnum'} = $self->custnum;
198   $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
199
200   map { $_ } #behavior of sort undefined in scalar context
201     sort { $a->paybatchnum <=> $b->paybatchnum }
202       qsearch($opt);
203 }
204
205 =item in_transit_payments
206
207 Returns the total of requests for payments for this customer pending in 
208 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
209
210 =cut
211
212 sub in_transit_payments {
213   my $self = shift;
214   my $in_transit_payments = 0;
215   foreach my $pay_batch ( qsearch('pay_batch', {
216     'status' => 'I',
217   } ) ) {
218     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
219       'batchnum' => $pay_batch->batchnum,
220       'custnum' => $self->custnum,
221     } ) ) {
222       $in_transit_payments += $cust_pay_batch->amount;
223     }
224   }
225   sprintf( "%.2f", $in_transit_payments );
226 }
227
228 1;