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