]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Money.pm
plugged in the new and improved in-db penalty calculation
[working/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/OpenILS::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::CStoreEditor qw/:funcs/;
30 use OpenILS::Utils::Penalty;
31
32 __PACKAGE__->register_method(
33         method  => "make_payments",
34         api_name        => "open-ils.circ.money.payment",
35         notes           => <<"  NOTE");
36         Pass in a structure like so:
37                 { 
38                         cash_drawer: <string>, 
39                         payment_type : <string>, 
40                         note : <string>, 
41                         userid : <id>,
42                         payments: [ 
43                                 [trans_id, amt], 
44                                 [...]
45                         ], 
46                         patron_credit : <credit amt> 
47                 }
48         login must have CREATE_PAYMENT priveleges.
49         If any payments fail, all are reverted back.
50         NOTE
51
52 sub make_payments {
53
54         my( $self, $client, $login, $payments ) = @_;
55
56         my( $user, $trans, $evt );
57
58         ( $user, $evt ) = $apputils->checkses($login);
59         return $evt if $evt;
60         $evt = $apputils->check_perms($user->id, $user->ws_ou, 'CREATE_PAYMENT');
61         return $evt if $evt;
62
63         my $e = new_editor(); # at this point, just for convenience
64
65         $logger->info("Creating payment objects: " . Dumper($payments) );
66
67         my $session = $apputils->start_db_session;
68         my $type                = $payments->{payment_type};
69         my $credit      = $payments->{patron_credit} || 0;
70         my $drawer      = $user->wsid;
71         my $userid      = $payments->{userid};
72         my $note                = $payments->{note};
73         my $cc_type = $payments->{cc_type} || 'n/a';
74         my $cc_number           = $payments->{cc_number} || 'n/a';
75         my $expire_month        = $payments->{expire_month};
76         my $expire_year = $payments->{expire_year};
77         my $approval_code = $payments->{approval_code} || 'n/a';
78         my $check_number        = $payments->{check_number} || 'n/a';
79
80         my $total_paid = 0;
81
82         for my $pay (@{$payments->{payments}}) {
83
84                 my $transid = $pay->[0];
85                 my $amount = $pay->[1];
86                 $amount =~ s/\$//og; # just to be safe
87
88                 $total_paid += $amount;
89
90                 $trans = fetch_mbts($self, $client, $login, $transid);
91                 return $trans if $U->event_code($trans);
92
93                 $logger->info("payment: processing transaction [$transid] with balance_owed = ". 
94                         $trans->balance_owed. ",  payment amount = $amount, and payment type = $type");
95
96                 if($trans->usr != $userid) { # Do we need to restrict this in some way ??
97                         $logger->info( " * User $userid is making a payment for " . 
98                                 "a different user: " .  $trans->usr . ' for transaction ' . $trans->id  );
99                 }
100
101                 if($type eq 'credit_payment') {
102                         $credit -= $amount;
103                         $logger->activity("user ".$user->id." reducing patron credit by ".
104                                 "$credit for making a credit_payment on transaction ".$trans->id);
105                 }
106
107                 # A negative payment is a refund.  
108                 if( $amount < 0 ) {
109                         
110                         $logger->info("payment: received a negative payment (refund) of $amount");
111
112                         # If the refund causes the transaction balance to exceed 0 dollars, 
113                         # we are in effect loaning the patron money.  This is not allowed.
114                         if( ($trans->balance_owed - $amount) > 0 ) {
115                                 return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
116                         }
117
118                         # Otherwise, make sure the refund does not exceed desk payments
119                         # This is also not allowed
120                         my $desk_total = 0;
121                         my $desk_payments = $e->search_money_desk_payment(
122                                 { xact => $transid, voided => 'f' });
123                         $desk_total += $_->amount for @$desk_payments;
124
125                         if( (-$amount) > $desk_total ) {
126                                 return OpenILS::Event->new(
127                                         'REFUND_EXCEEDS_DESK_PAYMENTS', 
128                                         payload => { allowed_refund => $desk_total, submitted_refund => -$amount } );
129                         }
130                 }
131
132                 my $payobj = "Fieldmapper::money::$type";
133                 $payobj = $payobj->new;
134
135                 $payobj->amount($amount);
136                 $payobj->amount_collected($amount);
137                 $payobj->xact($transid);
138                 $payobj->note($note);
139
140                 if ($payobj->has_field('accepting_usr')) { $payobj->accepting_usr($user->id); }
141                 if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
142                 if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_type); }
143                 if ($payobj->has_field('cc_number')) { $payobj->cc_number($cc_number); }
144                 if ($payobj->has_field('expire_month')) { $payobj->expire_month($expire_month); }
145                 if ($payobj->has_field('expire_year')) { $payobj->expire_year($expire_year); }
146                 if ($payobj->has_field('approval_code')) { $payobj->approval_code($approval_code); }
147                 if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
148                 
149                 # update the transaction if it's done 
150                 if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
151
152                         # Any overpay on this transaction goes directly into patron credit 
153                         $cred = -$cred;
154
155                         $logger->info("payment: amount ($amount) exceeds transaction balance of ".
156                                 $trans->balance_owed.".  Applying patron credit of $cred");
157
158                         $credit += $cred;
159
160                         $trans = $session->request(
161                                 "open-ils.storage.direct.money.billable_transaction.retrieve", $transid )->gather(1);
162
163                         # If this is a circulation, we can't close the transaction unless stop_fines is set
164                         my $circ = $session->request(
165                                 'open-ils.storage.direct.action.circulation.retrieve', $transid )->gather(1);
166
167                         if( !$circ || $circ->stop_fines ) {
168
169                                 $trans->xact_finish("now");
170                                 my $s = $session->request(
171                                         "open-ils.storage.direct.money.billable_transaction.update", $trans )->gather(1);
172         
173                                 if(!$s) { throw OpenSRF::EX::ERROR 
174                                         ("Error updating billable_xact in circ.money.payment"); }
175                         }
176                 }
177
178                 my $s = $session->request(
179                         "open-ils.storage.direct.money.$type.create", $payobj )->gather(1);
180                 if(!$s) { throw OpenSRF::EX::ERROR ("Error creating new $type"); }
181
182         }
183
184
185         my $uid = $user->id;
186         $logger->info("user $uid applying total ".
187                 "credit of $credit to user $userid") if $credit != 0;
188
189         $logger->info("user $uid applying total payment of $total_paid to user $userid");
190
191         $evt = _update_patron_credit( $session, $userid, $credit );
192         return $evt if $evt;
193
194         $apputils->commit_db_session($session);
195
196     $client->respond_complete(1);       
197
198         $e = new_editor(xact => 1);
199     $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $userid, $drawer);
200     $e->commit unless $evt;
201
202         return undef;
203 }
204
205
206 sub _update_patron_credit {
207         my( $session, $userid, $credit ) = @_;
208         #return if $credit <= 0;
209
210         my $patron = $session->request( 
211                 'open-ils.storage.direct.actor.user.retrieve', $userid )->gather(1);
212
213         $patron->credit_forward_balance( 
214                 $patron->credit_forward_balance + $credit);
215
216         if( $patron->credit_forward_balance < 0 ) {
217                 return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE');
218         }
219         
220         $logger->info("Total patron credit for $userid is now " . $patron->credit_forward_balance );
221
222         $session->request( 
223                 'open-ils.storage.direct.actor.user.update', $patron )->gather(1);
224
225         return undef;
226 }
227
228
229 __PACKAGE__->register_method(
230         method  => "retrieve_payments",
231         api_name        => "open-ils.circ.money.payment.retrieve.all_",
232         notes           => "Returns a list of payments attached to a given transaction"
233         );
234         
235 sub retrieve_payments {
236         my( $self, $client, $login, $transid ) = @_;
237
238         my( $staff, $evt ) =  
239                 $apputils->checksesperm($login, 'VIEW_TRANSACTION');
240         return $evt if $evt;
241
242         # XXX the logic here is wrong.. we need to check the owner of the transaction
243         # to make sure the requestor has access
244
245         # XXX grab the view, for each object in the view, grab the real object
246
247         return $apputils->simplereq(
248                 'open-ils.cstore',
249                 'open-ils.cstore.direct.money.payment.search.atomic', { xact => $transid } );
250 }
251
252
253
254 __PACKAGE__->register_method(
255         method  => "retrieve_payments2",
256     authoritative => 1,
257         api_name        => "open-ils.circ.money.payment.retrieve.all",
258         notes           => "Returns a list of payments attached to a given transaction"
259         );
260         
261 sub retrieve_payments2 {
262         my( $self, $client, $login, $transid ) = @_;
263
264         my $e = new_editor(authtoken=>$login);
265         return $e->event unless $e->checkauth;
266         return $e->event unless $e->allowed('VIEW_TRANSACTION');
267
268         my @payments;
269         my $pmnts = $e->search_money_payment({ xact => $transid });
270         for( @$pmnts ) {
271                 my $type = $_->payment_type;
272                 my $meth = "retrieve_money_$type";
273                 my $p = $e->$meth($_->id) or return $e->event;
274                 $p->payment_type($type);
275                 $p->cash_drawer($e->retrieve_actor_workstation($p->cash_drawer))
276                         if $p->has_field('cash_drawer');
277                 push( @payments, $p );
278         }
279
280         return \@payments;
281 }
282
283
284
285 __PACKAGE__->register_method(
286         method  => "create_grocery_bill",
287         api_name        => "open-ils.circ.money.grocery.create",
288         notes           => <<"  NOTE");
289         Creates a new grocery transaction using the transaction object provided
290         PARAMS: (login_session, money.grocery (mg) object)
291         NOTE
292
293 sub create_grocery_bill {
294         my( $self, $client, $login, $transaction ) = @_;
295
296         my( $staff, $evt ) = $apputils->checkses($login);
297         return $evt if $evt;
298         $evt = $apputils->check_perms($staff->id, 
299                 $transaction->billing_location, 'CREATE_TRANSACTION' );
300         return $evt if $evt;
301
302
303         $logger->activity("Creating grocery bill " . Dumper($transaction) );
304
305         $transaction->clear_id;
306         my $session = $apputils->start_db_session;
307         my $transid = $session->request(
308                 'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
309
310         throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
311
312         $logger->debug("Created new grocery transaction $transid");
313         
314         $apputils->commit_db_session($session);
315
316     my $e = new_editor(xact=>1);
317     $evt = _check_open_xact($e, $transid);
318     return $evt if $evt;
319     $e->commit;
320
321         return $transid;
322 }
323
324
325 __PACKAGE__->register_method(
326         method => 'fetch_grocery',
327         api_name => 'open-ils.circ.money.grocery.retrieve'
328 );
329
330 sub fetch_grocery {
331         my( $self, $conn, $auth, $id ) = @_;
332         my $e = new_editor(authtoken=>$auth);
333         return $e->event unless $e->checkauth;
334         return $e->event unless $e->allowed('VIEW_TRANSACTION'); # eh.. basically the same permission
335         my $g = $e->retrieve_money_grocery($id)
336                 or return $e->event;
337         return $g;
338 }
339
340
341 __PACKAGE__->register_method(
342         method  => "billing_items",
343     authoritative => 1,
344         api_name        => "open-ils.circ.money.billing.retrieve.all",
345         notes           =><<"   NOTE");
346         Returns a list of billing items for the given transaction.
347         PARAMS( login, transaction_id )
348         NOTE
349
350 sub billing_items {
351         my( $self, $client, $login, $transid ) = @_;
352
353         my( $trans, $evt ) = $U->fetch_billable_xact($transid);
354         return $evt if $evt;
355
356         my $staff;
357         ($staff, $evt ) = $apputils->checkses($login);
358         return $evt if $evt;
359
360         if($staff->id ne $trans->usr) {
361                 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
362                 return $evt if $evt;
363         }
364         
365         return $apputils->simplereq( 'open-ils.cstore',
366                 'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
367 }
368
369
370 __PACKAGE__->register_method(
371         method  => "billing_items_create",
372         api_name        => "open-ils.circ.money.billing.create",
373         notes           =><<"   NOTE");
374         Creates a new billing line item
375         PARAMS( login, bill_object (mb) )
376         NOTE
377
378 sub billing_items_create {
379         my( $self, $client, $login, $billing ) = @_;
380
381         my $e = new_editor(authtoken => $login, xact => 1);
382         return $e->die_event unless $e->checkauth;
383         return $e->die_event unless $e->allowed('CREATE_BILL');
384
385         my $xact = $e->retrieve_money_billable_transaction($billing->xact)
386                 or return $e->die_event;
387
388         # if the transaction was closed, re-open it
389         if($xact->xact_finish) {
390                 $xact->clear_xact_finish;
391                 $e->update_money_billable_transaction($xact)
392                         or return $e->die_event;
393         }
394
395         my $amt = $billing->amount;
396         $amt =~ s/\$//og;
397         $billing->amount($amt);
398
399         $e->create_money_billing($billing) or return $e->die_event;
400     my $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $xact->usr, $e->requestor->ws_ou);
401     return $evt if $evt;
402         $e->commit;
403
404         return $billing->id;
405 }
406
407 __PACKAGE__->register_method(
408         method          =>      'void_bill',
409         api_name                => 'open-ils.circ.money.billing.void',
410         signature       => q/
411                 Voids a bill
412                 @param authtoken Login session key
413                 @param billid The id of the bill to void
414                 @return 1 on success, Event on error
415         /
416 );
417
418
419 sub void_bill {
420         my( $s, $c, $authtoken, @billids ) = @_;
421
422         my $e = new_editor( authtoken => $authtoken, xact => 1 );
423         return $e->event unless $e->checkauth;
424         return $e->event unless $e->allowed('VOID_BILLING');
425
426     my %users;
427     for my $billid (@billids) {
428
429             my $bill = $e->retrieve_money_billing($billid)
430                     or return $e->event;
431
432         my $xact = $e->retrieve_money_billable_transaction($bill->xact)
433             or return $e->event;
434
435         $users{$xact->usr} = 1;
436     
437             return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill) 
438                     if $bill->voided and $bill->voided =~ /t/io;
439     
440             $bill->voided('t');
441             $bill->voider($e->requestor->id);
442             $bill->void_time('now');
443     
444             $e->update_money_billing($bill) or return $e->event;
445             my $evt = _check_open_xact($e, $bill->xact, $xact);
446             return $evt if $evt;
447     }
448
449     OpenILS::Utils::Penalty->calculate_penalties($e, $_, $e->requestor->ws_ou) for keys %users;
450         $e->commit;
451         return 1;
452 }
453
454
455 sub _check_open_xact {
456         my( $editor, $xactid, $xact ) = @_;
457
458         # Grab the transaction
459         $xact ||= $editor->retrieve_money_billable_transaction($xactid);
460     return $editor->event unless $xact;
461     $xactid ||= $xact->id;
462
463         # grab the summary and see how much is owed on this transaction
464         my ($summary) = $U->fetch_mbts($xactid, $editor);
465
466         # grab the circulation if it is a circ;
467         my $circ = $editor->retrieve_action_circulation($xactid);
468
469         # If nothing is owed on the transaction but it is still open
470         # and this transaction is not an open circulation, close it
471         if( 
472                 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
473                 ( !$circ or $circ->stop_fines )) {
474
475                 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
476                 $xact->xact_finish('now');
477                 $editor->update_money_billable_transaction($xact)
478                         or return $editor->event;
479                 return undef;
480         }
481
482         # If money is owed or a refund is due on the xact and xact_finish
483         # is set, clear it (to reopen the xact) and update
484         if( $summary->balance_owed != 0 and $xact->xact_finish ) {
485                 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
486                 $xact->clear_xact_finish;
487                 $editor->update_money_billable_transaction($xact)
488                         or return $editor->event;
489                 return undef;
490         }
491
492         return undef;
493 }
494
495
496
497 __PACKAGE__->register_method (
498         method => 'fetch_mbts',
499     authoritative => 1,
500         api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
501 );
502 sub fetch_mbts {
503         my( $self, $conn, $auth, $id) = @_;
504
505         my $e = new_editor(xact => 1, authtoken=>$auth);
506         return $e->event unless $e->checkauth;
507         my ($mbts) = $U->fetch_mbts($id, $e);
508
509         my $user = $e->retrieve_actor_user($mbts->usr)
510                 or return $e->die_event;
511
512         return $e->die_event unless $e->allowed('VIEW_TRANSACTION', $user->home_ou);
513         $e->rollback;
514         return $mbts
515 }
516
517
518
519 __PACKAGE__->register_method(
520         method => 'desk_payments',
521         api_name => 'open-ils.circ.money.org_unit.desk_payments'
522 );
523
524 sub desk_payments {
525         my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
526         my $e = new_editor(authtoken=>$auth);
527         return $e->event unless $e->checkauth;
528         return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
529         my $data = $U->storagereq(
530                 'open-ils.storage.money.org_unit.desk_payments.atomic',
531                 $org, $start_date, $end_date );
532
533         $_->workstation( $_->workstation->name ) for(@$data);
534         return $data;
535 }
536
537
538 __PACKAGE__->register_method(
539         method => 'user_payments',
540         api_name => 'open-ils.circ.money.org_unit.user_payments'
541 );
542
543 sub user_payments {
544         my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
545         my $e = new_editor(authtoken=>$auth);
546         return $e->event unless $e->checkauth;
547         return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
548         my $data = $U->storagereq(
549                 'open-ils.storage.money.org_unit.user_payments.atomic',
550                 $org, $start_date, $end_date );
551         for(@$data) {
552                 $_->usr->card(
553                         $e->retrieve_actor_card($_->usr->card)->barcode);
554                 $_->usr->home_ou(
555                         $e->retrieve_actor_org_unit($_->usr->home_ou)->shortname);
556         }
557         return $data;
558 }
559
560
561
562
563 1;
564
565
566