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/OpenILS::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/;
30 use OpenILS::Utils::Penalty;
32 __PACKAGE__->register_method(
33 method => "make_payments",
34 api_name => "open-ils.circ.money.payment",
36 desc => q/Create payments for a given user and set of transactions,
37 login must have CREATE_PAYMENT priveleges.
38 If any payments fail, all are reverted back./,
40 {desc => 'Authtoken', type => 'string'},
41 {desc => q/Arguments Hash, supporting the following params:
66 my($self, $client, $auth, $payments) = @_;
68 my $e = new_editor(authtoken => $auth, xact => 1);
69 return $e->die_event unless $e->checkauth;
71 my $type = $payments->{payment_type};
72 my $user_id = $payments->{userid};
73 my $credit = $payments->{patron_credit} || 0;
74 my $drawer = $e->requestor->wsid;
75 my $note = $payments->{note};
76 my $check_number = $payments->{check_number};
77 my $cc_args = $payments->{cc_args};
81 my $patron = $e->retrieve_actor_user($user_id) or return $e->die_event;
83 # A user is allowed to make credit card payments on his/her own behalf
84 # All other scenarious require permission
85 unless($type eq 'credit_card_payment' and $user_id == $e->requestor->id) {
86 return $e->die_event unless $e->allowed('CREATE_PAYMENT', $patron->home_ou);
89 # first collect the transactions and make sure the transaction
90 # user matches the requested user
92 for my $pay (@{$payments->{payments}}) {
94 my $xact_id = $pay->[0];
95 my $xact = $e->retrieve_money_billable_transaction_summary($xact_id)
96 or return $e->die_event;
98 if($xact->usr != $user_id) {
100 return OpenILS::Event->new('BAD_PARAMS', note => q/user does not match transaction/);
103 $xacts{$xact_id} = $xact;
108 for my $pay (@{$payments->{payments}}) {
110 my $transid = $pay->[0];
111 my $amount = $pay->[1];
112 $amount =~ s/\$//og; # just to be safe
113 my $trans = $xacts{$transid};
115 $total_paid += $amount;
117 $orgs{$U->xact_org($transid, $e)} = 1;
119 # making payment with existing patron credit
120 $credit -= $amount if $type eq 'credit_payment';
122 # A negative payment is a refund.
125 # Negative credit card payments are not allowed
126 if($type eq 'credit_card_payment') {
128 return OpenILS::Event->new(
130 note => q/Negative credit card payments not allowed/
134 # If the refund causes the transaction balance to exceed 0 dollars,
135 # we are in effect loaning the patron money. This is not allowed.
136 if( ($trans->balance_owed - $amount) > 0 ) {
138 return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
141 # Otherwise, make sure the refund does not exceed desk payments
142 # This is also not allowed
144 my $desk_payments = $e->search_money_desk_payment({xact => $transid, voided => 'f'});
145 $desk_total += $_->amount for @$desk_payments;
147 if( (-$amount) > $desk_total ) {
149 return OpenILS::Event->new(
150 'REFUND_EXCEEDS_DESK_PAYMENTS',
151 payload => { allowed_refund => $desk_total, submitted_refund => -$amount } );
155 my $payobj = "Fieldmapper::money::$type";
156 $payobj = $payobj->new;
158 $payobj->amount($amount);
159 $payobj->amount_collected($amount);
160 $payobj->xact($transid);
161 $payobj->note($note);
163 if ($payobj->has_field('accepting_usr')) { $payobj->accepting_usr($e->requestor->id); }
164 if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
165 if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_args->{type}); }
166 if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
168 # Store the last 4 digits?
169 #if ($payobj->has_field('cc_number')) { $payobj->cc_number($cc_args->{number}); }
170 #if ($payobj->has_field('approval_code')) { $payobj->approval_code($cc_args->{approval_code}); }
171 if ($payobj->has_field('expire_month')) { $payobj->expire_month($cc_args->{expire_month}); }
172 if ($payobj->has_field('expire_year')) { $payobj->expire_year($cc_args->{expire_year}); }
174 # update the transaction if it's done
175 if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
177 # Any overpay on this transaction goes directly into patron credit
180 my $circ = $e->retrieve_action_circulation($transid);
182 if(!$circ || $circ->stop_fines) {
183 # If this is a circulation, we can't close the transaction unless stop_fines is set
184 $trans = $e->retrieve_money_billable_transaction($transid);
185 $trans->xact_finish("now");
186 $e->update_money_billable_transaction($trans) or return $e->die_event;
190 my $method = "create_money_$type";
191 $e->$method($payobj) or return $e->die_event;
192 push(@payment_objs, $payobj);
194 } # all payment objects have been created and inserted.
196 my $evt = _update_patron_credit($e, $patron, $credit);
199 for my $org_id (keys %orgs) {
200 # calculate penalties for each of the affected orgs
201 $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
205 if($type eq 'credit_card_payment') {
206 my $this_ou = $e->requestor->ws_ou;
207 my $response = $apputils->simplereq(
209 'open-ils.credit.process',
211 "desc" => $payments->{note},
212 "amount" => $total_paid,
213 "patron_id" => $user_id,
214 "cc" => $payments->{cc_number},
215 "expiration" => sprintf(
217 $payments->{expire_month},
218 $payments->{expire_year}
224 if (exists $response->{ilsevent}) {
228 if ($response->{statusCode} != 200) {
230 $logger->info("Credit card payment for user $user_id failed with message: " . $response->{statusText});
231 return OpenILS::Event->new(
232 'CREDIT_PROCESSOR_DECLINED_TRANSACTION',
233 note => $response->{statusText}
237 for my $payment (@payment_objs) {
238 $payment->approval_code($response->{approvalCode});
239 $e->update_money_credit_card_payment($payment) or return $e->die_event;
241 $logger->info("Credit card payment for user $user_id succeeded");
249 sub _update_patron_credit {
250 my($e, $patron, $credit) = @_;
251 return undef if $credit == 0;
252 $patron->credit_forward_balance($patron->credit_forward_balance + $credit);
253 return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE') if $patron->credit_forward_balance < 0;
254 $e->update_actor_user($patron) or return $e->die_event;
259 __PACKAGE__->register_method(
260 method => "retrieve_payments",
261 api_name => "open-ils.circ.money.payment.retrieve.all_",
262 notes => "Returns a list of payments attached to a given transaction"
265 sub retrieve_payments {
266 my( $self, $client, $login, $transid ) = @_;
269 $apputils->checksesperm($login, 'VIEW_TRANSACTION');
272 # XXX the logic here is wrong.. we need to check the owner of the transaction
273 # to make sure the requestor has access
275 # XXX grab the view, for each object in the view, grab the real object
277 return $apputils->simplereq(
279 'open-ils.cstore.direct.money.payment.search.atomic', { xact => $transid } );
284 __PACKAGE__->register_method(
285 method => "retrieve_payments2",
287 api_name => "open-ils.circ.money.payment.retrieve.all",
288 notes => "Returns a list of payments attached to a given transaction"
291 sub retrieve_payments2 {
292 my( $self, $client, $login, $transid ) = @_;
294 my $e = new_editor(authtoken=>$login);
295 return $e->event unless $e->checkauth;
296 return $e->event unless $e->allowed('VIEW_TRANSACTION');
299 my $pmnts = $e->search_money_payment({ xact => $transid });
301 my $type = $_->payment_type;
302 my $meth = "retrieve_money_$type";
303 my $p = $e->$meth($_->id) or return $e->event;
304 $p->payment_type($type);
305 $p->cash_drawer($e->retrieve_actor_workstation($p->cash_drawer))
306 if $p->has_field('cash_drawer');
307 push( @payments, $p );
315 __PACKAGE__->register_method(
316 method => "create_grocery_bill",
317 api_name => "open-ils.circ.money.grocery.create",
319 Creates a new grocery transaction using the transaction object provided
320 PARAMS: (login_session, money.grocery (mg) object)
323 sub create_grocery_bill {
324 my( $self, $client, $login, $transaction ) = @_;
326 my( $staff, $evt ) = $apputils->checkses($login);
328 $evt = $apputils->check_perms($staff->id,
329 $transaction->billing_location, 'CREATE_TRANSACTION' );
333 $logger->activity("Creating grocery bill " . Dumper($transaction) );
335 $transaction->clear_id;
336 my $session = $apputils->start_db_session;
337 my $transid = $session->request(
338 'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
340 throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
342 $logger->debug("Created new grocery transaction $transid");
344 $apputils->commit_db_session($session);
346 my $e = new_editor(xact=>1);
347 $evt = _check_open_xact($e, $transid);
355 __PACKAGE__->register_method(
356 method => 'fetch_grocery',
357 api_name => 'open-ils.circ.money.grocery.retrieve'
361 my( $self, $conn, $auth, $id ) = @_;
362 my $e = new_editor(authtoken=>$auth);
363 return $e->event unless $e->checkauth;
364 return $e->event unless $e->allowed('VIEW_TRANSACTION'); # eh.. basically the same permission
365 my $g = $e->retrieve_money_grocery($id)
371 __PACKAGE__->register_method(
372 method => "billing_items",
374 api_name => "open-ils.circ.money.billing.retrieve.all",
376 Returns a list of billing items for the given transaction.
377 PARAMS( login, transaction_id )
381 my( $self, $client, $login, $transid ) = @_;
383 my( $trans, $evt ) = $U->fetch_billable_xact($transid);
387 ($staff, $evt ) = $apputils->checkses($login);
390 if($staff->id ne $trans->usr) {
391 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
395 return $apputils->simplereq( 'open-ils.cstore',
396 'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
400 __PACKAGE__->register_method(
401 method => "billing_items_create",
402 api_name => "open-ils.circ.money.billing.create",
404 Creates a new billing line item
405 PARAMS( login, bill_object (mb) )
408 sub billing_items_create {
409 my( $self, $client, $login, $billing ) = @_;
411 my $e = new_editor(authtoken => $login, xact => 1);
412 return $e->die_event unless $e->checkauth;
413 return $e->die_event unless $e->allowed('CREATE_BILL');
415 my $xact = $e->retrieve_money_billable_transaction($billing->xact)
416 or return $e->die_event;
418 # if the transaction was closed, re-open it
419 if($xact->xact_finish) {
420 $xact->clear_xact_finish;
421 $e->update_money_billable_transaction($xact)
422 or return $e->die_event;
425 my $amt = $billing->amount;
427 $billing->amount($amt);
429 $e->create_money_billing($billing) or return $e->die_event;
430 my $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $xact->usr, $U->xact_org($xact->id));
437 __PACKAGE__->register_method(
438 method => 'void_bill',
439 api_name => 'open-ils.circ.money.billing.void',
442 @param authtoken Login session key
443 @param billid Id for the bill to void. This parameter may be repeated to reference other bills.
444 @return 1 on success, Event on error
450 my( $s, $c, $authtoken, @billids ) = @_;
452 my $e = new_editor( authtoken => $authtoken, xact => 1 );
453 return $e->die_event unless $e->checkauth;
454 return $e->die_event unless $e->allowed('VOID_BILLING');
457 for my $billid (@billids) {
459 my $bill = $e->retrieve_money_billing($billid)
460 or return $e->die_event;
462 my $xact = $e->retrieve_money_billable_transaction($bill->xact)
463 or return $e->die_event;
465 if($U->is_true($bill->voided)) {
467 return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill);
470 my $org = $U->xact_org($bill->xact, $e);
471 $users{$xact->usr} = {} unless $users{$xact->usr};
472 $users{$xact->usr}->{$org} = 1;
475 $bill->voider($e->requestor->id);
476 $bill->void_time('now');
478 $e->update_money_billing($bill) or return $e->die_event;
479 my $evt = _check_open_xact($e, $bill->xact, $xact);
483 # calculate penalties for all user/org combinations
484 for my $user_id (keys %users) {
485 for my $org_id (keys %{$users{$user_id}}) {
486 OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
494 __PACKAGE__->register_method(
495 method => 'edit_bill_note',
496 api_name => 'open-ils.circ.money.billing.note.edit',
498 Edits the note for a bill
499 @param authtoken Login session key
500 @param note The replacement note for the bills we're editing
501 @param billid Id for the bill to edit the note of. This parameter may be repeated to reference other bills.
502 @return 1 on success, Event on error
508 my( $s, $c, $authtoken, $note, @billids ) = @_;
510 my $e = new_editor( authtoken => $authtoken, xact => 1 );
511 return $e->die_event unless $e->checkauth;
512 return $e->die_event unless $e->allowed('UPDATE_BILL_NOTE');
514 for my $billid (@billids) {
516 my $bill = $e->retrieve_money_billing($billid)
517 or return $e->die_event;
520 # FIXME: Does this get audited? Need some way so that the original creator of the bill does not get credit/blame for the new note.
522 $e->update_money_billing($bill) or return $e->die_event;
529 __PACKAGE__->register_method(
530 method => 'edit_payment_note',
531 api_name => 'open-ils.circ.money.payment.note.edit',
533 Edits the note for a payment
534 @param authtoken Login session key
535 @param note The replacement note for the payments we're editing
536 @param paymentid Id for the payment to edit the note of. This parameter may be repeated to reference other payments.
537 @return 1 on success, Event on error
542 sub edit_payment_note {
543 my( $s, $c, $authtoken, $note, @paymentids ) = @_;
545 my $e = new_editor( authtoken => $authtoken, xact => 1 );
546 return $e->die_event unless $e->checkauth;
547 return $e->die_event unless $e->allowed('UPDATE_PAYMENT_NOTE');
549 for my $paymentid (@paymentids) {
551 my $payment = $e->retrieve_money_payment($paymentid)
552 or return $e->die_event;
554 $payment->note($note);
555 # FIXME: Does this get audited? Need some way so that the original taker of the payment does not get credit/blame for the new note.
557 $e->update_money_payment($payment) or return $e->die_event;
564 sub _check_open_xact {
565 my( $editor, $xactid, $xact ) = @_;
567 # Grab the transaction
568 $xact ||= $editor->retrieve_money_billable_transaction($xactid);
569 return $editor->event unless $xact;
570 $xactid ||= $xact->id;
572 # grab the summary and see how much is owed on this transaction
573 my ($summary) = $U->fetch_mbts($xactid, $editor);
575 # grab the circulation if it is a circ;
576 my $circ = $editor->retrieve_action_circulation($xactid);
578 # If nothing is owed on the transaction but it is still open
579 # and this transaction is not an open circulation, close it
581 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
582 ( !$circ or $circ->stop_fines )) {
584 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
585 $xact->xact_finish('now');
586 $editor->update_money_billable_transaction($xact)
587 or return $editor->event;
591 # If money is owed or a refund is due on the xact and xact_finish
592 # is set, clear it (to reopen the xact) and update
593 if( $summary->balance_owed != 0 and $xact->xact_finish ) {
594 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
595 $xact->clear_xact_finish;
596 $editor->update_money_billable_transaction($xact)
597 or return $editor->event;
606 __PACKAGE__->register_method (
607 method => 'fetch_mbts',
609 api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
612 my( $self, $conn, $auth, $id) = @_;
614 my $e = new_editor(xact => 1, authtoken=>$auth);
615 return $e->event unless $e->checkauth;
616 my ($mbts) = $U->fetch_mbts($id, $e);
618 my $user = $e->retrieve_actor_user($mbts->usr)
619 or return $e->die_event;
621 return $e->die_event unless $e->allowed('VIEW_TRANSACTION', $user->home_ou);
628 __PACKAGE__->register_method(
629 method => 'desk_payments',
630 api_name => 'open-ils.circ.money.org_unit.desk_payments'
634 my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
635 my $e = new_editor(authtoken=>$auth);
636 return $e->event unless $e->checkauth;
637 return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
638 my $data = $U->storagereq(
639 'open-ils.storage.money.org_unit.desk_payments.atomic',
640 $org, $start_date, $end_date );
642 $_->workstation( $_->workstation->name ) for(@$data);
647 __PACKAGE__->register_method(
648 method => 'user_payments',
649 api_name => 'open-ils.circ.money.org_unit.user_payments'
653 my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
654 my $e = new_editor(authtoken=>$auth);
655 return $e->event unless $e->checkauth;
656 return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
657 my $data = $U->storagereq(
658 'open-ils.storage.money.org_unit.user_payments.atomic',
659 $org, $start_date, $end_date );
662 $e->retrieve_actor_card($_->usr->card)->barcode);
664 $e->retrieve_actor_org_unit($_->usr->home_ou)->shortname);