]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Money.pm
fleshing workstation on payment objects and returning specific objects
[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                 try {
254                         $p->cash_drawer($e->retrieve_actor_workstation($p->cash_drawer));
255                 } catch Error with {};
256                 push( @payments, $p );
257         }
258
259         return \@payments;
260 }
261
262
263
264 __PACKAGE__->register_method(
265         method  => "create_grocery_bill",
266         api_name        => "open-ils.circ.money.grocery.create",
267         notes           => <<"  NOTE");
268         Creates a new grocery transaction using the transaction object provided
269         PARAMS: (login_session, money.grocery (mg) object)
270         NOTE
271
272 sub create_grocery_bill {
273         my( $self, $client, $login, $transaction ) = @_;
274
275         my( $staff, $evt ) = $apputils->checkses($login);
276         return $evt if $evt;
277         $evt = $apputils->check_perms($staff->id, 
278                 $transaction->billing_location, 'CREATE_TRANSACTION' );
279         return $evt if $evt;
280
281
282         $logger->activity("Creating grocery bill " . Dumper($transaction) );
283
284         $transaction->clear_id;
285         my $session = $apputils->start_db_session;
286         my $transid = $session->request(
287                 'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
288
289         throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
290
291         $logger->debug("Created new grocery transaction $transid");
292         
293         $apputils->commit_db_session($session);
294
295
296
297         return $transid;
298 }
299
300 __PACKAGE__->register_method(
301         method  => "billing_items",
302         api_name        => "open-ils.circ.money.billing.retrieve.all",
303         notes           =><<"   NOTE");
304         Returns a list of billing items for the given transaction.
305         PARAMS( login, transaction_id )
306         NOTE
307
308 sub billing_items {
309         my( $self, $client, $login, $transid ) = @_;
310
311         my( $trans, $evt ) = $U->fetch_billable_xact($transid);
312         return $evt if $evt;
313
314         my $staff;
315         ($staff, $evt ) = $apputils->checkses($login);
316         return $evt if $evt;
317
318         if($staff->id ne $trans->usr) {
319                 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
320                 return $evt if $evt;
321         }
322         
323         return $apputils->simplereq( 'open-ils.cstore',
324                 'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
325 }
326
327
328 __PACKAGE__->register_method(
329         method  => "billing_items_create",
330         api_name        => "open-ils.circ.money.billing.create",
331         notes           =><<"   NOTE");
332         Creates a new billing line item
333         PARAMS( login, bill_object (mb) )
334         NOTE
335
336 sub billing_items_create {
337         my( $self, $client, $login, $billing ) = @_;
338
339         my $e = new_editor(authtoken => $login, xact => 1);
340         return $e->event unless $e->checkauth;
341         return $e->event unless $e->allowed('CREATE_BILL');
342
343         my $xact = $e->retrieve_money_billable_transaction($billing->xact)
344                 or return $e->event;
345
346         # if the transaction was closed, re-open it
347         if($xact->xact_finish) {
348                 $xact->clear_xact_finish;
349                 $e->update_money_billable_transaction($xact)
350                         or return $e->event;
351         }
352
353         $e->create_money_billing($billing) or return $e->event;
354         $e->commit;
355
356         # ------------------------------------------------------------------------------
357         # Update the patron penalty info in the DB
358         # ------------------------------------------------------------------------------
359         $U->update_patron_penalties(
360                 authtoken => $login,
361                 patronid  => $xact->usr,
362         );
363
364         return $billing->id;
365 }
366
367 __PACKAGE__->register_method(
368         method          =>      'void_bill',
369         api_name                => 'open-ils.circ.money.billing.void',
370         signature       => q/
371                 Voids a bill
372                 @param authtoken Login session key
373                 @param billid The id of the bill to void
374                 @return 1 on success, Event on error
375         /
376 );
377
378 sub void_bill {
379         my( $s, $c, $authtoken, $billid ) = @_;
380
381         #my $e = OpenILS::Utils::Editor->new( authtoken => $authtoken );
382         my $e = new_editor( authtoken => $authtoken );
383         return $e->event unless $e->checkauth;
384         return $e->event unless $e->allowed('VOID_BILLING');
385
386         my $bill = $e->retrieve_money_billing($billid)
387                 or return $e->event;
388
389         return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill) 
390                 if $bill->voided and $bill->voided =~ /t/io;
391
392         $bill->voided('t');
393         $bill->voider($e->requestor->id);
394         $bill->void_time('now');
395
396         $e->update_money_billing($bill) or return $e->event;
397         my $evt = _check_open_xact($e, $bill->xact);
398         return $evt if $evt;
399
400         $e->commit;
401
402         # ------------------------------------------------------------------------------
403         # Update the patron penalty info in the DB
404         # ------------------------------------------------------------------------------
405         my $xact = $e->retrieve_money_billable_transaction($bill->xact)
406                 or return $e->event;
407
408         $U->update_patron_penalties(
409                 authtoken => $authtoken,
410                 patronid  => $xact->usr,
411         );
412
413         return 1;
414 }
415
416 sub _check_open_xact {
417         my( $editor, $xactid ) = @_;
418
419         # Grab the transaction
420         my $xact = $editor->retrieve_money_billable_transaction($xactid)
421                 or return $editor->event;
422
423         # grab the summary and see how much is owed on this transaction
424         my $summary = $editor->retrieve_money_open_billable_transaction_summary($xactid)
425                 or return $editor->event;
426
427         # grab the circulation if it is a circ;
428         my $circ = $editor->retrieve_action_circulation($xactid);
429
430         # If nothing is owed on the transaction but it is still open
431         # and this transaction is not an open circulation, close it
432         if( 
433                 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
434                 ( !$circ or $circ->stop_fines )) {
435
436                 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
437                 $xact->xact_finish('now');
438                 $editor->update_money_billable_transaction($xact)
439                         or return $editor->event;
440                 return undef;
441         }
442
443         # If money is owed or a refund is due on the xact and xact_finish
444         # is set, clear it (to reopen the xact) and update
445         if( $summary->balance_owed != 0 and $xact->xact_finish ) {
446                 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
447                 $xact->clear_xact_finish;
448                 $editor->update_money_billable_transaction($xact)
449                         or return $editor->event;
450                 return undef;
451         }
452
453         return undef;
454 }
455
456
457
458 __PACKAGE__->register_method (
459         method => 'fetch_mbts',
460         api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
461 );
462 sub fetch_mbts {
463         my($s, $c, $authtoken, $id) = @_;
464
465         my $sum = $U->cstorereq(
466                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
467         return OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', id => $id) unless $sum;
468
469         my ($reqr, $evt) = $U->checkses($authtoken);
470         return $evt if $evt;
471
472         my $usr;
473         ($usr, $evt) = $U->fetch_user($sum->usr);
474         return $evt if $evt;
475
476         $evt = $U->check_perms($reqr->id, $usr->home_ou, 'VIEW_TRANSACTION');
477         return $evt if $evt;
478
479         return $sum;
480 }
481
482
483
484
485
486 1;
487
488
489