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