]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Money.pm
Improve the way information from payment card processors bubbles up to
[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 package OpenILS::Application::Circ::Money;
17 use base qw/OpenILS::Application/;
18 use strict; use warnings;
19 use OpenILS::Application::AppUtils;
20 my $apputils = "OpenILS::Application::AppUtils";
21 my $U = "OpenILS::Application::AppUtils";
22
23 use OpenSRF::EX qw(:try);
24 use OpenILS::Perm;
25 use Data::Dumper;
26 use OpenILS::Event;
27 use OpenSRF::Utils::Logger qw/:logger/;
28 use OpenILS::Utils::CStoreEditor qw/:funcs/;
29 use OpenILS::Utils::Penalty;
30
31 __PACKAGE__->register_method(
32     method => "make_payments",
33     api_name => "open-ils.circ.money.payment",
34     signature => {
35         desc => q/Create payments for a given user and set of transactions,
36             login must have CREATE_PAYMENT privileges.
37             If any payments fail, all are reverted back./,
38         params => [
39             {desc => 'Authtoken', type => 'string'},
40             {desc => q/Arguments Hash, supporting the following params:
41                 { 
42                     payment_type
43                     userid
44                     patron_credit
45                     note
46                     cc_args: {
47                         where_process   1 to use processor, !1 for out-of-band
48                         approval_code   (for out-of-band payment)
49                         type            (for out-of-band payment)
50                         number          (for call to payment processor)
51                         expire_month    (for call to payment processor)
52                         expire_year     (for call to payment processor)
53                         billing_first   (for call to payment processor)
54                         billing_last    (for call to payment processor)
55                         billing_address (for call to payment processor)
56                         billing_city    (for call to payment processor)
57                         billing_state   (for call to payment processor)
58                         billing_zip     (for call to payment processor)
59                         note            (if payments->{note} is blank, use this)
60                     },
61                     check_number
62                     payments: [ 
63                         [trans_id, amt], 
64                         [...]
65                     ], 
66                 }/, type => 'hash'
67             },
68         ],
69         "return" => {
70             "desc" =>
71                 q{1 on success, event on failure.  Event possibilities include:
72                 BAD_PARAMS
73                     (Bad parameters were given to this API method itself.
74                     See note field.)
75                 CREDIT_PROCESSOR_NOT_SPECIFIED
76                     (Evergreen has not been set up to process CC payments)
77                 CREDIT_PROCESSOR_NOT_ALLOWED
78                     (Evergreen has been incorrectly setup for CC payments)
79                 CREDIT_PROCESSOR_NOT_ENABLED
80                     (Evergreen has been set up for CC payments, but an admin
81                     has not explicitly enabled them)
82                 CREDIT_PROCESSOR_BAD_PARAMS
83                     (Evergreen has been incorrectly setup for CC payments;
84                     specifically, the login and/or password for the CC
85                     processor weren't provided)
86                 CREDIT_PROCESSOR_DECLINED_TRANSACTION
87                     (We contacted the CC processor to attempt the charge, but
88                     they declined it.  See the statusText field for their
89                     message.)
90                 CREDIT_PROCESSOR_SUCCESS_WO_RECORD
91                     (A payment was processed successfully, but couldn't be
92                     recorded in Evergreen.  This is bad bad bad, as it means
93                     somebody made a payment but isn't getting credit for it.
94                     See note field for more info.)
95 },
96             "type" => "number"
97         }
98     }
99 );
100 sub make_payments {
101     my($self, $client, $auth, $payments) = @_;
102
103     my $e = new_editor(authtoken => $auth, xact => 1);
104     return $e->die_event unless $e->checkauth;
105
106     my $type = $payments->{payment_type};
107     my $user_id = $payments->{userid};
108     my $credit = $payments->{patron_credit} || 0;
109     my $drawer = $e->requestor->wsid;
110     my $note = $payments->{note};
111     my $cc_args = $payments->{cc_args};
112     my $check_number = $payments->{check_number};
113     my $total_paid = 0;
114     my $this_ou = $e->requestor->ws_ou;
115     my %orgs;
116
117     # unless/until determined by payment processor API
118     my ($approval_code, $cc_processor, $cc_type) = (undef,undef,undef);
119
120     my $patron = $e->retrieve_actor_user($user_id) or return $e->die_event;
121
122     # A user is allowed to make credit card payments on his/her own behalf
123     # All other scenarious require permission
124     unless($type eq 'credit_card_payment' and $user_id == $e->requestor->id) {
125         return $e->die_event unless $e->allowed('CREATE_PAYMENT', $patron->home_ou);
126     }
127
128     # first collect the transactions and make sure the transaction
129     # user matches the requested user
130     my %xacts;
131     for my $pay (@{$payments->{payments}}) {
132         my $xact_id = $pay->[0];
133         my $xact = $e->retrieve_money_billable_transaction_summary($xact_id)
134             or return $e->die_event;
135         
136         if($xact->usr != $user_id) {
137             $e->rollback;
138             return OpenILS::Event->new('BAD_PARAMS', note => q/user does not match transaction/);
139         }
140
141         $xacts{$xact_id} = $xact;
142     }
143
144     my @payment_objs;
145
146     for my $pay (@{$payments->{payments}}) {
147         my $transid = $pay->[0];
148         my $amount = $pay->[1];
149         $amount =~ s/\$//og; # just to be safe
150         my $trans = $xacts{$transid};
151
152         $total_paid += $amount;
153
154         $orgs{$U->xact_org($transid, $e)} = 1;
155
156         # A negative payment is a refund.  
157         if( $amount < 0 ) {
158
159             # Negative credit card payments are not allowed
160             if($type eq 'credit_card_payment') {
161                 $e->rollback;
162                 return OpenILS::Event->new(
163                     'BAD_PARAMS', 
164                     note => q/Negative credit card payments not allowed/
165                 );
166             }
167
168             # If the refund causes the transaction balance to exceed 0 dollars, 
169             # we are in effect loaning the patron money.  This is not allowed.
170             if( ($trans->balance_owed - $amount) > 0 ) {
171                 $e->rollback;
172                 return OpenILS::Event->new('REFUND_EXCEEDS_BALANCE');
173             }
174
175             # Otherwise, make sure the refund does not exceed desk payments
176             # This is also not allowed
177             my $desk_total = 0;
178             my $desk_payments = $e->search_money_desk_payment({xact => $transid, voided => 'f'});
179             $desk_total += $_->amount for @$desk_payments;
180
181             if( (-$amount) > $desk_total ) {
182                 $e->rollback;
183                 return OpenILS::Event->new(
184                     'REFUND_EXCEEDS_DESK_PAYMENTS', 
185                     payload => { allowed_refund => $desk_total, submitted_refund => -$amount } );
186             }
187         }
188
189         my $payobj = "Fieldmapper::money::$type";
190         $payobj = $payobj->new;
191
192         $payobj->amount($amount);
193         $payobj->amount_collected($amount);
194         $payobj->xact($transid);
195         $payobj->note($note);
196         if ((not $payobj->note) and ($type eq 'credit_card_payment')) {
197             $payobj->note($cc_args->{note});
198         }
199
200         if ($payobj->has_field('accepting_usr')) { $payobj->accepting_usr($e->requestor->id); }
201         if ($payobj->has_field('cash_drawer')) { $payobj->cash_drawer($drawer); }
202         if ($payobj->has_field('cc_type')) { $payobj->cc_type($cc_args->{type}); }
203         if ($payobj->has_field('check_number')) { $payobj->check_number($check_number); }
204
205         # Store the last 4 digits of the CC number
206         if ($payobj->has_field('cc_number')) {
207             $payobj->cc_number(substr($cc_args->{number}, -4));
208         }
209         if ($payobj->has_field('expire_month')) { $payobj->expire_month($cc_args->{expire_month}); }
210         if ($payobj->has_field('expire_year')) { $payobj->expire_year($cc_args->{expire_year}); }
211         
212         # Note: It is important not to set approval_code
213         # on the fieldmapper object yet.
214
215         push(@payment_objs, $payobj);
216
217     } # all payment objects have been created and inserted. 
218
219     #### NO WRITES TO THE DB ABOVE THIS LINE -- THEY'LL ONLY BE DISCARDED  ###
220     $e->rollback;
221
222     # After we try to externally process a credit card (if desired), we'll
223     # open a new transaction.  We cannot leave one open while credit card
224     # processing might be happening, as it can easily time out the database
225     # transaction.
226     if($type eq 'credit_card_payment') {
227         $approval_code = $cc_args->{approval_code};
228         # If an approval code was not given, we'll need
229         # to call to the payment processor ourselves.
230         if ($cc_args->{where_process} == 1) {
231             return OpenILS::Event->new('BAD_PARAMS', note => 'Need CC number')
232                 if not $cc_args->{number};
233             my $response =
234                 OpenILS::Application::Circ::CreditCard::process_payment({
235                     "desc" => $cc_args->{note},
236                     "amount" => $total_paid,
237                     "patron_id" => $user_id,
238                     "cc" => $cc_args->{number},
239                     "expiration" => sprintf(
240                         "%02d-%04d",
241                         $cc_args->{expire_month},
242                         $cc_args->{expire_year}
243                     ),
244                     "ou" => $this_ou,
245                     "first_name" => $cc_args->{billing_first},
246                     "last_name" => $cc_args->{billing_last},
247                     "address" => $cc_args->{billing_address},
248                     "city" => $cc_args->{billing_city},
249                     "state" => $cc_args->{billing_state},
250                     "zip" => $cc_args->{billing_zip},
251                 });
252
253             if ($U->event_code($response)) { # non-success
254                 $logger->info(
255                     "Credit card payment for user $user_id failed: " .
256                     $response->{"textcode"} . " " .
257                     $response->{"payload"}->{"error_message"}
258                 );
259
260                 return $response;
261             } else {
262                 $approval_code = $response->{"payload"}->{"authorization"};
263                 $cc_type = $response->{"payload"}->{"card_type"};
264                 $cc_processor = $response->{"payload"}->{"processor"};
265                 $logger->info(
266                     "Credit card payment for user $user_id succeeded"
267                 );
268             }
269         } else {
270             return OpenILS::Event->new(
271                 'BAD_PARAMS', note => 'Need approval code'
272             ) if not $cc_args->{approval_code};
273         }
274     }
275
276     ### RE-OPEN TRANSACTION HERE ###
277     $e->xact_begin;
278
279     # create payment records
280     my $create_money_method = "create_money_" . $type;
281     for my $payment (@payment_objs) {
282         # update the transaction if it's done
283         my $amount = $payment->amount;
284         my $transid = $payment->xact;
285         my $trans = $xacts{$transid};
286         if( (my $cred = ($trans->balance_owed - $amount)) <= 0 ) {
287             # Any overpay on this transaction goes directly into patron
288             # credit making payment with existing patron credit.
289             $credit -= $amount if $type eq 'credit_payment';
290
291             $cred = -$cred;
292             $credit += $cred;
293             my $circ = $e->retrieve_action_circulation($transid);
294
295             if(!$circ || $circ->stop_fines) {
296                 # If this is a circulation, we can't close the transaction
297                 # unless stop_fines is set.
298                 $trans = $e->retrieve_money_billable_transaction($transid);
299                 $trans->xact_finish("now");
300                 if (!$e->update_money_billable_transaction($trans)) {
301                     $logger->warn("update_money_billable_transaction() " .
302                         "failed");
303                     $e->rollback;
304                     return OpenILS::Event->new(
305                         'CREDIT_PROCESSOR_SUCCESS_WO_RECORD',
306                         note => 'update_money_billable_transaction() failed'
307                     );
308                 }
309             }
310         }
311
312         $payment->approval_code($approval_code) if $approval_code;
313         $payment->cc_type($cc_type) if $cc_type;
314         $payment->cc_processor($cc_processor) if $cc_processor;
315         if (!$e->$create_money_method($payment)) {
316             $logger->warn("$create_money_method failed: " .
317                 Dumper($payment)); # won't contain CC number.
318             $e->rollback;
319             return OpenILS::Event->new(
320                 'CREDIT_PROCESSOR_SUCCESS_WO_RECORD',
321                 note => "$create_money_method failed"
322             );
323         }
324     }
325
326     my $evt = _update_patron_credit($e, $patron, $credit);
327     if ($evt) {
328         $logger->warn("_update_patron_credit() failed");
329         $e->rollback;
330         return OpenILS::Event->new(
331             'CREDIT_PROCESSOR_SUCCESS_WO_RECORD',
332             note => "_update_patron_credit() failed"
333         );
334     }
335
336     for my $org_id (keys %orgs) {
337         # calculate penalties for each of the affected orgs
338         $evt = OpenILS::Utils::Penalty->calculate_penalties(
339             $e, $user_id, $org_id
340         );
341         if ($evt) {
342             $logger->warn(
343                 "OpenILS::Utils::Penalty::calculate_penalties() failed"
344             );
345             $e->rollback;
346             return OpenILS::Event->new(
347                 'CREDIT_PROCESSOR_SUCCESS_WO_RECORD',
348                 note => "OpenILS::Utils::Penalty::calculate_penalties() failed"
349             );
350         }
351     }
352
353     $e->commit;
354     return 1;
355 }
356
357 sub _update_patron_credit {
358     my($e, $patron, $credit) = @_;
359     return undef if $credit == 0;
360     $patron->credit_forward_balance($patron->credit_forward_balance + $credit);
361     return OpenILS::Event->new('NEGATIVE_PATRON_BALANCE') if $patron->credit_forward_balance < 0;
362     $e->update_actor_user($patron) or return $e->die_event;
363     return undef;
364 }
365
366
367 __PACKAGE__->register_method(
368     method    => "retrieve_payments",
369     api_name    => "open-ils.circ.money.payment.retrieve.all_",
370     notes        => "Returns a list of payments attached to a given transaction"
371     );
372 sub retrieve_payments {
373     my( $self, $client, $login, $transid ) = @_;
374
375     my( $staff, $evt ) =  
376         $apputils->checksesperm($login, 'VIEW_TRANSACTION');
377     return $evt if $evt;
378
379     # XXX the logic here is wrong.. we need to check the owner of the transaction
380     # to make sure the requestor has access
381
382     # XXX grab the view, for each object in the view, grab the real object
383
384     return $apputils->simplereq(
385         'open-ils.cstore',
386         'open-ils.cstore.direct.money.payment.search.atomic', { xact => $transid } );
387 }
388
389
390 __PACKAGE__->register_method(
391     method    => "retrieve_payments2",
392     authoritative => 1,
393     api_name    => "open-ils.circ.money.payment.retrieve.all",
394     notes        => "Returns a list of payments attached to a given transaction"
395     );
396     
397 sub retrieve_payments2 {
398     my( $self, $client, $login, $transid ) = @_;
399
400     my $e = new_editor(authtoken=>$login);
401     return $e->event unless $e->checkauth;
402     return $e->event unless $e->allowed('VIEW_TRANSACTION');
403
404     my @payments;
405     my $pmnts = $e->search_money_payment({ xact => $transid });
406     for( @$pmnts ) {
407         my $type = $_->payment_type;
408         my $meth = "retrieve_money_$type";
409         my $p = $e->$meth($_->id) or return $e->event;
410         $p->payment_type($type);
411         $p->cash_drawer($e->retrieve_actor_workstation($p->cash_drawer))
412             if $p->has_field('cash_drawer');
413         push( @payments, $p );
414     }
415
416     return \@payments;
417 }
418
419 __PACKAGE__->register_method(
420     method    => "format_payment_receipt",
421     api_name  => "open-ils.circ.money.payment_receipt.print",
422     signature => {
423         desc   => 'Returns a printable receipt for the specified payments',
424         params => [
425             { desc => 'Authentication token',  type => 'string'},
426             { desc => 'Payment ID or array of payment IDs', type => 'number' },
427         ],
428         return => {
429             desc => q/An action_trigger.event object or error event./,
430             type => 'object',
431         }
432     }
433 );
434 __PACKAGE__->register_method(
435     method    => "format_payment_receipt",
436     api_name  => "open-ils.circ.money.payment_receipt.email",
437     signature => {
438         desc   => 'Emails a receipt for the specified payments to the user associated with the first payment',
439         params => [
440             { desc => 'Authentication token',  type => 'string'},
441             { desc => 'Payment ID or array of payment IDs', type => 'number' },
442         ],
443         return => {
444             desc => q/Undefined on success, otherwise an error event./,
445             type => 'object',
446         }
447     }
448 );
449
450 sub format_payment_receipt {
451     my($self, $conn, $auth, $mp_id) = @_;
452
453     my $mp_ids;
454     if (ref $mp_id ne 'ARRAY') {
455         $mp_ids = [ $mp_id ];
456     } else {
457         $mp_ids = $mp_id;
458     }
459
460     my $for_print = ($self->api_name =~ /print/);
461     my $for_email = ($self->api_name =~ /email/);
462     my $e = new_editor(authtoken => $auth);
463     return $e->event unless $e->checkauth;
464
465     my $payments = [];
466     for my $id (@$mp_ids) {
467
468         my $payment = $e->retrieve_money_payment([
469             $id,
470             {   flesh => 2,
471                 flesh_fields => {
472                     mp => ['xact'],
473                     mbt => ['usr']
474                 }
475             }
476         ]) or return OpenILS::Event->new('MP_NOT_FOUND');
477
478         return $e->event unless $e->allowed('VIEW_TRANSACTION', $payment->xact->usr->home_ou); 
479
480         push @$payments, $payment;
481     }
482
483     if ($for_print) {
484
485         return $U->fire_object_event(undef, 'money.format.payment_receipt.print', $payments, $$payments[0]->xact->usr->home_ou);
486
487     } elsif ($for_email) {
488
489         for my $p (@$payments) {
490             $U->create_events_for_hook('money.format.payment_receipt.email', $p, $p->xact->usr->home_ou, undef, undef, 1);
491         }
492     }
493
494     return undef;
495 }
496
497 __PACKAGE__->register_method(
498     method    => "create_grocery_bill",
499     api_name    => "open-ils.circ.money.grocery.create",
500     notes        => <<"    NOTE");
501     Creates a new grocery transaction using the transaction object provided
502     PARAMS: (login_session, money.grocery (mg) object)
503     NOTE
504
505 sub create_grocery_bill {
506     my( $self, $client, $login, $transaction ) = @_;
507
508     my( $staff, $evt ) = $apputils->checkses($login);
509     return $evt if $evt;
510     $evt = $apputils->check_perms($staff->id, 
511         $transaction->billing_location, 'CREATE_TRANSACTION' );
512     return $evt if $evt;
513
514
515     $logger->activity("Creating grocery bill " . Dumper($transaction) );
516
517     $transaction->clear_id;
518     my $session = $apputils->start_db_session;
519     my $transid = $session->request(
520         'open-ils.storage.direct.money.grocery.create', $transaction)->gather(1);
521
522     throw OpenSRF::EX ("Error creating new money.grocery") unless defined $transid;
523
524     $logger->debug("Created new grocery transaction $transid");
525     
526     $apputils->commit_db_session($session);
527
528     my $e = new_editor(xact=>1);
529     $evt = _check_open_xact($e, $transid);
530     return $evt if $evt;
531     $e->commit;
532
533     return $transid;
534 }
535
536
537 __PACKAGE__->register_method(
538     method => 'fetch_reservation',
539     api_name => 'open-ils.circ.booking.reservation.retrieve'
540 );
541 sub fetch_reservation {
542     my( $self, $conn, $auth, $id ) = @_;
543     my $e = new_editor(authtoken=>$auth);
544     return $e->event unless $e->checkauth;
545     return $e->event unless $e->allowed('VIEW_TRANSACTION'); # eh.. basically the same permission
546     my $g = $e->retrieve_booking_reservation($id)
547         or return $e->event;
548     return $g;
549 }
550
551 __PACKAGE__->register_method(
552     method   => 'fetch_grocery',
553     api_name => 'open-ils.circ.money.grocery.retrieve'
554 );
555 sub fetch_grocery {
556     my( $self, $conn, $auth, $id ) = @_;
557     my $e = new_editor(authtoken=>$auth);
558     return $e->event unless $e->checkauth;
559     return $e->event unless $e->allowed('VIEW_TRANSACTION'); # eh.. basically the same permission
560     my $g = $e->retrieve_money_grocery($id)
561         or return $e->event;
562     return $g;
563 }
564
565
566 __PACKAGE__->register_method(
567     method        => "billing_items",
568     api_name      => "open-ils.circ.money.billing.retrieve.all",
569     authoritative => 1,
570     signature     => {
571         desc   => 'Returns a list of billing items for the given transaction ID.  ' .
572                   'If the operator is not the owner of the transaction, the VIEW_TRANSACTION permission is required.',
573         params => [
574             { desc => 'Authentication token', type => 'string'},
575             { desc => 'Transaction ID',       type => 'number'}
576         ],
577         return => {
578             desc => 'Transaction object, event on error'
579         },
580     }
581 );
582
583 sub billing_items {
584     my( $self, $client, $login, $transid ) = @_;
585
586     my( $trans, $evt ) = $U->fetch_billable_xact($transid);
587     return $evt if $evt;
588
589     my $staff;
590     ($staff, $evt ) = $apputils->checkses($login);
591     return $evt if $evt;
592
593     if($staff->id ne $trans->usr) {
594         $evt = $U->check_perms($staff->id, $staff->home_ou, 'VIEW_TRANSACTION');
595         return $evt if $evt;
596     }
597     
598     return $apputils->simplereq( 'open-ils.cstore',
599         'open-ils.cstore.direct.money.billing.search.atomic', { xact => $transid } )
600 }
601
602
603 __PACKAGE__->register_method(
604     method   => "billing_items_create",
605     api_name => "open-ils.circ.money.billing.create",
606     notes    => <<"    NOTE");
607     Creates a new billing line item
608     PARAMS( login, bill_object (mb) )
609     NOTE
610
611 sub billing_items_create {
612     my( $self, $client, $login, $billing ) = @_;
613
614     my $e = new_editor(authtoken => $login, xact => 1);
615     return $e->die_event unless $e->checkauth;
616     return $e->die_event unless $e->allowed('CREATE_BILL');
617
618     my $xact = $e->retrieve_money_billable_transaction($billing->xact)
619         or return $e->die_event;
620
621     # if the transaction was closed, re-open it
622     if($xact->xact_finish) {
623         $xact->clear_xact_finish;
624         $e->update_money_billable_transaction($xact)
625             or return $e->die_event;
626     }
627
628     my $amt = $billing->amount;
629     $amt =~ s/\$//og;
630     $billing->amount($amt);
631
632     $e->create_money_billing($billing) or return $e->die_event;
633     my $evt = OpenILS::Utils::Penalty->calculate_penalties($e, $xact->usr, $U->xact_org($xact->id));
634     return $evt if $evt;
635     $e->commit;
636
637     return $billing->id;
638 }
639
640
641 __PACKAGE__->register_method(
642     method        =>    'void_bill',
643     api_name        => 'open-ils.circ.money.billing.void',
644     signature    => q/
645         Voids a bill
646         @param authtoken Login session key
647         @param billid Id for the bill to void.  This parameter may be repeated to reference other bills.
648         @return 1 on success, Event on error
649     /
650 );
651 sub void_bill {
652     my( $s, $c, $authtoken, @billids ) = @_;
653
654     my $e = new_editor( authtoken => $authtoken, xact => 1 );
655     return $e->die_event unless $e->checkauth;
656     return $e->die_event unless $e->allowed('VOID_BILLING');
657
658     my %users;
659     for my $billid (@billids) {
660
661         my $bill = $e->retrieve_money_billing($billid)
662             or return $e->die_event;
663
664         my $xact = $e->retrieve_money_billable_transaction($bill->xact)
665             or return $e->die_event;
666
667         if($U->is_true($bill->voided)) {
668             $e->rollback;
669             return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill);
670         }
671
672         my $org = $U->xact_org($bill->xact, $e);
673         $users{$xact->usr} = {} unless $users{$xact->usr};
674         $users{$xact->usr}->{$org} = 1;
675
676         $bill->voided('t');
677         $bill->voider($e->requestor->id);
678         $bill->void_time('now');
679     
680         $e->update_money_billing($bill) or return $e->die_event;
681         my $evt = _check_open_xact($e, $bill->xact, $xact);
682         return $evt if $evt;
683     }
684
685     # calculate penalties for all user/org combinations
686     for my $user_id (keys %users) {
687         for my $org_id (keys %{$users{$user_id}}) {
688             OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
689         }
690     }
691     $e->commit;
692     return 1;
693 }
694
695
696 __PACKAGE__->register_method(
697     method        =>    'edit_bill_note',
698     api_name        => 'open-ils.circ.money.billing.note.edit',
699     signature    => q/
700         Edits the note for a bill
701         @param authtoken Login session key
702         @param note The replacement note for the bills we're editing
703         @param billid Id for the bill to edit the note of.  This parameter may be repeated to reference other bills.
704         @return 1 on success, Event on error
705     /
706 );
707 sub edit_bill_note {
708     my( $s, $c, $authtoken, $note, @billids ) = @_;
709
710     my $e = new_editor( authtoken => $authtoken, xact => 1 );
711     return $e->die_event unless $e->checkauth;
712     return $e->die_event unless $e->allowed('UPDATE_BILL_NOTE');
713
714     for my $billid (@billids) {
715
716         my $bill = $e->retrieve_money_billing($billid)
717             or return $e->die_event;
718
719         $bill->note($note);
720         # 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.
721     
722         $e->update_money_billing($bill) or return $e->die_event;
723     }
724     $e->commit;
725     return 1;
726 }
727
728
729 __PACKAGE__->register_method(
730     method        =>    'edit_payment_note',
731     api_name        => 'open-ils.circ.money.payment.note.edit',
732     signature    => q/
733         Edits the note for a payment
734         @param authtoken Login session key
735         @param note The replacement note for the payments we're editing
736         @param paymentid Id for the payment to edit the note of.  This parameter may be repeated to reference other payments.
737         @return 1 on success, Event on error
738     /
739 );
740 sub edit_payment_note {
741     my( $s, $c, $authtoken, $note, @paymentids ) = @_;
742
743     my $e = new_editor( authtoken => $authtoken, xact => 1 );
744     return $e->die_event unless $e->checkauth;
745     return $e->die_event unless $e->allowed('UPDATE_PAYMENT_NOTE');
746
747     for my $paymentid (@paymentids) {
748
749         my $payment = $e->retrieve_money_payment($paymentid)
750             or return $e->die_event;
751
752         $payment->note($note);
753         # 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.
754     
755         $e->update_money_payment($payment) or return $e->die_event;
756     }
757
758     $e->commit;
759     return 1;
760 }
761
762 sub _check_open_xact {
763     my( $editor, $xactid, $xact ) = @_;
764
765     # Grab the transaction
766     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
767     return $editor->event unless $xact;
768     $xactid ||= $xact->id;
769
770     # grab the summary and see how much is owed on this transaction
771     my ($summary) = $U->fetch_mbts($xactid, $editor);
772
773     # grab the circulation if it is a circ;
774     my $circ = $editor->retrieve_action_circulation($xactid);
775
776     # If nothing is owed on the transaction but it is still open
777     # and this transaction is not an open circulation, close it
778     if( 
779         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
780         ( !$circ or $circ->stop_fines )) {
781
782         $logger->info("closing transaction ".$xact->id. ' becauase balance_owed == 0');
783         $xact->xact_finish('now');
784         $editor->update_money_billable_transaction($xact)
785             or return $editor->event;
786         return undef;
787     }
788
789     # If money is owed or a refund is due on the xact and xact_finish
790     # is set, clear it (to reopen the xact) and update
791     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
792         $logger->info("re-opening transaction ".$xact->id. ' becauase balance_owed != 0');
793         $xact->clear_xact_finish;
794         $editor->update_money_billable_transaction($xact)
795             or return $editor->event;
796         return undef;
797     }
798     return undef;
799 }
800
801
802 __PACKAGE__->register_method (
803     method => 'fetch_mbts',
804     authoritative => 1,
805     api_name => 'open-ils.circ.money.billable_xact_summary.retrieve'
806 );
807 sub fetch_mbts {
808     my( $self, $conn, $auth, $id) = @_;
809
810     my $e = new_editor(xact => 1, authtoken=>$auth);
811     return $e->event unless $e->checkauth;
812     my ($mbts) = $U->fetch_mbts($id, $e);
813
814     my $user = $e->retrieve_actor_user($mbts->usr)
815         or return $e->die_event;
816
817     return $e->die_event unless $e->allowed('VIEW_TRANSACTION', $user->home_ou);
818     $e->rollback;
819     return $mbts
820 }
821
822
823 __PACKAGE__->register_method(
824     method => 'desk_payments',
825     api_name => 'open-ils.circ.money.org_unit.desk_payments'
826 );
827 sub desk_payments {
828     my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
829     my $e = new_editor(authtoken=>$auth);
830     return $e->event unless $e->checkauth;
831     return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
832     my $data = $U->storagereq(
833         'open-ils.storage.money.org_unit.desk_payments.atomic',
834         $org, $start_date, $end_date );
835
836     $_->workstation( $_->workstation->name ) for(@$data);
837     return $data;
838 }
839
840
841 __PACKAGE__->register_method(
842     method => 'user_payments',
843     api_name => 'open-ils.circ.money.org_unit.user_payments'
844 );
845
846 sub user_payments {
847     my( $self, $conn, $auth, $org, $start_date, $end_date ) = @_;
848     my $e = new_editor(authtoken=>$auth);
849     return $e->event unless $e->checkauth;
850     return $e->event unless $e->allowed('VIEW_TRANSACTION', $org);
851     my $data = $U->storagereq(
852         'open-ils.storage.money.org_unit.user_payments.atomic',
853         $org, $start_date, $end_date );
854     for(@$data) {
855         $_->usr->card(
856             $e->retrieve_actor_card($_->usr->card)->barcode);
857         $_->usr->home_ou(
858             $e->retrieve_actor_org_unit($_->usr->home_ou)->shortname);
859     }
860     return $data;
861 }
862
863
864 __PACKAGE__->register_method(
865     method    => 'retrieve_credit_payable_balance',
866     api_name  => 'open-ils.circ.credit.payable_balance.retrieve',
867     authoritative => 1,
868     signature => {
869         desc   => q/Returns the total amount the patron can pay via credit card/,
870         params => [
871             { desc => 'Authentication token', type => 'string' },
872             { desc => 'User id', type => 'number' }
873         ],
874         return => { desc => 'The ID of the new provider' }
875     }
876 );
877
878 sub retrieve_credit_payable_balance {
879     my ( $self, $conn, $auth, $user_id ) = @_;
880     my $e = new_editor(authtoken => $auth);
881     return $e->event unless $e->checkauth;
882
883     my $user = $e->retrieve_actor_user($user_id) 
884         or return $e->event;
885
886     if($e->requestor->id != $user_id) {
887         return $e->event unless $e->allowed('VIEW_USER_TRANSACTIONS', $user->home_ou)
888     }
889
890     my $circ_orgs = $e->json_query({
891         "select" => {circ => ["circ_lib"]},
892         from     => "circ",
893         "where"  => {usr => $user_id, xact_finish => undef},
894         distinct => 1
895     });
896
897     my $groc_orgs = $e->json_query({
898         "select" => {mg => ["billing_location"]},
899         from     => "mg",
900         "where"  => {usr => $user_id, xact_finish => undef},
901         distinct => 1
902     });
903
904     my %hash;
905     for my $org ( @$circ_orgs, @$groc_orgs ) {
906         my $o = $org->{billing_location};
907         $o = $org->{circ_lib} unless $o;
908         next if $hash{$o};    # was $hash{$org}, but that doesn't make sense.  $org is a hashref and $o gets added in the next line.
909         $hash{$o} = $U->ou_ancestor_setting_value($o, 'credit.payments.allow', $e);
910     }
911
912     my @credit_orgs = map { $hash{$_} ? ($_) : () } keys %hash;
913     $logger->debug("credit: relevant orgs that allow credit payments => @credit_orgs");
914
915     my $xact_summaries =
916       OpenILS::Application::AppUtils->simplereq('open-ils.actor',
917         'open-ils.actor.user.transactions.have_charge', $auth, $user_id);
918
919     my $sum = 0.0;
920
921     for my $xact (@$xact_summaries) {
922
923         # make two lists and grab them in batch XXX
924         if ( $xact->xact_type eq 'circulation' ) {
925             my $circ = $e->retrieve_action_circulation($xact->id) or return $e->event;
926             next unless grep { $_ == $circ->circ_lib } @credit_orgs;
927
928         } elsif ($xact->xact_type eq 'grocery') {
929             my $bill = $e->retrieve_money_grocery($xact->id) or return $e->event;
930             next unless grep { $_ == $bill->billing_location } @credit_orgs;
931         } elsif ($xact->xact_type eq 'reservation') {
932             my $bill = $e->retrieve_booking_reservation($xact->id) or return $e->event;
933             next unless grep { $_ == $bill->pickup_lib } @credit_orgs;
934         }
935         $sum += $xact->balance_owed();
936     }
937
938     return $sum;
939 }
940
941
942 1;