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