1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <billserickson@gmail.com>
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.
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 # ---------------------------------------------------------------
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";
24 use OpenSRF::EX qw(:try);
28 use OpenSRF::Utils::Logger qw/:logger/;
29 use OpenILS::Utils::CStoreEditor qw/:funcs/;
31 __PACKAGE__->register_method(
32 method => "make_payments",
33 api_name => "open-ils.circ.money.payment",
35 Pass in a structure like so:
37 cash_drawer: <string>,
38 payment_type : <string>,
45 patron_credit : <credit amt>
47 login must have CREATE_PAYMENT priveleges.
48 If any payments fail, all are reverted back.
53 my( $self, $client, $login, $payments ) = @_;
55 my( $user, $trans, $evt );
57 ( $user, $evt ) = $apputils->checkses($login);
59 $evt = $apputils->check_perms($user->id, $user->ws_ou, 'CREATE_PAYMENT');
62 my $e = new_editor(); # at this point, just for convenience
64 $logger->info("Creating payment objects: " . Dumper($payments) );
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';
79 for my $pay (@{$payments->{payments}}) {
81 my $transid = $pay->[0];
82 my $amount = $pay->[1];
83 $amount =~ s/\$//og; # just to be safe
85 $trans = $self->fetch_mbts($client, $login, $transid);
86 return $trans if $U->event_code($trans);
88 $logger->info("payment method retrieved transaction [$transid] with balance_owed = " . $trans->balance_owed);
90 if($trans->usr != $userid) { # Do we need to restrict this in some way ??
91 $logger->info( " * User $userid is making a payment for " .
92 "a different user: " . $trans->usr . ' for transaction ' . $trans->id );
95 if($type eq 'credit_payment') {
97 $logger->activity("user ".$user->id." reducing patron credit by ".
98 "$credit for making a credit_payment on transaction ".$trans->id);
101 # A negative payment is a refund.
104 # If the refund causes the transaction balance to exceed 0 dollars,
105 # we are in effect loaning the patron money. This is not allowed.
106 if( ($trans->balance_owed - $amount) > 0 ) {
107 return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
110 # Otherwise, make sure the refund does not exceed desk payments
111 # This is also not allowed
113 my $desk_payments = $e->search_money_desk_payment(
114 { xact => $transid, voided => 'f' });
115 #$desk_total += $_->amount_collected for @$desk_payments;
116 $desk_total += $_->amount for @$desk_payments;
118 if( (-$amount) > $desk_total ) {
119 return OpenILS::Event->new(
120 'REFUND_EXCEEDS_DESK_PAYMENTS',
121 payload => { allowed_refund => $desk_total, submitted_refund => -$amount } );
125 my $payobj = "Fieldmapper::money::$type";
126 $payobj = $payobj->new;
128 $payobj->amount($amount);
129 $payobj->amount_collected($amount);
130 $payobj->accepting_usr($user->id);
131 $payobj->xact($transid);
132 $payobj->note($note);
134 if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
135 if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_type); }
136 if ($payobj->has_field('cc_number')) { $payobj->cc_number($cc_number); }
137 if ($payobj->has_field('expire_month')) { $payobj->expire_month($expire_month); }
138 if ($payobj->has_field('expire_year')) { $payobj->expire_year($expire_year); }
139 if ($payobj->has_field('approval_code')) { $payobj->approval_code($approval_code); }
140 if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
142 # update the transaction if it's done
143 if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
145 # Any overpay on this transaction goes directly into patron credit
148 $logger->activity("user ".$user->id." applying credit ".
149 "of $cred on transaction ".$trans->id. " because of overpayment");
151 $logger->debug("Transactin " . $trans->id . ' is complete');
152 $trans = $session->request(
153 "open-ils.storage.direct.money.billable_transaction.retrieve", $transid )->gather(1);
155 # If this is a circulation, we can't close the transaction unless stop_fines is set
156 my $circ = $session->request(
157 'open-ils.storage.direct.action.circulation.retrieve', $transid )->gather(1);
159 if( !$circ || $circ->stop_fines ) {
161 $trans->xact_finish("now");
162 my $s = $session->request(
163 "open-ils.storage.direct.money.billable_transaction.update", $trans )->gather(1);
165 if(!$s) { throw OpenSRF::EX::ERROR
166 ("Error updating billable_xact in circ.money.payment"); }
171 $logger->debug("Creating new $payobj for \$$amount\n");
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"); }
180 $logger->activity("user ".$user->id." applying total ".
181 "credit of $credit to user $userid") if $credit != 0;
183 $evt = _update_patron_credit( $session, $userid, $credit );
186 $apputils->commit_db_session($session);
188 # ------------------------------------------------------------------------------
189 # Update the patron penalty info in the DB
190 # ------------------------------------------------------------------------------
191 $U->update_patron_penalties(
196 $client->respond_complete(1);
202 sub _update_patron_credit {
203 my( $session, $userid, $credit ) = @_;
204 #return if $credit <= 0;
206 my $patron = $session->request(
207 'open-ils.storage.direct.actor.user.retrieve', $userid )->gather(1);
209 $patron->credit_forward_balance(
210 $patron->credit_forward_balance + $credit);
212 if( $patron->credit_forward_balance < 0 ) {
213 return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE');
216 $logger->info("Total patron credit for $userid is now " . $patron->credit_forward_balance );
219 'open-ils.storage.direct.actor.user.update', $patron )->gather(1);
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"
231 sub retrieve_payments {
232 my( $self, $client, $login, $transid ) = @_;
235 $apputils->checksesperm($login, 'VIEW_TRANSACTION');
238 # XXX the logic here is wrong.. we need to check the owner of the transaction
239 # to make sure the requestor has access
241 # XXX grab the view, for each object in the view, grab the real object
243 return $apputils->simplereq(
245 'open-ils.cstore.direct.money.payment.search.atomic', { xact => $transid } );
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"
256 sub retrieve_payments2 {
257 my( $self, $client, $login, $transid ) = @_;
259 my $e = new_editor(authtoken=>$login);
260 return $e->event unless $e->checkauth;
261 return $e->event unless $e->allowed('VIEW_TRANSACTION');
264 my $pmnts = $e->search_money_payment({ xact => $transid });
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 );
280 __PACKAGE__->register_method(
281 method => "create_grocery_bill",
282 api_name => "open-ils.circ.money.grocery.create",
284 Creates a new grocery transaction using the transaction object provided
285 PARAMS: (login_session, money.grocery (mg) object)
288 sub create_grocery_bill {
289 my( $self, $client, $login, $transaction ) = @_;
291 my( $staff, $evt ) = $apputils->checkses($login);
293 $evt = $apputils->check_perms($staff->id,
294 $transaction->billing_location, 'CREATE_TRANSACTION' );
298 $logger->activity("Creating grocery bill " . Dumper($transaction) );
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);
305 throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
307 $logger->debug("Created new grocery transaction $transid");
309 $apputils->commit_db_session($session);
315 __PACKAGE__->register_method(
316 method => 'fetch_grocery',
317 api_name => 'open-ils.circ.money.grocery.retrieve'
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)
331 __PACKAGE__->register_method(
332 method => "billing_items",
333 api_name => "open-ils.circ.money.billing.retrieve.all",
335 Returns a list of billing items for the given transaction.
336 PARAMS( login, transaction_id )
340 my( $self, $client, $login, $transid ) = @_;
342 my( $trans, $evt ) = $U->fetch_billable_xact($transid);
346 ($staff, $evt ) = $apputils->checkses($login);
349 if($staff->id ne $trans->usr) {
350 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
354 return $apputils->simplereq( 'open-ils.cstore',
355 'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
359 __PACKAGE__->register_method(
360 method => "billing_items_create",
361 api_name => "open-ils.circ.money.billing.create",
363 Creates a new billing line item
364 PARAMS( login, bill_object (mb) )
367 sub billing_items_create {
368 my( $self, $client, $login, $billing ) = @_;
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');
374 my $xact = $e->retrieve_money_billable_transaction($billing->xact)
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)
384 my $amt = $billing->amount;
386 $billing->amount($amt);
388 $e->create_money_billing($billing) or return $e->event;
391 # ------------------------------------------------------------------------------
392 # Update the patron penalty info in the DB
393 # ------------------------------------------------------------------------------
394 $U->update_patron_penalties(
396 patronid => $xact->usr,
402 __PACKAGE__->register_method(
403 method => 'void_bill',
404 api_name => 'open-ils.circ.money.billing.void',
407 @param authtoken Login session key
408 @param billid The id of the bill to void
409 @return 1 on success, Event on error
414 my( $s, $c, $authtoken, $billid ) = @_;
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');
421 my $bill = $e->retrieve_money_billing($billid)
424 return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill)
425 if $bill->voided and $bill->voided =~ /t/io;
428 $bill->voider($e->requestor->id);
429 $bill->void_time('now');
431 $e->update_money_billing($bill) or return $e->event;
432 my $evt = _check_open_xact($e, $bill->xact);
437 # ------------------------------------------------------------------------------
438 # Update the patron penalty info in the DB
439 # ------------------------------------------------------------------------------
440 my $xact = $e->retrieve_money_billable_transaction($bill->xact)
443 $U->update_patron_penalties(
444 authtoken => $authtoken,
445 patronid => $xact->usr,
451 sub _check_open_xact {
452 my( $editor, $xactid ) = @_;
454 # Grab the transaction
455 my $xact = $editor->retrieve_money_billable_transaction($xactid)
456 or return $editor->event;
458 # grab the summary and see how much is owed on this transaction
459 my $summary = $editor->retrieve_money_billable_transaction_summary($xactid)
460 or return $editor->event;
462 # grab the circulation if it is a circ;
463 my $circ = $editor->retrieve_action_circulation($xactid);
465 # If nothing is owed on the transaction but it is still open
466 # and this transaction is not an open circulation, close it
468 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
469 ( !$circ or $circ->stop_fines )) {
471 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
472 $xact->xact_finish('now');
473 $editor->update_money_billable_transaction($xact)
474 or return $editor->event;
478 # If money is owed or a refund is due on the xact and xact_finish
479 # is set, clear it (to reopen the xact) and update
480 if( $summary->balance_owed != 0 and $xact->xact_finish ) {
481 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
482 $xact->clear_xact_finish;
483 $editor->update_money_billable_transaction($xact)
484 or return $editor->event;
497 my $s = new Fieldmapper::money::billable_transaction_summary;
500 $s->xact_start( $x->xact_start );
501 $s->xact_finish( $x->xact_finish );
505 for my $b (@{ $x->billings }) {
506 next if ($U->is_true($b->voided));
507 $to += ($b->amount * 100);
508 $lb ||= $b->billing_ts;
509 if ($b->billing_ts ge $lb) {
510 $lb = $b->billing_ts;
511 $s->last_billing_note($b->note);
512 $s->last_billing_ts($b->billing_ts);
513 $s->last_billing_type($b->billing_type);
516 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
520 for my $p (@{ $x->payments }) {
521 next if ($U->is_true($p->voided));
522 $tp += ($p->amount * 100);
523 $lp ||= $p->payment_ts;
524 if ($p->payment_ts ge $lp) {
525 $lp = $p->payment_ts;
526 $s->last_payment_note($p->note);
527 $s->last_payment_ts($p->payment_ts);
528 $s->last_payment_type($p->payment_type);
531 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
533 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
535 $s->xact_type( 'grocery' ) if ($x->grocery);
536 $s->xact_type( 'circulation' ) if ($x->circulation);
545 __PACKAGE__->register_method (
546 method => 'fetch_mbts',
547 api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
550 my($s, $c, $authtoken, $id) = @_;
552 $id = $id->id if (ref($id));
554 my @xacts = @{ $U->cstorereq(
555 'open-ils.cstore.direct.money.billable_transaction.search.atomic',
557 { flesh => 1, flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] } }
560 my ($sum) = _make_mbts(@xacts);
561 return OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', id => $id) unless $sum;
563 my ($reqr, $evt) = $U->checkses($authtoken);
567 ($usr, $evt) = $U->fetch_user($sum->usr);
570 $evt = $U->check_perms($reqr->id, $usr->home_ou, 'VIEW_TRANSACTION');
577 __PACKAGE__->register_method(
578 method => 'desk_payments',
579 api_name => 'open-ils.circ.money.org_unit.desk_payments'
583 my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
584 my $e = new_editor(authtoken=>$auth);
585 return $e->event unless $e->checkauth;
586 return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
587 my $data = $U->storagereq(
588 'open-ils.storage.money.org_unit.desk_payments.atomic',
589 $org, $start_date, $end_date );
591 $_->workstation( $_->workstation->name ) for(@$data);
596 __PACKAGE__->register_method(
597 method => 'user_payments',
598 api_name => 'open-ils.circ.money.org_unit.user_payments'
602 my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
603 my $e = new_editor(authtoken=>$auth);
604 return $e->event unless $e->checkauth;
605 return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
606 my $data = $U->storagereq(
607 'open-ils.storage.money.org_unit.user_payments.atomic',
608 $org, $start_date, $end_date );
611 $e->retrieve_actor_card($_->usr->card)->barcode);
613 $e->retrieve_actor_org_unit($_->usr->home_ou)->shortname);