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