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