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