]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Money.pm
added some basic log lines. Add the approval code in the newly created credit_card_p...
[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/OpenILS::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 use OpenILS::Utils::Penalty;
31
32 __PACKAGE__->register_method(
33         method => "make_payments",
34         api_name => "open-ils.circ.money.payment",
35     signature => {
36         desc => q/Create payments for a given user and set of transactions,
37                 login must have CREATE_PAYMENT priveleges.
38                 If any payments fail, all are reverted back./,
39         params => [
40             {desc => 'Authtoken', type => 'string'},
41             {desc => q/Arguments Hash, supporting the following params:
42                 { 
43                     payment_type
44                     userid
45                     patron_credit
46                     note
47                     cc_args : {
48                         type
49                         number
50                         expire_month
51                         expire_year
52                         approval_code
53                     }
54                     check_number
55                     payments: [ 
56                         [trans_id, amt], 
57                         [...]
58                     ], 
59                 }/, type => 'hash'
60             },
61         ]
62     }
63 );
64
65 sub make_payments {
66         my($self, $client, $auth, $payments) = @_;
67
68         my $e = new_editor(authtoken => $auth, xact => 1);
69     return $e->die_event unless $e->checkauth;
70
71         my $type = $payments->{payment_type};
72         my $user_id = $payments->{userid};
73         my $credit = $payments->{patron_credit} || 0;
74         my $drawer = $e->requestor->wsid;
75         my $note = $payments->{note};
76         my $check_number = $payments->{check_number};
77     my $cc_args = $payments->{cc_args};
78         my $total_paid = 0;
79     my %orgs;
80
81     my $patron = $e->retrieve_actor_user($user_id) or return $e->die_event;
82
83     # A user is allowed to make credit card payments on his/her own behalf
84     # All other scenarious require permission
85     unless($type eq 'credit_card_payment' and $user_id == $e->requestor->id) {
86             return $e->die_event unless $e->allowed('CREATE_PAYMENT', $patron->home_ou);
87     }
88
89     # first collect the transactions and make sure the transaction
90     # user matches the requested user
91     my %xacts;
92     for my $pay (@{$payments->{payments}}) {
93
94         my $xact_id = $pay->[0];
95         my $xact = $e->retrieve_money_billable_transaction_summary($xact_id)
96             or return $e->die_event;
97         
98         if($xact->usr != $user_id) {
99             $e->rollback;
100             return OpenILS::Event->new('BAD_PARAMS', note => q/user does not match transaction/);
101         }
102
103         $xacts{$xact_id} = $xact;
104     }
105
106     my @payment_objs;
107
108         for my $pay (@{$payments->{payments}}) {
109
110         my $transid = $pay->[0];
111                 my $amount = $pay->[1];
112                 $amount =~ s/\$//og; # just to be safe
113         my $trans = $xacts{$transid};
114
115                 $total_paid += $amount;
116
117         $orgs{$U->xact_org($transid, $e)} = 1;
118
119         # making payment with existing patron credit
120                 $credit -= $amount if $type eq 'credit_payment';
121
122                 # A negative payment is a refund.  
123                 if( $amount < 0 ) {
124
125             # Negative credit card payments are not allowed
126             if($type eq 'credit_card_payment') {
127                 $e->rollback;
128                                 return OpenILS::Event->new(
129                     'BAD_PARAMS', 
130                     note => q/Negative credit card payments not allowed/
131                 );
132             }
133
134                         # If the refund causes the transaction balance to exceed 0 dollars, 
135                         # we are in effect loaning the patron money.  This is not allowed.
136                         if( ($trans->balance_owed - $amount) > 0 ) {
137                 $e->rollback;
138                                 return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
139                         }
140
141                         # Otherwise, make sure the refund does not exceed desk payments
142                         # This is also not allowed
143                         my $desk_total = 0;
144                         my $desk_payments = $e->search_money_desk_payment({xact => $transid, voided => 'f'});
145                         $desk_total += $_->amount for @$desk_payments;
146
147                         if( (-$amount) > $desk_total ) {
148                 $e->rollback;
149                                 return OpenILS::Event->new(
150                                         'REFUND_EXCEEDS_DESK_PAYMENTS', 
151                                         payload => { allowed_refund => $desk_total, submitted_refund => -$amount } );
152                         }
153                 }
154
155                 my $payobj = "Fieldmapper::money::$type";
156                 $payobj = $payobj->new;
157
158                 $payobj->amount($amount);
159                 $payobj->amount_collected($amount);
160                 $payobj->xact($transid);
161                 $payobj->note($note);
162
163                 if ($payobj->has_field('accepting_usr')) { $payobj->accepting_usr($e->requestor->id); }
164                 if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
165                 if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_args->{type}); }
166                 if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
167
168         # Store the last 4 digits?
169                 #if ($payobj->has_field('cc_number')) { $payobj->cc_number($cc_args->{number}); }
170                 #if ($payobj->has_field('approval_code')) { $payobj->approval_code($cc_args->{approval_code}); }
171                 if ($payobj->has_field('expire_month')) { $payobj->expire_month($cc_args->{expire_month}); }
172                 if ($payobj->has_field('expire_year')) { $payobj->expire_year($cc_args->{expire_year}); }
173                 
174                 # update the transaction if it's done 
175                 if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
176
177                         # Any overpay on this transaction goes directly into patron credit 
178                         $cred = -$cred;
179                         $credit += $cred;
180             my $circ = $e->retrieve_action_circulation($transid);
181
182                         if(!$circ || $circ->stop_fines) {
183                             # If this is a circulation, we can't close the transaction unless stop_fines is set
184                 $trans = $e->retrieve_money_billable_transaction($transid);
185                                 $trans->xact_finish("now");
186                 $e->update_money_billable_transaction($trans) or return $e->die_event;
187                         }
188                 }
189
190         my $method = "create_money_$type";
191         $e->$method($payobj) or return $e->die_event;
192         push(@payment_objs, $payobj);
193
194         } # all payment objects have been created and inserted. 
195
196         my $evt = _update_patron_credit($e, $patron, $credit);
197         return $evt if $evt;
198
199     for my $org_id (keys %orgs) {
200         # calculate penalties for each of the affected orgs
201         $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
202         return $evt if $evt;
203     }
204
205     if($type eq 'credit_card_payment') {
206         my $this_ou = $e->requestor->ws_ou;
207         my $response = $apputils->simplereq(
208             'open-ils.credit',
209             'open-ils.credit.process',
210             {
211                 "desc" => $payments->{note},
212                 "amount" => $total_paid,
213                 "patron_id" => $user_id,
214                 "cc" => $payments->{cc_number},
215                 "expiration" => sprintf(
216                     "%02d-%04d",
217                     $payments->{expire_month},
218                     $payments->{expire_year}
219                 ),
220                 "ou" => $this_ou
221             }
222         );
223
224         if (exists $response->{ilsevent}) {
225             $e->rollback;
226             return $response;
227         }
228         if ($response->{statusCode} != 200) {
229             $e->rollback;
230             $logger->info("Credit card payment for user $user_id failed with message: " . $response->{statusText});
231             return OpenILS::Event->new(
232                 'CREDIT_PROCESSOR_DECLINED_TRANSACTION',
233                 note => $response->{statusText}
234             );
235         }
236
237         for my $payment (@payment_objs) {
238             $payment->approval_code($response->{approvalCode});
239             $e->update_money_credit_card_payment($payment) or return $e->die_event;
240         }
241         $logger->info("Credit card payment for user $user_id succeeded");
242     }
243
244     $e->commit;
245     return 1;
246 }
247
248
249 sub _update_patron_credit {
250         my($e, $patron, $credit) = @_;
251     return undef if $credit == 0;
252         $patron->credit_forward_balance($patron->credit_forward_balance + $credit);
253     return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE') if $patron->credit_forward_balance < 0;
254     $e->update_actor_user($patron) or return $e->die_event;
255         return undef;
256 }
257
258
259 __PACKAGE__->register_method(
260         method  => "retrieve_payments",
261         api_name        => "open-ils.circ.money.payment.retrieve.all_",
262         notes           => "Returns a list of payments attached to a given transaction"
263         );
264         
265 sub retrieve_payments {
266         my( $self, $client, $login, $transid ) = @_;
267
268         my( $staff, $evt ) =  
269                 $apputils->checksesperm($login, 'VIEW_TRANSACTION');
270         return $evt if $evt;
271
272         # XXX the logic here is wrong.. we need to check the owner of the transaction
273         # to make sure the requestor has access
274
275         # XXX grab the view, for each object in the view, grab the real object
276
277         return $apputils->simplereq(
278                 'open-ils.cstore',
279                 'open-ils.cstore.direct.money.payment.search.atomic', { xact => $transid } );
280 }
281
282
283
284 __PACKAGE__->register_method(
285         method  => "retrieve_payments2",
286     authoritative => 1,
287         api_name        => "open-ils.circ.money.payment.retrieve.all",
288         notes           => "Returns a list of payments attached to a given transaction"
289         );
290         
291 sub retrieve_payments2 {
292         my( $self, $client, $login, $transid ) = @_;
293
294         my $e = new_editor(authtoken=>$login);
295         return $e->event unless $e->checkauth;
296         return $e->event unless $e->allowed('VIEW_TRANSACTION');
297
298         my @payments;
299         my $pmnts = $e->search_money_payment({ xact => $transid });
300         for( @$pmnts ) {
301                 my $type = $_->payment_type;
302                 my $meth = "retrieve_money_$type";
303                 my $p = $e->$meth($_->id) or return $e->event;
304                 $p->payment_type($type);
305                 $p->cash_drawer($e->retrieve_actor_workstation($p->cash_drawer))
306                         if $p->has_field('cash_drawer');
307                 push( @payments, $p );
308         }
309
310         return \@payments;
311 }
312
313
314
315 __PACKAGE__->register_method(
316         method  => "create_grocery_bill",
317         api_name        => "open-ils.circ.money.grocery.create",
318         notes           => <<"  NOTE");
319         Creates a new grocery transaction using the transaction object provided
320         PARAMS: (login_session, money.grocery (mg) object)
321         NOTE
322
323 sub create_grocery_bill {
324         my( $self, $client, $login, $transaction ) = @_;
325
326         my( $staff, $evt ) = $apputils->checkses($login);
327         return $evt if $evt;
328         $evt = $apputils->check_perms($staff->id, 
329                 $transaction->billing_location, 'CREATE_TRANSACTION' );
330         return $evt if $evt;
331
332
333         $logger->activity("Creating grocery bill " . Dumper($transaction) );
334
335         $transaction->clear_id;
336         my $session = $apputils->start_db_session;
337         my $transid = $session->request(
338                 'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
339
340         throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
341
342         $logger->debug("Created new grocery transaction $transid");
343         
344         $apputils->commit_db_session($session);
345
346     my $e = new_editor(xact=>1);
347     $evt = _check_open_xact($e, $transid);
348     return $evt if $evt;
349     $e->commit;
350
351         return $transid;
352 }
353
354
355 __PACKAGE__->register_method(
356         method => 'fetch_grocery',
357         api_name => 'open-ils.circ.money.grocery.retrieve'
358 );
359
360 sub fetch_grocery {
361         my( $self, $conn, $auth, $id ) = @_;
362         my $e = new_editor(authtoken=>$auth);
363         return $e->event unless $e->checkauth;
364         return $e->event unless $e->allowed('VIEW_TRANSACTION'); # eh.. basically the same permission
365         my $g = $e->retrieve_money_grocery($id)
366                 or return $e->event;
367         return $g;
368 }
369
370
371 __PACKAGE__->register_method(
372         method  => "billing_items",
373     authoritative => 1,
374         api_name        => "open-ils.circ.money.billing.retrieve.all",
375         notes           =><<"   NOTE");
376         Returns a list of billing items for the given transaction.
377         PARAMS( login, transaction_id )
378         NOTE
379
380 sub billing_items {
381         my( $self, $client, $login, $transid ) = @_;
382
383         my( $trans, $evt ) = $U->fetch_billable_xact($transid);
384         return $evt if $evt;
385
386         my $staff;
387         ($staff, $evt ) = $apputils->checkses($login);
388         return $evt if $evt;
389
390         if($staff->id ne $trans->usr) {
391                 $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
392                 return $evt if $evt;
393         }
394         
395         return $apputils->simplereq( 'open-ils.cstore',
396                 'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
397 }
398
399
400 __PACKAGE__->register_method(
401         method  => "billing_items_create",
402         api_name        => "open-ils.circ.money.billing.create",
403         notes           =><<"   NOTE");
404         Creates a new billing line item
405         PARAMS( login, bill_object (mb) )
406         NOTE
407
408 sub billing_items_create {
409         my( $self, $client, $login, $billing ) = @_;
410
411         my $e = new_editor(authtoken => $login, xact => 1);
412         return $e->die_event unless $e->checkauth;
413         return $e->die_event unless $e->allowed('CREATE_BILL');
414
415         my $xact = $e->retrieve_money_billable_transaction($billing->xact)
416                 or return $e->die_event;
417
418         # if the transaction was closed, re-open it
419         if($xact->xact_finish) {
420                 $xact->clear_xact_finish;
421                 $e->update_money_billable_transaction($xact)
422                         or return $e->die_event;
423         }
424
425         my $amt = $billing->amount;
426         $amt =~ s/\$//og;
427         $billing->amount($amt);
428
429         $e->create_money_billing($billing) or return $e->die_event;
430     my $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $xact->usr, $U->xact_org($xact->id));
431     return $evt if $evt;
432         $e->commit;
433
434         return $billing->id;
435 }
436
437 __PACKAGE__->register_method(
438         method          =>      'void_bill',
439         api_name                => 'open-ils.circ.money.billing.void',
440         signature       => q/
441                 Voids a bill
442                 @param authtoken Login session key
443                 @param billid Id for the bill to void.  This parameter may be repeated to reference other bills.
444                 @return 1 on success, Event on error
445         /
446 );
447
448
449 sub void_bill {
450         my( $s, $c, $authtoken, @billids ) = @_;
451
452         my $e = new_editor( authtoken => $authtoken, xact => 1 );
453         return $e->die_event unless $e->checkauth;
454         return $e->die_event unless $e->allowed('VOID_BILLING');
455
456     my %users;
457     for my $billid (@billids) {
458
459             my $bill = $e->retrieve_money_billing($billid)
460                     or return $e->die_event;
461
462         my $xact = $e->retrieve_money_billable_transaction($bill->xact)
463             or return $e->die_event;
464
465         if($U->is_true($bill->voided)) {
466             $e->rollback;
467                 return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill);
468         }
469
470         my $org = $U->xact_org($bill->xact, $e);
471         $users{$xact->usr} = {} unless $users{$xact->usr};
472         $users{$xact->usr}->{$org} = 1;
473
474             $bill->voided('t');
475             $bill->voider($e->requestor->id);
476             $bill->void_time('now');
477     
478             $e->update_money_billing($bill) or return $e->die_event;
479             my $evt = _check_open_xact($e, $bill->xact, $xact);
480             return $evt if $evt;
481     }
482
483     # calculate penalties for all user/org combinations
484     for my $user_id (keys %users) {
485         for my $org_id (keys %{$users{$user_id}}) {
486             OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
487         }
488     }
489
490         $e->commit;
491         return 1;
492 }
493
494 __PACKAGE__->register_method(
495         method          =>      'edit_bill_note',
496         api_name                => 'open-ils.circ.money.billing.note.edit',
497         signature       => q/
498                 Edits the note for a bill
499                 @param authtoken Login session key
500         @param note The replacement note for the bills we're editing
501                 @param billid Id for the bill to edit the note of.  This parameter may be repeated to reference other bills.
502                 @return 1 on success, Event on error
503         /
504 );
505
506
507 sub edit_bill_note {
508         my( $s, $c, $authtoken, $note, @billids ) = @_;
509
510         my $e = new_editor( authtoken => $authtoken, xact => 1 );
511         return $e->die_event unless $e->checkauth;
512         return $e->die_event unless $e->allowed('UPDATE_BILL_NOTE');
513
514     for my $billid (@billids) {
515
516             my $bill = $e->retrieve_money_billing($billid)
517                     or return $e->die_event;
518
519             $bill->note($note);
520         # FIXME: Does this get audited?  Need some way so that the original creator of the bill does not get credit/blame for the new note.
521     
522             $e->update_money_billing($bill) or return $e->die_event;
523     }
524
525         $e->commit;
526         return 1;
527 }
528
529 __PACKAGE__->register_method(
530         method          =>      'edit_payment_note',
531         api_name                => 'open-ils.circ.money.payment.note.edit',
532         signature       => q/
533                 Edits the note for a payment
534                 @param authtoken Login session key
535         @param note The replacement note for the payments we're editing
536                 @param paymentid Id for the payment to edit the note of.  This parameter may be repeated to reference other payments.
537                 @return 1 on success, Event on error
538         /
539 );
540
541
542 sub edit_payment_note {
543         my( $s, $c, $authtoken, $note, @paymentids ) = @_;
544
545         my $e = new_editor( authtoken => $authtoken, xact => 1 );
546         return $e->die_event unless $e->checkauth;
547         return $e->die_event unless $e->allowed('UPDATE_PAYMENT_NOTE');
548
549     for my $paymentid (@paymentids) {
550
551             my $payment = $e->retrieve_money_payment($paymentid)
552                     or return $e->die_event;
553
554             $payment->note($note);
555         # FIXME: Does this get audited?  Need some way so that the original taker of the payment does not get credit/blame for the new note.
556     
557             $e->update_money_payment($payment) or return $e->die_event;
558     }
559
560         $e->commit;
561         return 1;
562 }
563
564 sub _check_open_xact {
565         my( $editor, $xactid, $xact ) = @_;
566
567         # Grab the transaction
568         $xact ||= $editor->retrieve_money_billable_transaction($xactid);
569     return $editor->event unless $xact;
570     $xactid ||= $xact->id;
571
572         # grab the summary and see how much is owed on this transaction
573         my ($summary) = $U->fetch_mbts($xactid, $editor);
574
575         # grab the circulation if it is a circ;
576         my $circ = $editor->retrieve_action_circulation($xactid);
577
578         # If nothing is owed on the transaction but it is still open
579         # and this transaction is not an open circulation, close it
580         if( 
581                 ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
582                 ( !$circ or $circ->stop_fines )) {
583
584                 $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
585                 $xact->xact_finish('now');
586                 $editor->update_money_billable_transaction($xact)
587                         or return $editor->event;
588                 return undef;
589         }
590
591         # If money is owed or a refund is due on the xact and xact_finish
592         # is set, clear it (to reopen the xact) and update
593         if( $summary->balance_owed != 0 and $xact->xact_finish ) {
594                 $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
595                 $xact->clear_xact_finish;
596                 $editor->update_money_billable_transaction($xact)
597                         or return $editor->event;
598                 return undef;
599         }
600
601         return undef;
602 }
603
604
605
606 __PACKAGE__->register_method (
607         method => 'fetch_mbts',
608     authoritative => 1,
609         api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
610 );
611 sub fetch_mbts {
612         my( $self, $conn, $auth, $id) = @_;
613
614         my $e = new_editor(xact => 1, authtoken=>$auth);
615         return $e->event unless $e->checkauth;
616         my ($mbts) = $U->fetch_mbts($id, $e);
617
618         my $user = $e->retrieve_actor_user($mbts->usr)
619                 or return $e->die_event;
620
621         return $e->die_event unless $e->allowed('VIEW_TRANSACTION', $user->home_ou);
622         $e->rollback;
623         return $mbts
624 }
625
626
627
628 __PACKAGE__->register_method(
629         method => 'desk_payments',
630         api_name => 'open-ils.circ.money.org_unit.desk_payments'
631 );
632
633 sub desk_payments {
634         my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
635         my $e = new_editor(authtoken=>$auth);
636         return $e->event unless $e->checkauth;
637         return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
638         my $data = $U->storagereq(
639                 'open-ils.storage.money.org_unit.desk_payments.atomic',
640                 $org, $start_date, $end_date );
641
642         $_->workstation( $_->workstation->name ) for(@$data);
643         return $data;
644 }
645
646
647 __PACKAGE__->register_method(
648         method => 'user_payments',
649         api_name => 'open-ils.circ.money.org_unit.user_payments'
650 );
651
652 sub user_payments {
653         my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
654         my $e = new_editor(authtoken=>$auth);
655         return $e->event unless $e->checkauth;
656         return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
657         my $data = $U->storagereq(
658                 'open-ils.storage.money.org_unit.user_payments.atomic',
659                 $org, $start_date, $end_date );
660         for(@$data) {
661                 $_->usr->card(
662                         $e->retrieve_actor_card($_->usr->card)->barcode);
663                 $_->usr->home_ou(
664                         $e->retrieve_actor_org_unit($_->usr->home_ou)->shortname);
665         }
666         return $data;
667 }
668
669
670
671
672 1;
673
674
675