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