]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Circ/CircCommon.pm
LP#1705524: Honor timezone of the acting library where appropriate
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Circ / CircCommon.pm
1 package OpenILS::Application::Circ::CircCommon;
2 use strict; use warnings;
3 use DateTime;
4 use DateTime::Format::ISO8601;
5 use OpenILS::Application::AppUtils;
6 use OpenSRF::Utils qw/:datetime/;
7 use OpenILS::Event;
8 use OpenSRF::Utils::Logger qw(:logger);
9 use OpenILS::Utils::CStoreEditor q/:funcs/;
10 use OpenILS::Const qw/:const/;
11 use POSIX qw(ceil);
12 use List::MoreUtils qw(uniq);
13
14 my $U = "OpenILS::Application::AppUtils";
15 my $parser = DateTime::Format::ISO8601->new;
16
17 # -----------------------------------------------------------------
18 # Do not publish methods here.  This code is shared across apps.
19 # -----------------------------------------------------------------
20
21
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
26 # overdue fines.
27 # -----------------------------------------------------------------
28 sub void_overdues {
29 #compatibility layer - TODO
30 }
31 sub void_or_zero_overdues {
32     my($class, $e, $circ, $opts) = @_;
33
34     my $bill_search = { 
35         xact => $circ->id, 
36         btype => 1 
37     };
38
39     if( $opts->{backdate} ) {
40         my $backdate = $opts->{backdate};
41         $opts->{note} = 'System: OVERDUE REVERSED FOR BACKDATE' if !$opts->{note};
42         # ------------------------------------------------------------------
43         # Fines for overdue materials are assessed up to, but not including,
44         # one fine interval after the fines are applicable.  Here, we add
45         # one fine interval to the backdate to ensure that we are not 
46         # voiding fines that were applicable before the backdate.
47         # ------------------------------------------------------------------
48
49         # if there is a raw time component (e.g. from postgres), 
50         # turn it into an interval that interval_to_seconds can parse
51         my $duration = $circ->fine_interval;
52         $duration =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
53         my $interval = OpenSRF::Utils->interval_to_seconds($duration);
54
55         my $date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($backdate));
56         my $due_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->due_date))->epoch;
57         my $grace_period = extend_grace_period( $class, $circ->circ_lib, $circ->due_date, OpenSRF::Utils->interval_to_seconds($circ->grace_period), $e);
58         if($date->epoch <= $due_date + $grace_period) {
59             $logger->info("backdate $backdate is within grace period, voiding all");
60         } else {
61             $backdate = $U->epoch2ISO8601($date->epoch + $interval);
62             $logger->info("applying backdate $backdate in overdue voiding");
63             $$bill_search{billing_ts} = {'>=' => $backdate};
64         }
65     }
66
67     my $billids = $e->search_money_billing([$bill_search, {idlist=>1}]);
68     if ($billids && @$billids) {
69         # overdue settings come from transaction org unit
70         my $prohibit_neg_balance_overdues = (
71             $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.prohibit_negative_balance_on_overdues')
72             ||
73             $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.prohibit_negative_balance_default')
74         );
75         my $neg_balance_interval_overdues = (
76             $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.negative_balance_interval_on_overdues')
77             ||
78             $U->ou_ancestor_setting_value($circ->circ_lib(), 'bill.negative_balance_interval_default')
79         );
80         my $result;
81         # if we prohibit negative overdue balances and all payments
82         # are outside the refund interval (if given), zero the transaction
83         if ($opts->{force_zero}
84             or (!$opts->{force_void}
85                 and (
86                     $U->is_true($prohibit_neg_balance_overdues)
87                     and !_has_refundable_payments($e, $circ->id, $neg_balance_interval_overdues)
88                 )
89             )
90         ) {
91             $result = $class->adjust_bills_to_zero($e, $billids, $opts->{note}, $neg_balance_interval_overdues);
92         } else {
93             # otherwise, just void the usual way
94             $result = $class->void_bills($e, $billids, $opts->{note});
95         }
96         if (ref($result)) {
97             return $result;
98         }
99     }
100
101     return undef;
102 }
103
104 # ------------------------------------------------------------------
105 # remove charge from patron's account if lost item is returned
106 # ------------------------------------------------------------------
107 sub void_lost {
108     my ($class, $e, $circ, $btype) = @_;
109
110     my $bills = $e->search_money_billing(
111         {
112             xact => $circ->id,
113             btype => $btype,
114             voided => 'f'
115         }
116     );
117
118     $logger->debug("voiding lost item charge of  ".scalar(@$bills));
119     for my $bill (@$bills) {
120         if( !$U->is_true($bill->voided) ) {
121             $logger->info("lost item returned - voiding bill ".$bill->id);
122             $bill->voided('t');
123             $bill->void_time('now');
124             $bill->voider($e->requestor->id);
125             my $note = ($bill->note) ? $bill->note . "\n" : '';
126             $bill->note("${note}System: VOIDED FOR LOST ITEM RETURNED");
127
128             return $e->event
129                 unless $e->update_money_billing($bill);
130         }
131     }
132     return undef;
133 }
134
135 # ------------------------------------------------------------------
136 # Void (or zero) all bills of a given type on a circulation.
137 #
138 # Takes an editor, a circ object, the btype number for the bills you
139 # want to void, and an optional note.
140 #
141 # Returns undef on success or the result from void_bills.
142 # ------------------------------------------------------------------
143 sub void_or_zero_bills_of_type {
144     my ($class, $e, $circ, $copy, $btype, $for_note) = @_;
145
146     my $billids = $e->search_money_billing(
147         {xact => $circ->id(), btype => $btype},
148         {idlist=>1}
149     );
150     if ($billids && @$billids) {
151         # settings for lost come from copy circlib.
152         my $prohibit_neg_balance_lost = (
153             $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.prohibit_negative_balance_on_lost')
154             ||
155             $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.prohibit_negative_balance_default')
156         );
157         my $neg_balance_interval_lost = (
158             $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.negative_balance_interval_on_lost')
159             ||
160             $U->ou_ancestor_setting_value($copy->circ_lib(), 'bill.negative_balance_interval_default')
161         );
162         my $result;
163         if (
164             $U->is_true($prohibit_neg_balance_lost)
165             and !_has_refundable_payments($e, $circ->id, $neg_balance_interval_lost)
166         ) {
167             $result = $class->adjust_bills_to_zero($e, $billids, "System: ADJUSTED $for_note");
168         } else {
169             $result = $class->void_bills($e, $billids, "System: VOIDED $for_note");
170         }
171         if (ref($result)) {
172             return $result;
173         }
174     }
175
176     return undef;
177 }
178
179 sub reopen_xact {
180     my($class, $e, $xactid) = @_;
181
182     # -----------------------------------------------------------------
183     # make sure the transaction is not closed
184     my $xact = $e->retrieve_money_billable_transaction($xactid)
185         or return $e->die_event;
186
187     if( $xact->xact_finish ) {
188         my ($mbts) = $U->fetch_mbts($xactid, $e);
189         if( $mbts->balance_owed != 0 ) {
190             $logger->info("* re-opening xact $xactid, orig xact_finish is ".$xact->xact_finish);
191             $xact->clear_xact_finish;
192             $e->update_money_billable_transaction($xact)
193                 or return $e->die_event;
194         } 
195     }
196
197     return undef;
198 }
199
200
201 sub create_bill {
202     my($class, $e, $amount, $btype, $type, $xactid, $note, $billing_ts) = @_;
203
204     $logger->info("The system is charging $amount [$type] on xact $xactid");
205     $note ||= 'SYSTEM GENERATED';
206
207     # -----------------------------------------------------------------
208     # now create the billing
209     my $bill = Fieldmapper::money::billing->new;
210     $bill->xact($xactid);
211     $bill->amount($amount);
212     $bill->billing_ts($billing_ts);
213     $bill->billing_type($type); 
214     $bill->btype($btype); 
215     $bill->note($note);
216     $e->create_money_billing($bill) or return $e->die_event;
217
218     return undef;
219 }
220
221 sub extend_grace_period {
222     my($class, $circ_lib, $due_date, $grace_period, $e, $h) = @_;
223     if ($grace_period >= 86400) { # Only extend grace periods greater than or equal to a full day
224         my $parser = DateTime::Format::ISO8601->new;
225         my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
226         my $due = $due_dt->epoch;
227
228         my $grace_extend = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend');
229         $e = new_editor() if (!$e);
230         $h = $e->retrieve_actor_org_unit_hours_of_operation($circ_lib) if (!$h);
231         if ($grace_extend and $h) { 
232             my $new_grace_period = $grace_period;
233
234             $logger->info( "Circ lib has an hours-of-operation entry and grace period extension is enabled." );
235
236             my $closed = 0;
237             my %h_closed;
238             for my $i (0 .. 6) {
239                 my $dow_open = "dow_${i}_open";
240                 my $dow_close = "dow_${i}_close";
241                 if($h->$dow_open() eq '00:00:00' and $h->$dow_close() eq '00:00:00') {
242                     $closed++;
243                     $h_closed{$i} = 1;
244                 } else {
245                     $h_closed{$i} = 0;
246                 }
247             }
248
249             if($closed == 7) {
250                 $logger->info("Circ lib is closed all week according to hours-of-operation entry. Skipping grace period extension checks.");
251             } else {
252                 # Extra nice grace periods
253                 # AKA, merge closed dates trailing the grace period into the grace period
254                 my $grace_extend_into_closed = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend.into_closed');
255                 $due += 86400 if $grace_extend_into_closed;
256
257                 my $grace_extend_all = $U->ou_ancestor_setting_value($circ_lib, 'circ.grace.extend.all');
258
259                 if ( $grace_extend_all ) {
260                     # Start checking the day after the item was due
261                     # This is "The grace period only counts open days"
262                     # NOTE: Adding 86400 seconds is not the same as adding one day. This uses seconds intentionally.
263                     $due_dt = $due_dt->add( seconds => 86400 );
264                 } else {
265                     # Jump to the end of the grace period
266                     # This is "If the grace period ends on a closed day extend it"
267                     # NOTE: This adds grace period as a number of seconds intentionally
268                     $due_dt = $due_dt->add( seconds => $grace_period );
269                 }
270
271                 my $count = 0; # Infinite loop protection
272                 do {
273                     $closed = 0; # Starting assumption for day: We are not closed
274                     $count++; # We limit the number of loops below.
275
276                     # get the day of the week for the day we are looking at
277                     my $dow = $due_dt->day_of_week_0;
278
279                     # Check hours of operation first.
280                     if ($h_closed{$dow}) {
281                         $closed = 1;
282                         $new_grace_period += 86400;
283                         $due_dt->add( seconds => 86400 );
284                     } else {
285                         # Check for closed dates for this period
286                         my $timestamptz = $due_dt->strftime('%FT%T%z');
287                         my $cl = $e->search_actor_org_unit_closed_date(
288                                 { close_start => { '<=' => $timestamptz },
289                                   close_end   => { '>=' => $timestamptz },
290                                   org_unit    => $circ_lib }
291                         );
292                         if ($cl and @$cl) {
293                             $closed = 1;
294                             foreach (@$cl) {
295                                 my $cl_dt = $parser->parse_datetime( cleanse_ISO8601( $_->close_end ) );
296                                 while ($due_dt <= $cl_dt) {
297                                     $due_dt->add( seconds => 86400 );
298                                     $new_grace_period += 86400;
299                                 }
300                             }
301                         } else {
302                             $due_dt->add( seconds => 86400 );
303                         }
304                     }
305                 } while ( $count <= 366 and ( $closed or $due_dt->epoch <= $due + $new_grace_period ) );
306                 if ($new_grace_period > $grace_period) {
307                     $grace_period = $new_grace_period;
308                     $logger->info( "Grace period for circ extended to $grace_period [" . seconds_to_interval( $grace_period ) . "]" );
309                 }
310             }
311         }
312     }
313     return $grace_period;
314 }
315
316 # check if a circulation transaction can be closed
317 # takes a CStoreEditor and a circ transaction.
318 # Returns 1 if the circ should be closed, 0 if not.
319 sub can_close_circ {
320     my ($class, $e, $circ) = @_;
321     my $can_close = 0;
322
323     my $reason = $circ->stop_fines;
324
325     # We definitely want to close if this circulation was
326     # checked in or renewed.
327     if ($circ->checkin_time) {
328         $can_close = 1;
329     } elsif ($reason eq OILS_STOP_FINES_LOST) {
330         # Check the copy circ_lib to see if they close
331         # transactions when lost are paid.
332         my $copy = $e->retrieve_asset_copy($circ->target_copy);
333         if ($copy) {
334             $can_close = !$U->is_true(
335                 $U->ou_ancestor_setting_value(
336                     $copy->circ_lib,
337                     'circ.lost.xact_open_on_zero',
338                     $e
339                 )
340             );
341         }
342
343     } elsif ($reason eq OILS_STOP_FINES_LONGOVERDUE) {
344         # Check the copy circ_lib to see if they close
345         # transactions when long-overdue are paid.
346         my $copy = $e->retrieve_asset_copy($circ->target_copy);
347         if ($copy) {
348             $can_close = !$U->is_true(
349                 $U->ou_ancestor_setting_value(
350                     $copy->circ_lib,
351                     'circ.longoverdue.xact_open_on_zero',
352                     $e
353                 )
354             );
355         }
356     }
357
358     return $can_close;
359 }
360
361 sub seconds_to_interval_hash {
362         my $interval = shift;
363         my $limit = shift || 's';
364         $limit =~ s/^(.)/$1/o;
365
366         my %output;
367
368         my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
369         my ($year, $month, $week, $day, $hour, $minute, $second) =
370                 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
371
372         if ($y = int($interval / (60 * 60 * 24 * 365))) {
373                 $output{$year} = $y;
374                 $ym = $interval % (60 * 60 * 24 * 365);
375         } else {
376                 $ym = $interval;
377         }
378         return %output if ($limit eq 'y');
379
380         if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
381                 $output{$month} = $M;
382                 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
383         } else {
384                 $Mm = $ym;
385         }
386         return %output if ($limit eq 'M');
387
388         if ($w = int($Mm / 604800)) {
389                 $output{$week} = $w;
390                 $wm = $Mm % 604800;
391         } else {
392                 $wm = $Mm;
393         }
394         return %output if ($limit eq 'w');
395
396         if ($d = int($wm / 86400)) {
397                 $output{$day} = $d;
398                 $dm = $wm % 86400;
399         } else {
400                 $dm = $wm;
401         }
402         return %output if ($limit eq 'd');
403
404         if ($h = int($dm / 3600)) {
405                 $output{$hour} = $h;
406                 $hm = $dm % 3600;
407         } else {
408                 $hm = $dm;
409         }
410         return %output if ($limit eq 'h');
411
412         if ($m = int($hm / 60)) {
413                 $output{$minute} = $m;
414                 $mm = $hm % 60;
415         } else {
416                 $mm = $hm;
417         }
418         return %output if ($limit eq 'm');
419
420         if ($s = int($mm)) {
421                 $output{$second} = $s;
422         } else {
423                 $output{$second} = 0 unless (keys %output);
424         }
425         return %output;
426 }
427
428 sub generate_fines {
429     my ($class, $args) = @_;
430     my $circs = $args->{circs};
431     return unless $circs and @$circs;
432     my $e = $args->{editor};
433     # if a client connection is passed in, this will be chatty like
434     # the old storage version
435     my $conn = $args->{conn};
436
437     my $commit = 0;
438     unless ($e) {
439         # Transactions are opened/closed with each circ, reservation, etc.
440         # The first $e->xact_begin (below) will cause a connect.
441         $e = new_editor();
442         $commit = 1;
443     }
444
445     my %hoo = map { ( $_->id => $_ ) } @{ $e->retrieve_all_actor_org_unit_hours_of_operation };
446
447     my $handling_resvs = 0;
448     for my $c (@$circs) {
449
450         my $ctype = ref($c);
451
452         if (!$ctype) { # we received only an idlist, not objects
453             if ($handling_resvs) {
454                 $c = $e->retrieve_booking_reservation($c);
455             } elsif (not defined $c) {
456                 # an undef value is the indicator that we are moving
457                 # from processing circulations to reservations.
458                 $handling_resvs = 1;
459                 next;
460             } else {
461                 $c = $e->retrieve_action_circulation($c);
462             }
463             $ctype = ref($c);
464         }
465
466         $ctype =~ s/^.+::(\w+)$/$1/;
467     
468         my $due_date_method = 'due_date';
469         my $target_copy_method = 'target_copy';
470         my $circ_lib_method = 'circ_lib';
471         my $recurring_fine_method = 'recurring_fine';
472         my $is_reservation = 0;
473         if ($ctype eq 'reservation') {
474             $is_reservation = 1;
475             $due_date_method = 'end_time';
476             $target_copy_method = 'current_resource';
477             $circ_lib_method = 'pickup_lib';
478             $recurring_fine_method = 'fine_amount';
479             next unless ($c->fine_interval);
480         }
481         #TODO: reservation grace periods
482         my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
483
484         eval {
485
486             # Clean up after previous transaction.  
487             # This is a no-op if there is no open transaction.
488             $e->xact_rollback if $commit;
489
490             $logger->info(sprintf("Processing $ctype %d...", $c->id));
491
492             # each (ils) transaction is processed in its own (db) transaction
493             $e->xact_begin if $commit;
494
495             my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
496     
497             my $due = $due_dt->epoch;
498             my $now = time;
499
500             my $fine_interval = $c->fine_interval;
501             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
502             $fine_interval = interval_to_seconds( $fine_interval );
503     
504             if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
505                 $conn->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" ) if $conn;
506                 $logger->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
507                 return;
508             }
509
510             if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {    
511                 my $tz_offset_s = 0;
512                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
513                     $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
514                 }
515     
516                 $due -= ($due % $fine_interval) + $tz_offset_s;
517                 $now -= ($now % $fine_interval) + $tz_offset_s;
518             }
519     
520             $conn->respond(
521                 "ARG! Overdue $ctype ".$c->id.
522                 " for item ".$c->$target_copy_method.
523                 " (user ".$c->usr.").\n".
524                 "\tItem was due on or before: ".localtime($due)."\n") if $conn;
525     
526             my @fines = @{$e->search_money_billing([
527                 { xact => $c->id,
528                   btype => 1,
529                   billing_ts => { '>' => $c->$due_date_method } },
530                 { order_by => {mb => 'billing_ts DESC'},
531                   flesh => 1,
532                   flesh_fields => {mb => ['adjustments']} }
533             ])};
534
535             my $f_idx = 0;
536             my $fine = $fines[$f_idx] if (@fines);
537             my $current_fine_total = 0;
538             $current_fine_total += int($_->amount * 100) for (grep { $_ and !$U->is_true($_->voided) } @fines);
539             $current_fine_total -= int($_->amount * 100) for (map { @{$_->adjustments} } @fines);
540     
541             my $last_fine;
542             if ($fine) {
543                 $conn->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")") if $conn;
544                 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
545             } else {
546                 $logger->info( "Potential first billing for circ ".$c->id );
547                 $last_fine = $due;
548
549                 $grace_period = extend_grace_period($class, $c->$circ_lib_method,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
550             }
551
552             return if ($last_fine > $now);
553             # Generate fines for each past interval, including the one we are inside
554             my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
555
556             if ( $last_fine == $due                         # we have no fines yet
557                  && $grace_period                           # and we have a grace period
558                  && $now < $due + $grace_period             # and some date math says were are within the grace period
559             ) {
560                 $conn->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" ) if $conn;
561                 $logger->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
562                 return;
563             }
564
565             $conn->respond( "\t$pending_fine_count pending fine(s)\n" ) if $conn;
566             return unless ($pending_fine_count);
567
568             my $recurring_fine = int($c->$recurring_fine_method * 100);
569             my $max_fine = int($c->max_fine * 100);
570
571             my $skip_closed_check = $U->ou_ancestor_setting_value(
572                 $c->$circ_lib_method, 'circ.fines.charge_when_closed');
573             $skip_closed_check = $U->is_true($skip_closed_check);
574
575             my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
576                 $c->$circ_lib_method, 'circ.fines.truncate_to_max_fine');
577             $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
578
579             my $tz = $U->ou_ancestor_setting_value(
580                 $c->$circ_lib_method, 'lib.timezone') || 'local';
581
582             my ($latest_billing_ts, $latest_amount) = ('',0);
583             for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
584     
585                 if ($current_fine_total >= $max_fine) {
586                     if ($ctype eq 'circulation') {
587                         $c->stop_fines('MAXFINES');
588                         $c->stop_fines_time('now');
589                         $e->update_action_circulation($c);
590                     }
591                     $conn->respond(
592                         "\tMaximum fine level of ".$c->max_fine.
593                         " reached for this $ctype.\n".
594                         "\tNo more fines will be generated.\n" ) if $conn;
595                     last;
596                 }
597                 
598                 # Use org time zone (or default to 'local')
599                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => $tz );
600                 my $current_bill_count = $bill;
601                 while ( $current_bill_count ) {
602                     $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
603                     $current_bill_count--;
604                 }
605
606                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
607                 if (!$skip_closed_check) {
608                     my $dow = $billing_ts->day_of_week_0();
609                     my $dow_open = "dow_${dow}_open";
610                     my $dow_close = "dow_${dow}_close";
611
612                     if (my $h = $hoo{$c->$circ_lib_method}) {
613                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
614                     }
615     
616                     my @cl = @{$e->search_actor_org_unit_closed_date(
617                             { close_start   => { '<=' => $timestamptz },
618                               close_end => { '>=' => $timestamptz },
619                               org_unit  => $c->$circ_lib_method }
620                     )};
621                     next if (@cl);
622                 }
623
624                 # The billing amount for this billing normally ought to be the recurring fine amount.
625                 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
626                 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
627                 my $this_billing_amount = $recurring_fine;
628                 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
629                     $this_billing_amount = ($max_fine - $current_fine_total);
630                 }
631                 $current_fine_total += $this_billing_amount;
632                 $latest_amount += $this_billing_amount;
633                 $latest_billing_ts = $timestamptz;
634
635                 my $bill = Fieldmapper::money::billing->new;
636                 $bill->xact($c->id);
637                 $bill->note("System Generated Overdue Fine");
638                 $bill->billing_type("Overdue materials");
639                 $bill->btype(1);
640                 $bill->amount(sprintf('%0.2f', $this_billing_amount/100));
641                 $bill->billing_ts($timestamptz);
642                 $e->create_money_billing($bill);
643
644             }
645
646             $conn->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
647                 if ($conn and $latest_billing_ts and $latest_amount);
648
649
650             # Calculate penalties inline
651             OpenILS::Utils::Penalty->calculate_penalties(
652                 $e, $c->usr, $c->$circ_lib_method);
653
654             $e->xact_commit if $commit;
655
656         };
657
658         if ($@) {
659             my $e = $@;
660             $conn->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" ) if $conn;
661             $logger->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
662             last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
663         }
664     }
665
666     # roll back any (potentially) orphaned transaction and disconnect.
667     $e->rollback if $commit;
668
669     return undef;
670 }
671
672 # -----------------------------------------------------------------
673 # Given an editor and a xact, return a reference to an array of
674 # hashrefs that map billing objects to payment objects.  Returns undef
675 # if no bills are found for the given transaction.
676 #
677 # The bill amounts are adjusted to reflect the application of the
678 # payments to the bills.  The original bill amounts are retained in
679 # the mapping.
680 #
681 # The payment objects may or may not have their amounts adjusted
682 # depending on whether or not they apply to more than one bill.  We
683 # could really use a better logic here, perhaps, but if it was
684 # consistent, it wouldn't be Evergreen.
685 #
686 # The data structure used in the array is a hashref that has the
687 # following fields:
688 #
689 # bill => the adjusted bill object
690 # adjustments => an arrayref of account adjustments that apply directly
691 #                to the bill
692 # payments => an arrayref of payment objects applied to the bill
693 # bill_amount => original amount from the billing object
694 # adjustment_amount => total of the account adjustments that apply
695 #                      directly to the bill
696 #
697 # Each bill is only mapped to payments one time.  However, a single
698 # payment may be mapped to more than one bill if the payment amount is
699 # greater than the amount of each individual bill, such as a $3.00
700 # payment for 30 $0.10 overdue bills.  There is an attempt made to
701 # first pay bills with payments that match the billing amount.  This
702 # is intended to catch payments for lost and/or long overdue bills so
703 # that they will match up.
704 #
705 # This function is heavily adapted from code written by Jeff Godin of
706 # Traverse Area District Library and submitted on LaunchPad bug
707 # #1009049.
708 # -----------------------------------------------------------------
709 sub bill_payment_map_for_xact {
710     my ($class, $e, $xact) = @_;
711
712     # Check for CStoreEditor and make a new one if we have to. This
713     # allows one-off calls to this subroutine to pass undef as the
714     # CStoreEditor and not have to create one of their own.
715     $e = OpenILS::Utils::CStoreEditor->new unless ($e);
716
717     # find all bills in order
718     my $bill_search = [
719         { xact => $xact->id(), voided => 'f' },
720         { order_by => { mb => { billing_ts => { direction => 'asc' } } } },
721     ];
722
723     # At some point, we should get rid of the voided column on
724     # money.payment and family.  It is not exposed in the client at
725     # the moment, and should be replaced with a void_bill type.  The
726     # descendants of money.payment don't expose the voided field in
727     # the fieldmapper, only the mp object, based on the money.payment
728     # view, does.  However, I want to leave that complication for
729     # later.  I wonder if I'm not slowing things down too much with
730     # the current account_adjustment logic.  It would probably be faster if
731     # we had direct Pg access at this layer.  I can probably wrangle
732     # something via the drivers or store interfaces, but I haven't
733     # really figured those out, yet.
734
735     my $bills = $e->search_money_billing($bill_search);
736
737     # return undef if there are no bills.
738     return undef unless ($bills && @$bills);
739
740     # map the bills into our bill_payment_map entry format:
741     my @entries = map {
742         {
743             bill => $_,
744             bill_amount => $_->amount(),
745             payments => [],
746             adjustments => [],
747             adjustment_amount => 0
748         }
749     } @$bills;
750
751     # Find all unvoided payments in order.  Flesh account adjustments
752     # so that we don't have to retrieve them later.
753     my $payments = $e->search_money_payment(
754         [
755             { xact => $xact->id, voided=>'f' },
756             {
757                 order_by => { mp => { payment_ts => { direction => 'asc' } } },
758                 flesh => 1,
759                 flesh_fields => { mp => ['account_adjustment'] }
760             }
761         ]
762     );
763
764     # If there were no payments, then we just return the bills.
765     return \@entries unless ($payments && @$payments);
766
767     # Now, we go through the rigmarole of mapping payments to bills
768     # and adjusting the bill balances.
769
770     # Apply the adjustments before "paying" other bills.
771     foreach my $entry (@entries) {
772         my $bill = $entry->{bill};
773         # Find only the adjustments that apply to individual bills.
774         my @adjustments = map {$_->account_adjustment()} grep {$_->payment_type() eq 'account_adjustment' && $_->account_adjustment()->billing() == $bill->id()} @$payments;
775         if (@adjustments) {
776             foreach my $adjustment (@adjustments) {
777                 my $new_amount = $U->fpdiff($bill->amount(),$adjustment->amount());
778                 if ($new_amount >= 0) {
779                     push @{$entry->{adjustments}}, $adjustment;
780                     $entry->{adjustment_amount} += $adjustment->amount();
781                     $bill->amount($new_amount);
782                     # Remove the used up adjustment from list of payments:
783                     my @p = grep {$_->id() != $adjustment->id()} @$payments;
784                     $payments = \@p;
785                 } else {
786                     # It should never happen that we have more adjustment
787                     # payments on a single bill than the amount of the
788                     # bill.  However, experience shows that the things
789                     # that should never happen actually do happen with
790                     # surprising regularity in a library setting.
791
792                     # Clone the adjustment to say how much of it actually
793                     # applied to this bill.
794                     my $new_adjustment = $adjustment->clone();
795                     $new_adjustment->amount($bill->amount());
796                     $new_adjustment->amount_collected($bill->amount());
797                     push (@{$entry->{adjustments}}, $new_adjustment);
798                     $entry->{adjustment_amount} += $new_adjustment->amount();
799                     $bill->amount(0);
800                     $adjustment->amount(-$new_amount);
801                     # Could be a candidate for YAOUS about what to do
802                     # with excess adjustment amounts on a bill.
803                 }
804                 last if ($bill->amount() == 0);
805             }
806         }
807     }
808
809     # Try to map payments to bills by amounts starting with the
810     # largest payments.
811     # To avoid modifying the array we're iterating over (which can result in a
812     # "Use of freed value in iteration" error), we create a copy of the
813     # payments array and remove handled payments from that instead.
814     my @handled_payments = @$payments;
815     foreach my $payment (sort {$b->amount() <=> $a->amount()} @$payments) {
816         my @bills2pay = grep {$_->{bill}->amount() == $payment->amount()} @entries;
817         if (@bills2pay) {
818             my $entry = $bills2pay[0];
819             $entry->{bill}->amount(0);
820             push @{$entry->{payments}}, $payment;
821             # Remove the payment from the master list.
822             my @p = grep {$_->id() != $payment->id()} @handled_payments;
823             @handled_payments = @p;
824         }
825     }
826     # Now, update our list of payments so that it only includes unhandled
827     # (unmapped) payments.
828     $payments = \@handled_payments;
829
830     # Map remaining bills to payments in whatever order.
831     foreach  my $entry (grep {$_->{bill}->amount() > 0} @entries) {
832         my $bill = $entry->{bill};
833         # We could run out of payments before bills.
834         if ($payments && @$payments) {
835             while ($bill->amount() > 0) {
836                 my $payment = shift @$payments;
837                 last unless $payment;
838                 my $new_amount = $U->fpdiff($bill->amount(),$payment->amount());
839                 if ($new_amount < 0) {
840                     # Clone the payment so we can say how much applied
841                     # to this bill.
842                     my $new_payment = $payment->clone();
843                     $new_payment->amount($bill->amount());
844                     $bill->amount(0);
845                     push @{$entry->{payments}}, $new_payment;
846                     # Reset the payment amount and put it back on the
847                     # list for later use.
848                     $payment->amount(-$new_amount);
849                     unshift @$payments, $payment;
850                 } else {
851                     $bill->amount($new_amount);
852                     push @{$entry->{payments}}, $payment;
853                 }
854             }
855         }
856     }
857
858     return \@entries;
859 }
860
861
862 # This subroutine actually handles voiding of bills.  It takes a
863 # CStoreEditor, an arrayref of bill ids or bills, and an optional note.
864 sub void_bills {
865     my ($class, $e, $billids, $note) = @_;
866
867     my %users;
868     my $bills;
869     if (ref($billids->[0])) {
870         $bills = $billids;
871     } else {
872         $bills = $e->search_money_billing([{id => $billids}])
873             or return $e->die_event;
874     }
875     for my $bill (@$bills) {
876
877         my $xact = $e->retrieve_money_billable_transaction($bill->xact)
878             or return $e->die_event;
879
880         if($U->is_true($bill->voided)) {
881             # For now, it is not an error to attempt to re-void a bill, but
882             # don't actually do anything
883             #$e->rollback;
884             #return OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill)
885             next;
886         }
887
888         my $org = $U->xact_org($bill->xact, $e);
889         $users{$xact->usr} = {} unless $users{$xact->usr};
890         $users{$xact->usr}->{$org} = 1;
891
892         $bill->voided('t');
893         $bill->voider($e->requestor->id);
894         $bill->void_time('now');
895         my $n = ($bill->note) ? sprintf("%s\n", $bill->note) : "";
896         $bill->note(sprintf("$n%s", $note));
897
898         $e->update_money_billing($bill) or return $e->die_event;
899         my $evt = $U->check_open_xact($e, $bill->xact, $xact);
900         return $evt if $evt;
901     }
902
903     # calculate penalties for all user/org combinations
904     for my $user_id (keys %users) {
905         for my $org_id (keys %{$users{$user_id}}) {
906             OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id)
907         }
908     }
909
910     return 1;
911 }
912
913
914 # This subroutine actually handles "adjusting" bills to zero.  It takes a
915 # CStoreEditor, an arrayref of bill ids or bills, and an optional note.
916 sub adjust_bills_to_zero {
917     my ($class, $e, $billids, $note) = @_;
918
919     my %users;
920
921     # Let's get all the billing objects and handle them by
922     # transaction.
923     my $bills;
924     if (ref($billids->[0])) {
925         $bills = $billids;
926     } else {
927         $bills = $e->search_money_billing([{id => $billids}])
928             or return $e->die_event;
929     }
930
931     my @xactids = uniq map {$_->xact()} @$bills;
932
933     foreach my $xactid (@xactids) {
934         my $mbt = $e->retrieve_money_billable_transaction(
935             [
936                 $xactid,
937                 {
938                     flesh=> 2,
939                     flesh_fields=> {
940                         mbt=>['grocery','circulation'],
941                         circ=>['target_copy']
942                     }
943                 }
944             ]
945         ) or return $e->die_event;
946         # Flesh grocery bills and circulations so we don't have to
947         # retrieve them later.
948         my ($circ, $grocery, $copy);
949         $grocery = $mbt->grocery();
950         $circ = $mbt->circulation();
951         $copy = $circ->target_copy() if ($circ);
952
953
954
955         # Get the bill_payment_map for the transaction.
956         my $bpmap = $class->bill_payment_map_for_xact($e, $mbt);
957
958         # Get the bills for this transaction from the main list of bills.
959         my @xact_bills = grep {$_->xact() == $xactid} @$bills;
960         # Handle each bill in turn.
961         foreach my $bill (@xact_bills) {
962             # As the total open amount on the transaction will change
963             # as each bill is adjusted, we'll just recalculate it for
964             # each bill.
965             my $xact_total = 0;
966             map {$xact_total += $_->{bill}->amount()} @$bpmap;
967             last if $xact_total == 0;
968
969             # Get the bill_payment_map entry for this bill:
970             my ($bpentry) = grep {$_->{bill}->id() == $bill->id()} @$bpmap;
971
972             # From here on out, use the bill object from the bill
973             # payment map entry.
974             $bill = $bpentry->{bill};
975
976             # The amount to adjust is the non-adjusted balance on the
977             # bill. It should never be less than zero.
978             my $amount_to_adjust = $U->fpdiff($bpentry->{bill_amount},$bpentry->{adjustment_amount});
979
980             # Check if this bill is already adjusted.  We don't allow
981             # "double" adjustments regardless of settings.
982             if ($amount_to_adjust <= 0) {
983                 #my $event = OpenILS::Event->new('BILL_ALREADY_VOIDED', payload => $bill);
984                 #$e->event($event);
985                 #return $event;
986                 next;
987             }
988
989             if ($amount_to_adjust > $xact_total) {
990                 $amount_to_adjust = $xact_total;
991             }
992
993             # Create the account adjustment
994             my $payobj = Fieldmapper::money::account_adjustment->new;
995             $payobj->amount($amount_to_adjust);
996             $payobj->amount_collected($amount_to_adjust);
997             $payobj->xact($xactid);
998             $payobj->accepting_usr($e->requestor->id);
999             $payobj->payment_ts('now');
1000             $payobj->billing($bill->id());
1001             $payobj->note($note) if ($note);
1002             $e->create_money_account_adjustment($payobj) or return $e->die_event;
1003             # Adjust our bill_payment_map
1004             $bpentry->{adjustment_amount} += $amount_to_adjust;
1005             push @{$bpentry->{adjustments}}, $payobj;
1006             # Should come to zero:
1007             my $new_bill_amount = $U->fpdiff($bill->amount(),$amount_to_adjust);
1008             $bill->amount($new_bill_amount);
1009         }
1010
1011         my $org = $U->xact_org($xactid, $e);
1012         $users{$mbt->usr} = {} unless $users{$mbt->usr};
1013         $users{$mbt->usr}->{$org} = 1;
1014
1015         my $evt = $U->check_open_xact($e, $xactid, $mbt);
1016         return $evt if $evt;
1017     }
1018
1019     # calculate penalties for all user/org combinations
1020     for my $user_id (keys %users) {
1021         for my $org_id (keys %{$users{$user_id}}) {
1022             OpenILS::Utils::Penalty->calculate_penalties($e, $user_id, $org_id);
1023         }
1024     }
1025
1026     return 1;
1027 }
1028
1029 # A helper function to check if the payments on a bill are inside the
1030 # range of a given interval.
1031 # TODO: here is one simple place we could do voids in the absence
1032 # of any payments
1033 sub _has_refundable_payments {
1034     my ($e, $xactid, $interval) = @_;
1035
1036     # for now, just short-circuit with no interval
1037     return 0 if (!$interval);
1038
1039     my $last_payment = $e->search_money_payment(
1040         {
1041             xact => $xactid,
1042             payment_type => {"!=" => 'account_adjustment'}
1043         },{
1044             limit => 1,
1045             order_by => { mp => "payment_ts DESC" }
1046         }
1047     );
1048
1049     if ($last_payment->[0]) {
1050         my $interval_secs = interval_to_seconds($interval);
1051         my $payment_ts = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($last_payment->[0]->payment_ts))->epoch;
1052         my $now = time;
1053         return 1 if ($payment_ts + $interval_secs >= $now);
1054     }
1055
1056     return 0;
1057 }
1058
1059 1;