Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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   my $payby = $options{payby} || $self->payby;  #still dubious
55
56   if ($options{'realtime'}) {
57     return $self->realtime_bop( FS::payby->payby2bop($self->payby),
58                                 $amount,
59                                 %options,
60                               );
61   }
62
63   my $oldAutoCommit = $FS::UID::AutoCommit;
64   local $FS::UID::AutoCommit = 0;
65   my $dbh = dbh;
66
67   #this needs to handle mysql as well as Pg, like svc_acct.pm
68   #(make it into a common function if folks need to do batching with mysql)
69   $dbh->do("LOCK TABLE pay_batch IN SHARE ROW EXCLUSIVE MODE")
70     or return "Cannot lock pay_batch: " . $dbh->errstr;
71
72   my %pay_batch = (
73     'status' => 'O',
74     'payby'  => FS::payby->payby2payment($payby),
75   );
76   $pay_batch{agentnum} = $self->agentnum if $conf->exists('batch-spoolagent');
77
78   my $pay_batch = qsearchs( 'pay_batch', \%pay_batch );
79
80   unless ( $pay_batch ) {
81     $pay_batch = new FS::pay_batch \%pay_batch;
82     my $error = $pay_batch->insert;
83     if ( $error ) {
84       $dbh->rollback if $oldAutoCommit;
85       die "error creating new batch: $error\n";
86     }
87   }
88
89   my $old_cust_pay_batch = qsearchs('cust_pay_batch', {
90       'batchnum' => $pay_batch->batchnum,
91       'custnum'  => $self->custnum,
92   } );
93
94   foreach (qw( address1 address2 city state zip country latitude longitude
95                payby payinfo paydate payname ))
96   {
97     $options{$_} = '' unless exists($options{$_});
98   }
99
100   my $loc = $self->bill_location;
101
102   my $cust_pay_batch = new FS::cust_pay_batch ( {
103     'batchnum' => $pay_batch->batchnum,
104     'invnum'   => $invnum || 0,                    # is there a better value?
105                                                    # this field should be
106                                                    # removed...
107                                                    # cust_bill_pay_batch now
108     'custnum'  => $self->custnum,
109     'last'     => $self->getfield('last'),
110     'first'    => $self->getfield('first'),
111     'address1' => $options{address1} || $loc->address1,
112     'address2' => $options{address2} || $loc->address2,
113     'city'     => $options{city}     || $loc->city,
114     'state'    => $options{state}    || $loc->state,
115     'zip'      => $options{zip}      || $loc->zip,
116     'country'  => $options{country}  || $loc->country,
117     'payby'    => $options{payby}    || $self->payby,
118     'payinfo'  => $options{payinfo}  || $self->payinfo,
119     'exp'      => $options{paydate}  || $self->paydate,
120     'payname'  => $options{payname}  || $self->payname,
121     'amount'   => $amount,                         # consolidating
122   } );
123   
124   $cust_pay_batch->paybatchnum($old_cust_pay_batch->paybatchnum)
125     if $old_cust_pay_batch;
126
127   my $error;
128   if ($old_cust_pay_batch) {
129     $error = $cust_pay_batch->replace($old_cust_pay_batch)
130   } else {
131     $error = $cust_pay_batch->insert;
132   }
133
134   if ( $error ) {
135     $dbh->rollback if $oldAutoCommit;
136     die $error;
137   }
138
139   my $unapplied =   $self->total_unapplied_credits
140                   + $self->total_unapplied_payments
141                   + $self->in_transit_payments;
142   foreach my $cust_bill ($self->open_cust_bill) {
143     #$dbh->commit or die $dbh->errstr if $oldAutoCommit;
144     my $cust_bill_pay_batch = new FS::cust_bill_pay_batch {
145       'invnum' => $cust_bill->invnum,
146       'paybatchnum' => $cust_pay_batch->paybatchnum,
147       'amount' => $cust_bill->owed,
148       '_date' => time,
149     };
150     if ($unapplied >= $cust_bill_pay_batch->amount){
151       $unapplied -= $cust_bill_pay_batch->amount;
152       next;
153     }else{
154       $cust_bill_pay_batch->amount(sprintf ( "%.2f", 
155                                    $cust_bill_pay_batch->amount - $unapplied ));      $unapplied = 0;
156     }
157     $error = $cust_bill_pay_batch->insert;
158     if ( $error ) {
159       $dbh->rollback if $oldAutoCommit;
160       die $error;
161     }
162   }
163
164   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
165   '';
166 }
167
168 =item cust_pay_batch [ OPTION => VALUE... | EXTRA_QSEARCH_PARAMS_HASHREF ]
169
170 Returns all batched payments (see L<FS::cust_pay_batch>) for this customer.
171
172 Optionally, a list or hashref of additional arguments to the qsearch call can
173 be passed.
174
175 =cut
176
177 sub cust_pay_batch {
178   my $self = shift;
179   my $opt = ref($_[0]) ? shift : { @_ };
180
181   #return $self->num_cust_statement unless wantarray || keys %$opt;
182
183   $opt->{'table'} = 'cust_pay_batch';
184   $opt->{'hashref'} ||= {}; #i guess it would autovivify anyway...
185   $opt->{'hashref'}{'custnum'} = $self->custnum;
186   $opt->{'order_by'} ||= 'ORDER BY paybatchnum ASC';
187
188   map { $_ } #behavior of sort undefined in scalar context
189     sort { $a->paybatchnum <=> $b->paybatchnum }
190       qsearch($opt);
191 }
192
193 =item in_transit_payments
194
195 Returns the total of requests for payments for this customer pending in 
196 batches in transit to the bank.  See L<FS::pay_batch> and L<FS::cust_pay_batch>
197
198 =cut
199
200 sub in_transit_payments {
201   my $self = shift;
202   my $in_transit_payments = 0;
203   foreach my $pay_batch ( qsearch('pay_batch', {
204     'status' => 'I',
205   } ) ) {
206     foreach my $cust_pay_batch ( qsearch('cust_pay_batch', {
207       'batchnum' => $pay_batch->batchnum,
208       'custnum' => $self->custnum,
209     } ) ) {
210       $in_transit_payments += $cust_pay_batch->amount;
211     }
212   }
213   sprintf( "%.2f", $in_transit_payments );
214 }
215
216 1;