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