]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Money.pm
updated the method that determines if a transaction needs to be closed or re-opened
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ / Money.pm
1 # ---------------------------------------------------------------
2 # Copyright (C) 2005  Georgia Public Library Service 
3 # Bill Erickson <billserickson@gmail.com>
4
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
15
16
17 package OpenILS::Application::Circ::Money;
18 use base qw/OpenSRF::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
21 my $apputils = "OpenILS::Application::AppUtils";
22 my $U = "OpenILS::Application::AppUtils";
23
24 use OpenSRF::EX qw(:try);
25 use OpenILS::Perm;
26 use Data::Dumper;
27 use OpenILS::Event;
28 use OpenSRF::Utils::Logger qw/:logger/;
29 use OpenILS::Utils::Editor qw/:funcs/;
30
31 __PACKAGE__->register_method(
32         method  => "make_payments",
33         api_name        => "open-ils.circ.money.payment",
34         notes           => <<"  NOTE");
35         Pass in a structure like so:
36                 { 
37                         cash_drawer: <string>, 
38                         payment_type : <string>, 
39                         note : <string>, 
40                         userid : <id>,
41                         payments: [ 
42                                 [trans_id, amt], 
43                                 [...]
44                         ], 
45                         patron_credit : <credit amt> 
46                 }
47         login must have CREATE_PAYMENT priveleges.
48         If any payments fail, all are reverted back.
49         NOTE
50
51 sub make_payments {
52
53         my( $self, $client, $login, $payments ) = @_;
54
55         my( $user, $trans, $evt );
56
57         ( $user, $evt ) = $apputils->checkses($login);
58         return $evt if $evt;
59         $evt = $apputils->check_perms($user->id, $user->ws_ou, 'CREATE_PAYMENT');
60         return $evt if $evt;
61
62         $logger->info("Creating payment objects: " . Dumper($payments) );
63
64         my $session = $apputils->start_db_session;
65         my $type                = $payments->{payment_type};
66         my $credit      = $payments->{patron_credit} || 0;
67         my $drawer      = $user->wsid;
68         my $userid      = $payments->{userid};
69         my $note                = $payments->{note};
70         my $cc_type = $payments->{cc_type} || 'n/a';
71         my $cc_number           = $payments->{cc_number} || 'n/a';
72         my $expire_month        = $payments->{expire_month};
73         my $expire_year = $payments->{expire_year};
74         my $approval_code = $payments->{approval_code} || 'n/a';
75         my $check_number        = $payments->{check_number} || 'n/a';
76
77         for my $pay (@{$payments->{payments}}) {
78
79                 my $transid = $pay->[0];
80                 my $amount = $pay->[1];
81                 ($trans, $evt) = $apputils->fetch_open_billable_transaction($transid);
82                 return $evt if $evt;
83
84                 if($trans->usr != $userid) { # Do we need to restrict this in some way ??
85                         $logger->info( " * User $userid is making a payment for " . 
86                                 "a different user: " .  $trans->usr . ' for transaction ' . $trans->id  );
87                 }
88
89                 if($type eq 'credit_payment') {
90                         $credit -= $amount;
91                         $logger->activity("user ".$user->id." reducing patron credit by ".
92                                 "$credit for making a credit_payment on transaction ".$trans->id);
93                 }
94
95
96                 # A negative payment is a refund.  If the refund causes the transaction 
97                 # balance to exceed 0 dollars, we are in effect loaning the patron
98                 # money.  This is not allowed.
99                 if( $amount < 0 and ($trans->balance_owed - $amount > 0) ) {
100                         return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
101                 }
102
103                 my $payobj = "Fieldmapper::money::$type";
104                 $payobj = $payobj->new;
105
106                 $payobj->amount($amount);
107                 $payobj->amount_collected($amount);
108                 $payobj->accepting_usr($user->id);
109                 $payobj->xact($transid);
110                 $payobj->note($note);
111
112                 if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
113                 if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_type); }
114                 if ($payobj->has_field('cc_number')) { $payobj->cc_number($cc_number); }
115                 if ($payobj->has_field('expire_month')) { $payobj->expire_month($expire_month); }
116                 if ($payobj->has_field('expire_year')) { $payobj->expire_year($expire_year); }
117                 if ($payobj->has_field('approval_code')) { $payobj->approval_code($approval_code); }
118                 if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
119                 
120                 # update the transaction if it's done 
121                 if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
122
123                         # Any overpay on this transaction goes directly into patron credit 
124                         $cred = -$cred;
125                         $credit += $cred;
126                         $logger->activity("user ".$user->id." applying credit ".
127                                 "of $cred on transaction ".$trans->id. " because of overpayment");
128
129                         $logger->debug("Transactin " . $trans->id . ' is complete');
130                         $trans = $session->request(
131                                 "open-ils.storage.direct.money.billable_transaction.retrieve", $transid )->gather(1);
132
133                         # If this is a circulation, we can't close the transaction unless stop_fines is set
134                         my $circ = $session->request(
135                                 'open-ils.storage.direct.action.circulation.retrieve', $transid )->gather(1);
136
137                         if( !$circ || $circ->stop_fines ) {
138
139                                 $trans->xact_finish("now");
140
141                                 use Data::Dumper;
142                                 warn Dumper($trans);
143
144                                 warn "calling open-ils.storage.direct.money.billable_transaction.update\n";
145
146                                 my $s = $session->request(
147                                         "open-ils.storage.direct.money.billable_transaction.update", $trans )->gather(1);
148         
149                                 if(!$s) { throw OpenSRF::EX::ERROR 
150                                         ("Error updating billable_xact in circ.money.payment"); }
151                         }
152                 }
153
154
155                 $logger->debug("Creating new $payobj for \$$amount\n");
156
157                 my $s = $session->request(
158                         "open-ils.storage.direct.money.$type.create", $payobj )->gather(1);
159                 if(!$s) { throw OpenSRF::EX::ERROR ("Error creating new $type"); }
160
161         }
162
163
164         $logger->activity("user ".$user->id." applying total ".
165                 "credit of $credit to user $userid") if $credit != 0;
166
167         $evt = _update_patron_credit( $session, $userid, $credit );
168         return $evt if $evt;
169
170         $apputils->commit_db_session($session);
171
172         $client->respond_complete(1);   
173
174         # ------------------------------------------------------------------------------
175         # Update the patron penalty info in the DB
176         # ------------------------------------------------------------------------------
177         $U->update_patron_penalties( 
178                 authtoken => $login,
179                 patronid  => $userid,
180         );
181
182         return undef;
183 }
184
185
186 sub _update_patron_credit {
187         my( $session, $userid, $credit ) = @_;
188         #return if $credit <= 0;
189
190         my $patron = $session->request( 
191                 'open-ils.storage.direct.actor.user.retrieve', $userid )->gather(1);
192
193         $patron->credit_forward_balance( 
194                 $patron->credit_forward_balance + $credit);
195
196         if( $patron->credit_forward_balance < 0 ) {
197                 return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE');
198         }
199         
200         $logger->info("Total patron credit for $userid is now " . $patron->credit_forward_balance );
201
202         $session->request( 
203                 'open-ils.storage.direct.actor.user.update', $patron )->gather(1);
204
205         return undef;
206 }
207
208
209 __PACKAGE__->register_method(
210         method  => "retrieve_payments",
211         api_name        => "open-ils.circ.money.payment.retrieve.all",
212         notes           => "Returns a list of payments attached to a given transaction"
213         );
214         
215 sub retrieve_payments {
216         my( $self, $client, $login, $transid ) = @_;
217
218         my( $staff, $evt ) =  
219                 $apputils->checksesperm($login, 'VIEW_TRANSACTION');
220         return $evt if $evt;
221
222         # XXX the logic here is wrong.. we need to check the owner of the transaction
223         # to make sure the requestor has access
224
225         return $apputils->simplereq(
226                 'open-ils.storage',
227                 'open-ils.storage.direct.money.payment.search.xact.atomic', $transid );
228 }
229
230
231
232 __PACKAGE__->register_method(
233         method  => "create_grocery_bill",
234         api_name        => "open-ils.circ.money.grocery.create",
235         notes           => <<"  NOTE");
236         Creates a new grocery transaction using the transaction object provided
237         PARAMS: (login_session, money.grocery (mg) object)
238         NOTE
239
240 sub create_grocery_bill {
241         my( $self, $client, $login, $transaction ) = @_;
242
243         my( $staff, $evt ) = $apputils->checkses($login);
244         return $evt if $evt;
245         $evt = $apputils->check_perms($staff->id, 
246                 $transaction->billing_location, 'CREATE_TRANSACTION' );
247         return $evt if $evt;
248
249
250         $logger->activity("Creating grocery bill " . Dumper($transaction) );
251
252         $transaction->clear_id;
253         my $session = $apputils->start_db_session;
254         my $transid = $session->request(
255                 'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
256
257         throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
258
259         $logger->debug("Created new grocery transaction $transid");
260         
261         $apputils->commit_db_session($session);
262
263         return $transid;
264 }
265
266 __PACKAGE__->register_method(
267         method  => "billing_items",
268         api_name        => "open-ils.circ.money.billing.retrieve.all",
269         notes           =><<"   NOTE");
270         Returns a list of billing items for the given transaction.
271         PARAMS( login, transaction_id )
272         NOTE
273
274 sub billing_items {
275         my( $self, $client, $login, $transid ) = @_;
276
277         my( $trans, $evt ) = $U->fetch_billable_xact($transid);
278         return $evt if $evt;
279
280         my $staff;
281         ($staff, $evt ) = $apputils->checkses($login);
282         return $evt if $evt;
283
284         if($staff->id ne $trans->usr) {
285                 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
286                 return $evt if $evt;
287         }
288         
289         return $apputils->simplereq( 'open-ils.storage',
290                 'open-ils.storage.direct.money.billing.search.xact.atomic', $transid )
291 }
292
293
294 __PACKAGE__->register_method(
295         method  => "billing_items_create",
296         api_name        => "open-ils.circ.money.billing.create",
297         notes           =><<"   NOTE");
298         Creates a new billing line item
299         PARAMS( login, bill_object (mb) )
300         NOTE
301
302 sub billing_items_create {
303         my( $self, $client, $login, $billing ) = @_;
304
305         my $e = new_editor(authtoken => $login, xact => 1);
306         return $e->event unless $e->checkauth;
307         return $e->event unless $e->allowed('CREATE_BILL');
308
309         my $xact = $e->retrieve_money_billable_transaction($billing->xact)
310                 or return $e->event;
311
312         # if the transaction was closed, re-open it
313         if($xact->xact_finish) {
314                 $xact->clear_xact_finish;
315                 $e->update_money_billable_transaction($xact)
316                         or return $e->event;
317         }
318
319         $e->create_money_billing($billing) or return $e->event;
320
321         $e->commit;
322         return $billing->id;
323 }
324
325 __PACKAGE__->register_method(
326         method          =>      'void_bill',
327         api_name                => 'open-ils.circ.money.billing.void',
328         signature       => q/
329                 Voids a bill
330                 @param authtoken Login session key
331                 @param billid The id of the bill to void
332                 @return 1 on success, Event on error
333         /
334 );
335
336 sub void_bill {
337         my( $s, $c, $authtoken, $billid ) = @_;
338
339         my $e = OpenILS::Utils::Editor->new( authtoken => $authtoken );
340         return $e->event unless $e->checkauth;
341         return $e->event unless $e->allowed('VOID_BILLING');
342
343         my $bill = $e->retrieve_money_billing($billid)
344                 or return $e->event;
345
346         return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill) 
347                 if $bill->voided and $bill->voided =~ /t/io;
348
349         $bill->voided('t');
350         $bill->voider($e->requestor->id);
351         $bill->void_time('now');
352
353         $e->update_money_billing($bill) or return $e->event;
354         my $evt = _check_open_xact($e, $bill->xact);
355         return $evt if $evt;
356
357         $e->finish;
358         return 1;
359 }
360
361 # refactored below XXX
362 sub ___check_open_xact {
363         my( $editor, $xactid ) = @_;
364
365         # Grab the transaction
366         my $xact = $editor->retrieve_money_billable_transaction($xactid)
367                 or return $editor->event;
368
369         # if it's still open, good.
370         return undef unless $xact->xact_finish;
371
372         $logger->info("re-opening transaction ".$xact->id);
373         my $finish = $xact->xact_finish;
374
375         # clear the transaction finish time
376         $xact->clear_xact_finish;
377         $editor->update_money_billable_transaction($xact);
378
379         # grab the summary and see how much is owed on this transaction
380         my $summary = $editor->retrieve_money_open_billable_transaction_summary($xactid)
381                 or return $editor->event;
382
383         if( $summary->balance_owed == 0 ) {
384                 # if nothing is owed, re-close the transaction
385                 $xact->xact_finish($finish);
386                 $editor->update_money_billable_transaction($xact);
387         }
388
389         return undef;
390 }
391
392
393
394 sub _check_open_xact {
395         my( $editor, $xactid ) = @_;
396
397         # Grab the transaction
398         my $xact = $editor->retrieve_money_billable_transaction($xactid)
399                 or return $editor->event;
400
401         # grab the summary and see how much is owed on this transaction
402         my $summary = $editor->retrieve_money_open_billable_transaction_summary($xactid)
403                 or return $editor->event;
404
405         # If nothing is owed on the transaction but xact_finish has
406         # not been set, set it and update
407         if( $summary->balance_owed == 0 and ! $xact->xact_finish ) {
408                 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
409                 $xact->xact_finish('now');
410                 $editor->update_money_billable_transaction($xact)
411                         or return $editor->event;
412                 return undef;
413         }
414
415         # If money is owed or a refund is due on the xact and xact_finish
416         # is set, clear it (to reopen the xact) and update
417         if( $summary->balance_owed != 0 and $xact->xact_finish ) {
418                 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
419                 $xact->clear_xact_finish;
420                 $editor->update_money_billable_transaction($xact)
421                         or return $editor->event;
422                 return undef;
423         }
424
425         return undef;
426 }
427
428
429
430 __PACKAGE__->register_method (
431         method => 'fetch_mbts',
432         api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
433 );
434 sub fetch_mbts {
435         my($s, $c, $authtoken, $id) = @_;
436
437         my $sum = $U->storagereq(
438                 'open-ils.storage.direct.money.billable_transaction_summary.retrieve', $id );
439         return OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', id => $id) unless $sum;
440
441         my ($reqr, $evt) = $U->checkses($authtoken);
442         return $evt if $evt;
443
444         my $usr;
445         ($usr, $evt) = $U->fetch_user($sum->usr);
446         return $evt if $evt;
447
448         $evt = $U->check_perms($reqr->id, $usr->home_ou, 'VIEW_TRANSACTION');
449         return $evt if $evt;
450
451         return $sum;
452 }
453
454
455
456
457
458 1;
459
460
461