1 package OpenILS::Application::Circ::CircCommon;
2 use strict; use warnings;
4 use DateTime::Format::ISO8601;
5 use OpenILS::Application::AppUtils;
6 use OpenSRF::Utils qw/:datetime/;
8 use OpenSRF::Utils::Logger qw(:logger);
9 use OpenILS::Utils::CStoreEditor q/:funcs/;
10 use OpenILS::Const qw/:const/;
12 use List::MoreUtils qw(uniq);
14 my $U = "OpenILS::Application::AppUtils";
15 my $parser = DateTime::Format::ISO8601->new;
17 # -----------------------------------------------------------------
18 # Do not publish methods here. This code is shared across apps.
19 # -----------------------------------------------------------------
22 # -----------------------------------------------------------------
23 # Voids (or zeros) overdue fines on the given circ. if a backdate is
24 # provided, then we only void back to the backdate, unless the
25 # backdate is to within the grace period, in which case we void all
27 # -----------------------------------------------------------------
29 #compatibility layer - TODO
31 sub void_or_zero_overdues {
32 my($class, $e, $circ, $opts) = @_;
39 if( $opts->{backdate} ) {
40 my $backdate = $opts->{backdate};
41 # ------------------------------------------------------------------
42 # Fines for overdue materials are assessed up to, but not including,
43 # one fine interval after the fines are applicable. Here, we add
44 # one fine interval to the backdate to ensure that we are not
45 # voiding fines that were applicable before the backdate.
46 # ------------------------------------------------------------------
48 # if there is a raw time component (e.g. from postgres),
49 # turn it into an interval that interval_to_seconds can parse
50 my $duration = $circ->fine_interval;
51 $duration =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
52 my $interval = OpenSRF::Utils->interval_to_seconds($duration);
54 my $date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($backdate));
55 my $due_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date))->epoch;
56 my $grace_period = extend_grace_period( $class, $circ->circ_lib, $circ->due_date, OpenSRF::Utils->interval_to_seconds($circ->grace_period), $e);
57 if($date->epoch <= $due_date + $grace_period) {
58 $logger->info("backdate $backdate is within grace period, voiding all");
60 $backdate = $U->epoch2ISO8601($date->epoch + $interval);
61 $logger->info("applying backdate $backdate in overdue voiding");
62 $$bill_search{billing_ts} = {'>=' => $backdate};
66 my $billids = $e->search_money_billing([$bill_search, {idlist=>1}]);
67 if ($billids && @$billids) {
68 # overdue settings come from transaction org unit
69 my $prohibit_neg_balance_overdues = (
70 $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.prohibit_negative_balance_on_overdues')
72 $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.prohibit_negative_balance_default')
74 my $neg_balance_interval_overdues = (
75 $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.negative_balance_interval_on_overdues')
77 $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.negative_balance_interval_default')
80 # if we prohibit negative overdue balances and all payments
81 # are outside the refund interval (if given), zero the transaction
82 if ($opts->{force_zero}
83 or (!$opts->{force_void}
85 $U->is_true($prohibit_neg_balance_overdues)
86 and !_has_refundable_payments($e, $circ->id, $neg_balance_interval_overdues)
90 $result = $class->adjust_bills_to_zero($e, $billids, $opts->{note}, $neg_balance_interval_overdues);
92 # otherwise, just void the usual way
93 $result = $class->void_bills($e, $billids, $opts->{note});
103 # ------------------------------------------------------------------
104 # remove charge from patron's account if lost item is returned
105 # ------------------------------------------------------------------
107 my ($class, $e, $circ, $btype) = @_;
109 my $bills = $e->search_money_billing(
117 $logger->debug("voiding lost item charge of ".scalar(@$bills));
118 for my $bill (@$bills) {
119 if( !$U->is_true($bill->voided) ) {
120 $logger->info("lost item returned - voiding bill ".$bill->id);
122 $bill->void_time('now');
123 $bill->voider($e->requestor->id);
124 my $note = ($bill->note) ? $bill->note . "\n" : '';
125 $bill->note("${note}System: VOIDED FOR LOST ITEM RETURNED");
128 unless $e->update_money_billing($bill);
134 # ------------------------------------------------------------------
135 # Void (or zero) all bills of a given type on a circulation.
137 # Takes an editor, a circ object, the btype number for the bills you
138 # want to void, and an optional note.
140 # Returns undef on success or the result from void_bills.
141 # ------------------------------------------------------------------
142 sub void_or_zero_bills_of_type {
143 my ($class, $e, $circ, $copy, $btype, $for_note) = @_;
145 my $billids = $e->search_money_billing(
146 {xact => $circ->id(), btype => $btype},
149 if ($billids && @$billids) {
150 # settings for lost come from copy circlib.
151 my $prohibit_neg_balance_lost = (
152 $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.prohibit_negative_balance_on_lost')
154 $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.prohibit_negative_balance_default')
156 my $neg_balance_interval_lost = (
157 $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.negative_balance_interval_on_lost')
159 $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.negative_balance_interval_default')
163 $U->is_true($prohibit_neg_balance_lost)
164 and !_has_refundable_payments($e, $circ->id, $neg_balance_interval_lost)
166 $result = $class->adjust_bills_to_zero($e, $billids, "System: ADJUSTED $for_note");
168 $result = $class->void_bills($e, $billids, "System: VOIDED $for_note");
179 my($class, $e, $xactid) = @_;
181 # -----------------------------------------------------------------
182 # make sure the transaction is not closed
183 my $xact = $e->retrieve_money_billable_transaction($xactid)
184 or return $e->die_event;
186 if( $xact->xact_finish ) {
187 my ($mbts) = $U->fetch_mbts($xactid, $e);
188 if( $mbts->balance_owed != 0 ) {
189 $logger->info("* re-opening xact $xactid, orig xact_finish is ".$xact->xact_finish);
190 $xact->clear_xact_finish;
191 $e->update_money_billable_transaction($xact)
192 or return $e->die_event;
201 my($class, $e, $amount, $btype, $type, $xactid, $note) = @_;
203 $logger->info("The system is charging $amount [$type] on xact $xactid");
204 $note ||= 'SYSTEM GENERATED';
206 # -----------------------------------------------------------------
207 # now create the billing
208 my $bill = Fieldmapper::money::billing->new;
209 $bill->xact($xactid);
210 $bill->amount($amount);
211 $bill->billing_type($type);
212 $bill->btype($btype);
214 $e->create_money_billing($bill) or return $e->die_event;
219 sub extend_grace_period {
220 my($class, $circ_lib, $due_date, $grace_period, $e, $h) = @_;
221 if ($grace_period >= 86400) { # Only extend grace periods greater than or equal to a full day
222 my $parser = DateTime::Format::ISO8601->new;
223 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
224 my $due = $due_dt->epoch;
226 my $grace_extend = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend');
227 $e = new_editor() if (!$e);
228 $h = $e->retrieve_actor_org_unit_hours_of_operation($circ_lib) if (!$h);
229 if ($grace_extend and $h) {
230 my $new_grace_period = $grace_period;
232 $logger->info( "Circ lib has an hours-of-operation entry and grace period extension is enabled." );
237 my $dow_open = "dow_${i}_open";
238 my $dow_close = "dow_${i}_close";
239 if($h->$dow_open() eq '00:00:00' and $h->$dow_close() eq '00:00:00') {
248 $logger->info("Circ lib is closed all week according to hours-of-operation entry. Skipping grace period extension checks.");
250 # Extra nice grace periods
251 # AKA, merge closed dates trailing the grace period into the grace period
252 my $grace_extend_into_closed = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend.into_closed');
253 $due += 86400 if $grace_extend_into_closed;
255 my $grace_extend_all = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend.all');
257 if ( $grace_extend_all ) {
258 # Start checking the day after the item was due
259 # This is "The grace period only counts open days"
260 # NOTE: Adding 86400 seconds is not the same as adding one day. This uses seconds intentionally.
261 $due_dt = $due_dt->add( seconds => 86400 );
263 # Jump to the end of the grace period
264 # This is "If the grace period ends on a closed day extend it"
265 # NOTE: This adds grace period as a number of seconds intentionally
266 $due_dt = $due_dt->add( seconds => $grace_period );
269 my $count = 0; # Infinite loop protection
271 $closed = 0; # Starting assumption for day: We are not closed
272 $count++; # We limit the number of loops below.
274 # get the day of the week for the day we are looking at
275 my $dow = $due_dt->day_of_week_0;
277 # Check hours of operation first.
278 if ($h_closed{$dow}) {
280 $new_grace_period += 86400;
281 $due_dt->add( seconds => 86400 );
283 # Check for closed dates for this period
284 my $timestamptz = $due_dt->strftime('%FT%T%z');
285 my $cl = $e->search_actor_org_unit_closed_date(
286 { close_start => { '<=' => $timestamptz },
287 close_end => { '>=' => $timestamptz },
288 org_unit => $circ_lib }
293 my $cl_dt = $parser->parse_datetime( cleanse_ISO8601( $_->close_end ) );
294 while ($due_dt <= $cl_dt) {
295 $due_dt->add( seconds => 86400 );
296 $new_grace_period += 86400;
300 $due_dt->add( seconds => 86400 );
303 } while ( $count <= 366 and ( $closed or $due_dt->epoch <= $due + $new_grace_period ) );
304 if ($new_grace_period > $grace_period) {
305 $grace_period = $new_grace_period;
306 $logger->info( "Grace period for circ extended to $grace_period [" . seconds_to_interval( $grace_period ) . "]" );
311 return $grace_period;
314 # check if a circulation transaction can be closed
315 # takes a CStoreEditor and a circ transaction.
316 # Returns 1 if the circ should be closed, 0 if not.
318 my ($class, $e, $circ) = @_;
321 my $reason = $circ->stop_fines;
323 # We definitely want to close if this circulation was
324 # checked in or renewed.
325 if ($circ->checkin_time) {
327 } elsif ($reason eq OILS_STOP_FINES_LOST) {
328 # Check the copy circ_lib to see if they close
329 # transactions when lost are paid.
330 my $copy = $e->retrieve_asset_copy($circ->target_copy);
332 $can_close = !$U->is_true(
333 $U->ou_ancestor_setting_value(
335 'circ.lost.xact_open_on_zero',
341 } elsif ($reason eq OILS_STOP_FINES_LONGOVERDUE) {
342 # Check the copy circ_lib to see if they close
343 # transactions when long-overdue are paid.
344 my $copy = $e->retrieve_asset_copy($circ->target_copy);
346 $can_close = !$U->is_true(
347 $U->ou_ancestor_setting_value(
349 'circ.longoverdue.xact_open_on_zero',
359 sub seconds_to_interval_hash {
360 my $interval = shift;
361 my $limit = shift || 's';
362 $limit =~ s/^(.)/$1/o;
366 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
367 my ($year, $month, $week, $day, $hour, $minute, $second) =
368 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
370 if ($y = int($interval / (60 * 60 * 24 * 365))) {
372 $ym = $interval % (60 * 60 * 24 * 365);
376 return %output if ($limit eq 'y');
378 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
379 $output{$month} = $M;
380 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
384 return %output if ($limit eq 'M');
386 if ($w = int($Mm / 604800)) {
392 return %output if ($limit eq 'w');
394 if ($d = int($wm / 86400)) {
400 return %output if ($limit eq 'd');
402 if ($h = int($dm / 3600)) {
408 return %output if ($limit eq 'h');
410 if ($m = int($hm / 60)) {
411 $output{$minute} = $m;
416 return %output if ($limit eq 'm');
419 $output{$second} = $s;
421 $output{$second} = 0 unless (keys %output);
427 my ($class, $args) = @_;
428 my $circs = $args->{circs};
429 return unless $circs and @$circs;
430 my $e = $args->{editor};
431 # if a client connection is passed in, this will be chatty like
432 # the old storage version
433 my $conn = $args->{conn};
437 # Transactions are opened/closed with each circ, reservation, etc.
438 # The first $e->xact_begin (below) will cause a connect.
443 my %hoo = map { ( $_->id => $_ ) } @{ $e->retrieve_all_actor_org_unit_hours_of_operation };
445 my $handling_resvs = 0;
446 for my $c (@$circs) {
450 if (!$ctype) { # we received only an idlist, not objects
451 if ($handling_resvs) {
452 $c = $e->retrieve_booking_reservation($c);
453 } elsif (not defined $c) {
454 # an undef value is the indicator that we are moving
455 # from processing circulations to reservations.
459 $c = $e->retrieve_action_circulation($c);
464 $ctype =~ s/^.+::(\w+)$/$1/;
466 my $due_date_method = 'due_date';
467 my $target_copy_method = 'target_copy';
468 my $circ_lib_method = 'circ_lib';
469 my $recurring_fine_method = 'recurring_fine';
470 my $is_reservation = 0;
471 if ($ctype eq 'reservation') {
473 $due_date_method = 'end_time';
474 $target_copy_method = 'current_resource';
475 $circ_lib_method = 'pickup_lib';
476 $recurring_fine_method = 'fine_amount';
477 next unless ($c->fine_interval);
479 #TODO: reservation grace periods
480 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
484 # Clean up after previous transaction.
485 # This is a no-op if there is no open transaction.
486 $e->xact_rollback if $commit;
488 $logger->info(sprintf("Processing $ctype %d...", $c->id));
490 # each (ils) transaction is processed in its own (db) transaction
491 $e->xact_begin if $commit;
493 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
495 my $due = $due_dt->epoch;
498 my $fine_interval = $c->fine_interval;
499 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
500 $fine_interval = interval_to_seconds( $fine_interval );
502 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
503 $conn->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" ) if $conn;
504 $logger->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
508 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
510 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
511 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
514 $due -= ($due % $fine_interval) + $tz_offset_s;
515 $now -= ($now % $fine_interval) + $tz_offset_s;
519 "ARG! Overdue $ctype ".$c->id.
520 " for item ".$c->$target_copy_method.
521 " (user ".$c->usr.").\n".
522 "\tItem was due on or before: ".localtime($due)."\n") if $conn;
524 my @fines = @{$e->search_money_billing([
527 billing_ts => { '>' => $c->$due_date_method } },
528 { order_by => {mb => 'billing_ts DESC'}}
532 my $fine = $fines[$f_idx] if (@fines);
533 my $current_fine_total = 0;
534 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$U->is_true($_->voided) } @fines);
538 $conn->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")") if $conn;
539 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
541 $logger->info( "Potential first billing for circ ".$c->id );
544 $grace_period = extend_grace_period($class, $c->$circ_lib_method,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
547 return if ($last_fine > $now);
548 # Generate fines for each past interval, including the one we are inside
549 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
551 if ( $last_fine == $due # we have no fines yet
552 && $grace_period # and we have a grace period
553 && $now < $due + $grace_period # and some date math says were are within the grace period
555 $conn->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" ) if $conn;
556 $logger->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
560 $conn->respond( "\t$pending_fine_count pending fine(s)\n" ) if $conn;
561 return unless ($pending_fine_count);
563 my $recurring_fine = int($c->$recurring_fine_method * 100);
564 my $max_fine = int($c->max_fine * 100);
566 my $skip_closed_check = $U->ou_ancestor_setting_value(
567 $c->$circ_lib_method, 'circ.fines.charge_when_closed');
568 $skip_closed_check = $U->is_true($skip_closed_check);
570 my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
571 $c->$circ_lib_method, 'circ.fines.truncate_to_max_fine');
572 $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
574 my ($latest_billing_ts, $latest_amount) = ('',0);
575 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
577 if ($current_fine_total >= $max_fine) {
578 if ($ctype eq 'circulation') {
579 $c->stop_fines('MAXFINES');
580 $c->stop_fines_time('now');
581 $e->update_action_circulation($c);
584 "\tMaximum fine level of ".$c->max_fine.
585 " reached for this $ctype.\n".
586 "\tNo more fines will be generated.\n" ) if $conn;
590 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
591 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
592 my $current_bill_count = $bill;
593 while ( $current_bill_count ) {
594 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
595 $current_bill_count--;
598 my $timestamptz = $billing_ts->strftime('%FT%T%z');
599 if (!$skip_closed_check) {
600 my $dow = $billing_ts->day_of_week_0();
601 my $dow_open = "dow_${dow}_open";
602 my $dow_close = "dow_${dow}_close";
604 if (my $h = $hoo{$c->$circ_lib_method}) {
605 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
608 my @cl = @{$e->search_actor_org_unit_closed_date(
609 { close_start => { '<=' => $timestamptz },
610 close_end => { '>=' => $timestamptz },
611 org_unit => $c->$circ_lib_method }
616 # The billing amount for this billing normally ought to be the recurring fine amount.
617 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
618 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
619 my $this_billing_amount = $recurring_fine;
620 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
621 $this_billing_amount = ($max_fine - $current_fine_total);
623 $current_fine_total += $this_billing_amount;
624 $latest_amount += $this_billing_amount;
625 $latest_billing_ts = $timestamptz;
627 my $bill = Fieldmapper::money::billing->new;
629 $bill->note("System Generated Overdue Fine");
630 $bill->billing_type("Overdue materials");
632 $bill->amount(sprintf('%0.2f', $this_billing_amount/100));
633 $bill->billing_ts($timestamptz);
634 $e->create_money_billing($bill);
638 $conn->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
639 if ($conn and $latest_billing_ts and $latest_amount);
642 # Calculate penalties inline
643 OpenILS::Utils::Penalty->calculate_penalties(
644 $e, $c->usr, $c->$circ_lib_method);
646 $e->xact_commit if $commit;
652 $conn->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" ) if $conn;
653 $logger->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
654 last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
658 # roll back any (potentially) orphaned transaction and disconnect.
659 $e->rollback if $commit;
664 # -----------------------------------------------------------------
665 # Given an editor and a xact, return a reference to an array of
666 # hashrefs that map billing objects to payment objects. Returns undef
667 # if no bills are found for the given transaction.
669 # The bill amounts are adjusted to reflect the application of the
670 # payments to the bills. The original bill amounts are retained in
673 # The payment objects may or may not have their amounts adjusted
674 # depending on whether or not they apply to more than one bill. We
675 # could really use a better logic here, perhaps, but if it was
676 # consistent, it wouldn't be Evergreen.
678 # The data structure used in the array is a hashref that has the
681 # bill => the adjusted bill object
682 # voids => an arrayref of void payments that apply directly to the
684 # payments => an arrayref of payment objects applied to the bill
685 # bill_amount => original amount from the billing object
686 # void_amount => total of the void payments that apply directly to the
689 # Each bill is only mapped to payments one time. However, a single
690 # payment may be mapped to more than one bill if the payment amount is
691 # greater than the amount of each individual bill, such as a $3.00
692 # payment for 30 $0.10 overdue bills. There is an attempt made to
693 # first pay bills with payments that match the billing amount. This
694 # is intended to catch payments for lost and/or long overdue bills so
695 # that they will match up.
697 # This function is heavily adapted from code written by Jeff Godin of
698 # Traverse Area District Library and submitted on LaunchPad bug
700 # -----------------------------------------------------------------
701 sub bill_payment_map_for_xact {
702 my ($class, $e, $xact) = @_;
704 # Check for CStoreEditor and make a new one if we have to. This
705 # allows one-off calls to this subroutine to pass undef as the
706 # CStoreEditor and not have to create one of their own.
707 $e = OpenILS::Utils::CStoreEditor->new unless ($e);
709 # find all bills in order
711 {xact => $xact->id()},
712 { order_by => { mb => { billing_ts => { direction => 'asc' } } } },
715 # At some point, we should get rid of the voided column on
716 # money.payment and family. It is not exposed in the client at
717 # the moment, and should be replaced with a void_bill type. The
718 # descendants of money.payment don't expose the voided field in
719 # the fieldmapper, only the mp object, based on the money.payment
720 # view, does. However, I want to leave that complication for
721 # later. I wonder if I'm not slowing things down too much with
722 # the current adjustment_payment logic. It would probably be faster if
723 # we had direct Pg access at this layer. I can probably wrangle
724 # something via the drivers or store interfaces, but I haven't
725 # really figured those out, yet.
727 my $bills = $e->search_money_billing($bill_search);
729 # return undef if there are no bills.
730 return undef unless ($bills && @$bills);
732 # map the bills into our bill_payment_map entry format:
736 bill_amount => $_->amount(),
743 # Find all unvoided payments in order. Flesh voids so that we
744 # don't have to retrieve them later.
745 my $payments = $e->search_money_payment(
747 { xact => $xact->id, voided=>'f' },
749 order_by => { mp => { payment_ts => { direction => 'asc' } } },
751 flesh_fields => { mp => ['adjustment_payment'] }
756 # If there were no payments, then we just return the bills.
757 return \@entries unless ($payments && @$payments);
759 # Now, we go through the rigmarole of mapping payments to bills
760 # and adjusting the bill balances.
762 # Apply the voids before "paying" other bills.
763 foreach my $entry (@entries) {
764 my $bill = $entry->{bill};
765 # Find only the voids that apply to individual bills.
766 my @voids = map {$_->adjustment_payment()} grep {$_->payment_type() eq 'adjustment_payment' && $_->adjustment_payment()->billing() == $bill->id()} @$payments;
768 foreach my $void (@voids) {
769 my $new_amount = $U->fpdiff($bill->amount(),$void->amount());
770 if ($new_amount >= 0) {
771 push @{$entry->{voids}}, $void;
772 $entry->{void_amount} += $void->amount();
773 $bill->amount($new_amount);
774 # Remove the used up void from list of payments:
775 my @p = grep {$_->id() != $void->id()} @$payments;
778 # It should never happen that we have more void
779 # payments on a single bill than the amount of the
780 # bill. However, experience shows that the things
781 # that should never happen actually do happen with
782 # surprising regularity in a library setting.
784 # Clone the void to say how much of it actually
785 # applied to this bill.
786 my $new_void = $void->clone();
787 $new_void->amount($bill->amount());
788 $new_void->amount_collected($bill->amount());
789 push (@{$entry->{voids}}, $new_void);
790 $entry->{void_amount} += $new_void->amount();
792 $void->amount(-$new_amount);
793 # Could be a candidate for YAOUS about what to do
794 # with excess void amounts on a bill.
796 last if ($bill->amount() == 0);
801 # Try to map payments to bills by amounts starting with the
803 foreach my $payment (sort {$b->amount() <=> $a->amount()} @$payments) {
804 my @bills2pay = grep {$_->{bill}->amount() == $payment->amount()} @entries;
806 my $entry = $bills2pay[0];
807 $entry->{bill}->amount(0);
808 push @{$entry->{payments}}, $payment;
809 # Remove the payment from the master list.
810 my @p = grep {$_->id() != $payment->id()} @$payments;
815 # Map remaining bills to payments in whatever order.
816 foreach my $entry (grep {$_->{bill}->amount() > 0} @entries) {
817 my $bill = $entry->{bill};
818 # We could run out of payments before bills.
819 if ($payments && @$payments) {
820 while ($bill->amount() > 0) {
821 my $payment = shift @$payments;
822 last unless $payment;
823 my $new_amount = $U->fpdiff($bill->amount(),$payment->amount());
824 if ($new_amount < 0) {
825 # Clone the payment so we can say how much applied
827 my $new_payment = $payment->clone();
828 $new_payment->amount($bill->amount());
830 push @{$entry->{payments}}, $new_payment;
831 # Reset the payment amount and put it back on the
832 # list for later use.
833 $payment->amount(-$new_amount);
834 unshift @$payments, $payment;
836 $bill->amount($new_amount);
837 push @{$entry->{payments}}, $payment;
847 # This subroutine actually handles voiding of bills. It takes a
848 # CStoreEditor, an arrayref of bill ids or bills, and an optional note.
850 my ($class, $e, $billids, $note) = @_;
851 return $e->die_event unless $e->checkauth;
852 return $e->die_event unless $e->allowed('VOID_BILLING');
856 if (ref($billids->[0])) {
859 $bills = $e->search_money_billing([{id => $billids}])
860 or return $e->die_event;
862 for my $bill (@$bills) {
864 my $xact = $e->retrieve_money_billable_transaction($bill->xact)
865 or return $e->die_event;
867 if($U->is_true($bill->voided)) {
868 # For now, it is not an error to attempt to re-void a bill, but
869 # don't actually do anything
871 #return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill)
875 my $org = $U->xact_org($bill->xact, $e);
876 $users{$xact->usr} = {} unless $users{$xact->usr};
877 $users{$xact->usr}->{$org} = 1;
880 $bill->voider($e->requestor->id);
881 $bill->void_time('now');
882 my $n = ($bill->note) ? sprintf("%s\n", $bill->note) : "";
883 $bill->note(sprintf("$n%s", ($note) ? $note : "System: VOIDED FOR BACKDATE"));
885 $e->update_money_billing($bill) or return $e->die_event;
886 my $evt = $U->check_open_xact($e, $bill->xact, $xact);
890 # calculate penalties for all user/org combinations
891 for my $user_id (keys %users) {
892 for my $org_id (keys %{$users{$user_id}}) {
893 OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id)
901 # This subroutine actually handles "adjusting" bills to zero. It takes a
902 # CStoreEditor, an arrayref of bill ids or bills, and an optional note.
903 sub adjust_bills_to_zero {
904 my ($class, $e, $billids, $note) = @_;
906 # Get with the editor to see if we have permission to void bills.
907 return $e->die_event unless $e->checkauth;
908 return $e->die_event unless $e->allowed('VOID_BILLING');
912 # Let's get all the billing objects and handle them by
915 if (ref($billids->[0])) {
918 $bills = $e->search_money_billing([{id => $billids}])
919 or return $e->die_event;
922 my @xactids = uniq map {$_->xact()} @$bills;
924 foreach my $xactid (@xactids) {
925 my $mbt = $e->retrieve_money_billable_transaction(
931 mbt=>['grocery','circulation'],
932 circ=>['target_copy']
936 ) or return $e->die_event;
937 # Flesh grocery bills and circulations so we don't have to
938 # retrieve them later.
939 my ($circ, $grocery, $copy);
940 $grocery = $mbt->grocery();
941 $circ = $mbt->circulation();
942 $copy = $circ->target_copy() if ($circ);
946 # Get the bill_payment_map for the transaction.
947 my $bpmap = $class->bill_payment_map_for_xact($e, $mbt);
949 # Get the bills for this transaction from the main list of bills.
950 my @xact_bills = grep {$_->xact() == $xactid} @$bills;
951 # Handle each bill in turn.
952 foreach my $bill (@xact_bills) {
953 # As the total open amount on the transaction will change
954 # as each bill is voided, we'll just recalculate it for
957 map {$xact_total += $_->{bill}->amount()} @$bpmap;
958 last if $xact_total == 0;
960 # Get the bill_payment_map entry for this bill:
961 my ($bpentry) = grep {$_->{bill}->id() == $bill->id()} @$bpmap;
963 # From here on out, use the bill object from the bill
965 $bill = $bpentry->{bill};
967 # The amount to void is the non-voided balance on the
968 # bill. It should never be less than zero.
969 my $amount_to_void = $U->fpdiff($bpentry->{bill_amount},$bpentry->{void_amount});
971 # Check if this bill is already voided. We don't allow
972 # "double" voids regardless of settings.
973 if ($amount_to_void <= 0) {
974 #my $event = OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill);
980 if ($amount_to_void > $xact_total) {
981 $amount_to_void = $xact_total;
984 # Create the adjustment payment
985 my $payobj = Fieldmapper::money::adjustment_payment->new;
986 $payobj->amount($amount_to_void);
987 $payobj->amount_collected($amount_to_void);
988 $payobj->xact($xactid);
989 $payobj->accepting_usr($e->requestor->id);
990 $payobj->payment_ts('now');
991 $payobj->billing($bill->id());
992 $payobj->note($note) if ($note);
993 $e->create_money_adjustment_payment($payobj) or return $e->die_event;
994 # Adjust our bill_payment_map
995 $bpentry->{void_amount} += $amount_to_void;
996 push @{$bpentry->{voids}}, $payobj;
997 # Should come to zero:
998 my $new_bill_amount = $U->fpdiff($bill->amount(),$amount_to_void);
999 $bill->amount($new_bill_amount);
1002 my $org = $U->xact_org($xactid, $e);
1003 $users{$mbt->usr} = {} unless $users{$mbt->usr};
1004 $users{$mbt->usr}->{$org} = 1;
1006 my $evt = $U->check_open_xact($e, $xactid, $mbt);
1007 return $evt if $evt;
1010 # calculate penalties for all user/org combinations
1011 for my $user_id (keys %users) {
1012 for my $org_id (keys %{$users{$user_id}}) {
1013 OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
1020 # A helper function to check if the payments on a bill are inside the
1021 # range of a given interval.
1022 # TODO: here is one simple place we could do voids in the absence
1024 sub _has_refundable_payments {
1025 my ($e, $xactid, $interval) = @_;
1027 # for now, just short-circuit with no interval
1028 return 0 if (!$interval);
1030 my $last_payment = $e->search_money_payment(
1033 payment_type => {"!=" => 'adjustment_payment'}
1036 order_by => { mp => "payment_ts DESC" }
1040 if ($last_payment->[0]) {
1041 my $interval_secs = interval_to_seconds($interval);
1042 my $payment_ts = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($last_payment->[0]->payment_ts))->epoch;
1044 return 1 if ($payment_ts + $interval_secs >= $now);