]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/action.pm
LP#1406367 Fine generator skips no-fines transactions (parallel)
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Publisher / action.pm
1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
3 use strict;
4 use warnings;
5 use OpenSRF::Utils::Logger qw/:level :logger/;
6 use OpenSRF::Utils qw/:datetime/;
7 use OpenSRF::Utils::JSON;
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::PermitHold;
12 use OpenILS::Utils::CStoreEditor qw/:funcs/;
13 use DateTime;
14 use DateTime::Format::ISO8601;
15 use OpenILS::Utils::Penalty;
16 use POSIX qw(ceil);
17 use OpenILS::Application::Circ::CircCommon;
18 use OpenILS::Application::AppUtils;
19 my $U = "OpenILS::Application::AppUtils";
20
21 # Used in build_hold_sort_clause().  See the hash %order_by_sprintf_args in
22 # that sub to confirm what gets used to replace the formatters, and see
23 # nearest_hold() for the main body of the SQL query that these go into.
24 my %HOLD_SORT_ORDER_BY = (
25     pprox => 'p.prox',
26     hprox => 'actor.org_unit_proximity(%d, h.pickup_lib)',  # $cp->call_number->owning_lib
27     aprox => 'COALESCE(hm.proximity, p.prox)',
28     approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
29     priority => 'pgt.hold_priority',
30     cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
31     depth => 'h.selection_depth',
32     rtime => 'h.request_time',
33     htime => q!
34         CASE WHEN
35             last_event_on_copy.place <> %d AND
36             copy_has_not_been_home.result
37         THEN actor.org_unit_proximity(%d, h.pickup_lib)
38         ELSE 999
39         END
40     !,  # $cp->call_number->owning_lib x 2
41     shtime => q!
42         CASE WHEN
43             last_event_on_copy.place <> %d AND
44             copy_has_not_been_home_even_to_idle.result
45         THEN actor.org_unit_proximity(%d, h.pickup_lib)
46         ELSE 999
47         END
48     !,  # $cp->call_number->owning_lib x 2
49 );
50
51
52 sub isTrue {
53     my $v = shift || '0';
54     return 1 if ($v == 1);
55     return 1 if ($v =~ /^t/io);
56     return 1 if ($v =~ /^y/io);
57     return 0;
58 }
59
60 sub ou_ancestor_setting_value_or_cache {
61     # cache should be specific to setting
62     my ($e, $org_id, $setting, $cache) = @_;
63
64     if (not exists $cache->{$org_id}) {
65         my $r = $U->ou_ancestor_setting(
66             $org_id, $setting, $e # undef $e is ok
67         );
68
69         if ($r) {
70             $cache->{$org_id} = $r->{value};
71         } else {
72             $cache->{$org_id} = undef;
73         }
74     }
75     return $cache->{$org_id};
76 }
77
78 my $parser = DateTime::Format::ISO8601->new;
79 my $log = 'OpenSRF::Utils::Logger';
80
81 sub open_noncat_circs {
82     my $self = shift;
83     my $client = shift;
84     my $user = shift;
85
86     my $a = action::non_cataloged_circulation->table;
87     my $c = config::non_cataloged_type->table;
88
89     my $sql = <<"    SQL";
90         SELECT  a.id
91           FROM  $a a
92             JOIN $c c ON (a.item_type = c.id)
93           WHERE a.circ_time + c.circ_duration > current_timestamp
94             AND a.patron = ?
95     SQL
96
97     return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
98 }
99 __PACKAGE__->register_method(
100     api_name  => 'open-ils.storage.action.open_non_cataloged_circulation.user',
101     method    => 'open_noncat_circs',
102     api_level => 1,
103     argc      => 1,
104 );
105
106
107 sub ou_hold_requests {
108     my $self = shift;
109     my $client = shift;
110     my $ou = shift;
111
112     my $h_table = action::hold_request->table;
113     my $c_table = asset::copy->table;
114     my $o_table = actor::org_unit->table;
115
116     my $SQL = <<"    SQL";
117         SELECT  h.id
118           FROM  $h_table h
119             JOIN $c_table cp ON (cp.id = h.current_copy)
120             JOIN $o_table ou ON (ou.id = cp.circ_lib)
121           WHERE ou.id = ?
122             AND h.capture_time IS NULL
123             AND h.cancel_time IS NULL
124             AND (h.expire_time IS NULL OR h.expire_time > NOW())
125           ORDER BY h.request_time
126     SQL
127
128     my $sth = action::hold_request->db_Main->prepare_cached($SQL);
129     $sth->execute($ou);
130
131     $client->respond($_) for (
132         map {
133             $self
134                 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
135                 ->run($_)
136         } map {
137             $_->[0]
138         } @{ $sth->fetchall_arrayref }
139     );
140     return undef;
141 }
142 __PACKAGE__->register_method(
143     api_name        => 'open-ils.storage.action.targeted_hold_request.org_unit',
144     api_level       => 1,
145     argc        => 1,
146     stream      => 1,
147     method          => 'ou_hold_requests',
148 );
149
150
151 # partition -- if set, an 'undef' will be inserted into the result list
152 # between the last circulation and the first reservation.  This is
153 # useful in conjunction with 'idlist' so the caller can tell what type 
154 # of transaction the ID refers to without having to query the DB.
155 # skip_no_fines - filter out transactions which will never be billed, 
156 # e.g. circs with a $0 max fine or $0 recurring fine.
157 sub overdue_circs {
158     my $upper_interval = shift || '1 millennium';
159     my $idlist = shift;
160     my $partition = shift;
161     my $skip_no_fines = shift;
162
163     # Only retrieve ID's in the initial query if that's all the caller needs.
164     my $contents = $idlist ? 'id' : '*';
165
166     my $fines_filter = $skip_no_fines ? 
167         'AND recurring_fine <> 0 AND max_fine <> 0' : '';
168
169     my $c_t = action::circulation->table;
170
171     my $sql = <<"    SQL";
172         SELECT  $contents
173           FROM  $c_t
174           WHERE stop_fines IS NULL
175             $fines_filter
176             AND due_date < ( CURRENT_TIMESTAMP - grace_period )
177             AND fine_interval < ?::INTERVAL
178     SQL
179
180     my $sth = action::circulation->db_Main->prepare_cached($sql);
181     $sth->execute($upper_interval);
182
183     my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
184
185     push (@circs, undef) if $partition;
186
187     $fines_filter = $skip_no_fines ? 
188         'AND fine_amount <> 0 AND max_fine <> 0' : '';
189
190     $c_t = booking::reservation->table;
191     $sql = <<"    SQL";
192         SELECT  $contents
193           FROM  $c_t
194           WHERE return_time IS NULL
195             $fines_filter
196             AND end_time < ( CURRENT_TIMESTAMP )
197             AND fine_interval IS NOT NULL
198             AND cancel_time IS NULL
199     SQL
200
201     $sth = action::circulation->db_Main->prepare_cached($sql);
202     $sth->execute();
203
204     push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
205
206     return @circs;
207 }
208
209 sub complete_reshelving {
210     my $self = shift;
211     my $client = shift;
212     my $window = shift;
213
214     local $OpenILS::Application::Storage::WRITE = 1;
215
216     throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
217         unless (interval_to_seconds( $window ));
218
219     my $cp = asset::copy->table;
220
221     my $sql = <<"    SQL";
222         UPDATE  $cp
223           SET   status = 0
224           WHERE id IN (
225             SELECT cp.id 
226             FROM  $cp cp
227             WHERE cp.status = 7
228                 AND cp.status_changed_time < NOW() - CAST( COALESCE( BTRIM( (SELECT value FROM actor.org_unit_ancestor_setting('circ.reshelving_complete.interval', cp.circ_lib)),'"' ), ? )  AS INTERVAL)
229           )
230     SQL
231     my $sth = action::circulation->db_Main->prepare_cached($sql);
232     $sth->execute($window);
233
234     return $sth->rows;
235
236 }
237 __PACKAGE__->register_method(
238     api_name        => 'open-ils.storage.action.circulation.reshelving.complete',
239     api_level       => 1,
240     argc        => 1,
241     method          => 'complete_reshelving',
242 );
243
244 sub mark_longoverdue {
245     my $self = shift;
246     my $client = shift;
247     my $window = shift;
248
249     local $OpenILS::Application::Storage::WRITE = 1;
250
251     throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
252         unless (interval_to_seconds( $window ));
253
254     my $setting = actor::org_unit_setting->table;
255     my $circ = action::circulation->table;
256
257     my $sql = <<"    SQL";
258         UPDATE  $circ
259           SET   stop_fines = 'LONGOVERDUE',
260             stop_fines_time = now()
261           WHERE id IN (
262             SELECT  circ.id
263                       FROM  $circ circ
264                             LEFT JOIN $setting setting
265                                 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
266                       WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
267                             AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? )  AS INTERVAL)
268                   )
269     SQL
270
271     my $sth = action::circulation->db_Main->prepare_cached($sql);
272     $sth->execute($window);
273
274     return $sth->rows;
275
276 }
277 __PACKAGE__->register_method(
278     api_name        => 'open-ils.storage.action.circulation.long_overdue',
279     api_level       => 1,
280     argc        => 1,
281     method          => 'mark_longoverdue',
282 );
283
284 sub auto_thaw_frozen_holds {
285     my $self = shift;
286     my $client = shift;
287
288     local $OpenILS::Application::Storage::WRITE = 1;
289
290     my $holds = action::hold_request->table;
291
292     my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
293
294     my $sth = action::hold_request->db_Main->prepare_cached($sql);
295     $sth->execute();
296
297     return $sth->rows;
298
299 }
300 __PACKAGE__->register_method(
301     api_name        => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
302     api_level       => 1,
303     stream      => 0,
304     argc        => 0,
305     method          => 'auto_thaw_frozen_holds',
306 );
307
308 sub grab_overdue {
309     my $self = shift;
310     my $client = shift;
311
312     my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
313     
314     $client->respond( $idlist ? $_ : $_->to_fieldmapper ) 
315         for ( overdue_circs('', $idlist, undef, 1) );
316
317     return undef;
318
319 }
320 __PACKAGE__->register_method(
321     api_name        => 'open-ils.storage.action.circulation.overdue',
322     api_level       => 1,
323     stream          => 1,
324     method          => 'grab_overdue',
325     signature       => q/
326         Return list of overdue circulations and reservations to be used for fine generation.
327         Despite the name, this is not a generic method for retrieving all overdue loans,
328         as it excludes loans that have already hit the maximum fine limit
329         and transactions which do not accrue fines.
330 /,
331 );
332 __PACKAGE__->register_method(
333     api_name        => 'open-ils.storage.action.circulation.overdue.id_list',
334     api_level       => 1,
335     stream      => 1,
336     method          => 'grab_overdue',
337 );
338
339 sub get_hold_sort_order {
340     my ($ou) = @_;
341
342     my $dbh = action::hold_request->db_Main;
343
344     # The purpose of this function is to return column names in a DB-configured
345     # order, so it won't do to add columns here or change column names unless
346     # you also change the expectation of anything calling this function.
347
348     my $row = $dbh->selectrow_hashref(
349         q!
350         SELECT
351             cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
352             cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
353         FROM config.best_hold_order cbho
354         WHERE id = (
355             SELECT oils_json_to_text(value)::INT
356             FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
357         )
358         !, undef, $ou
359     ) || {
360         pprox => 1, hprox => 8, aprox => 2, priority => 3,
361         cut => 4, depth => 5, htime => 7, rtime => 6
362     };
363
364     # Return only the keys of our hash, sorted by value,
365     # keys for null values omitted.
366     return [
367         grep { defined $row->{$_} } (
368             sort {$row->{$a} cmp $row->{$b}} keys %$row
369         )
370     ];
371 }
372
373 # Returns an ORDER BY clause
374 # *and* a string with a CTE expression to precede the nearest-hold SQL query
375 # *and* a string with extra JOIN statements needed
376 sub build_hold_sort_clause {
377     my ($columns, $cp, $here) = @_;
378
379     my %order_by_sprintf_args = (
380         hprox => [$cp->call_number->owning_lib],
381         approx => [$cp->id, $here],
382         htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
383         shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
384     );
385
386     my @clauses;
387     my $ctes_needed = 0;
388     foreach my $col (@$columns) {
389         if ($col eq 'htime' and not $ctes_needed) {
390             $ctes_needed = 1;
391         } elsif ($col eq 'shtime') {
392             $ctes_needed = 2;
393         }
394
395         my @args;
396         @args = @{$order_by_sprintf_args{$col}} if
397             exists $order_by_sprintf_args{$col};
398
399         push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
400
401         last if $col eq 'rtime';    # rtime is effectively unique, no need for
402                                     # more order-by clauses after that.
403     }
404
405     my ($ctes, $joins) = ("", "");
406     if ($ctes_needed >= 1) {
407         # Each CTE serves the next. The first is one version or another
408         # of last_event_on_copy, which is described in holds-go-home.txt
409         # TechRef, but it essentially returns place and time of the most
410         # recent transit or circ to do with a copy, and failing that it
411         # returns a synthetic event that means "here" and "now".
412
413         if ($ctes_needed == 2) {
414             $ctes .= sprintf(q!
415 , last_event_on_copy AS (    -- combined circ and transit version
416     SELECT *
417     FROM (
418         (   SELECT
419                 TRUE AS concrete,
420                 dest AS place,
421                 COALESCE(dest_recv_time, source_send_time) AS moment
422             FROM action.transit_copy
423             WHERE target_copy = %d
424             ORDER BY moment DESC LIMIT 1
425         ) UNION (
426             SELECT
427                 TRUE AS concrete,
428                 COALESCE(checkin_lib, circ_lib) AS place,
429                 COALESCE(checkin_time, xact_start) AS moment
430             FROM action.circulation
431             WHERE target_copy = %d
432             ORDER BY moment DESC LIMIT 1
433         ) UNION
434             SELECT
435                 FALSE AS concrete,
436                 %d AS place,
437                 NOW() AS moment
438     ) x ORDER BY concrete DESC, moment DESC LIMIT 1
439 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
440         } else {
441             $ctes .= sprintf(q!
442 , last_event_on_copy AS (   -- circ only version
443     SELECT * FROM (
444         ( SELECT
445                 TRUE AS concrete,
446                 COALESCE(checkin_lib, circ_lib) AS place,
447                 COALESCE(checkin_time, xact_start) AS moment
448             FROM action.circulation
449             WHERE target_copy = %d
450             ORDER BY moment DESC LIMIT 1
451         ) UNION SELECT
452                 FALSE AS concrete,
453                 %d AS place,
454                 NOW() AS moment
455     ) x ORDER BY concrete DESC, moment DESC LIMIT 1
456 ) !, $cp->id, $cp->call_number->owning_lib);
457         }
458
459         $joins .= q!
460             JOIN last_event_on_copy ON (true)
461         !;
462
463         # For our next auxiliary query, the question we seek to answer is,
464         # "has our copy been circulating away from home too long?"
465         #
466         # Have there been no checkouts at the copy's circ_lib since the
467         # beginning of our go-home interval?
468
469         # [We use sprintf because the outer function that's going to send one
470         # big query through DBI is blind to our process of dynamically building
471         # these CTEs, and it wouldn't know what bind parameters to pass unless
472         # we did a lot more work here. This is injection-safe because we only
473         # use the %d formatter.]
474         $ctes .= sprintf(q!
475 , copy_has_not_been_home AS (
476     SELECT (
477         -- part 1
478         SELECT MIN(circ.id) FROM action.circulation circ
479         JOIN go_home_interval ON (true)
480         WHERE
481             circ.target_copy = %d AND
482             circ.circ_lib = %d AND
483             circ.xact_start >= NOW() - go_home_interval.value
484     ) IS NULL AS result
485 ) !, $cp->id, $cp->circ_lib);
486
487         $joins .= q!
488             JOIN copy_has_not_been_home ON (true)
489         !;
490     }
491
492     if ($ctes_needed == 2) {
493         # By this query, we mean to determine that the copy hasn't landed at
494         # home by means of transit during the go-home interval (in addition
495         # to not having circulated from home in the same time frame).
496         #
497         # There have been no homebound transits that arrived for this copy
498         # since the beginning of the go-home interval.
499
500         $ctes .= sprintf(q!
501 , copy_has_not_been_home_even_to_idle AS (
502     SELECT result AND NOT (
503         SELECT COUNT(*)::INT::BOOL
504         FROM action.transit_copy atc
505         WHERE
506             atc.target_copy = %d AND
507             (atc.dest = %d OR atc.source = %d) AND
508             atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
509     ) AS result FROM copy_has_not_been_home
510 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
511         $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
512     }
513
514     return (
515         join(", ", @clauses),
516         $ctes,
517         $joins
518     );
519 }
520
521 sub nearest_hold {
522     my $self = shift;
523     my $client = shift;
524     my $here = shift;   # just the ID
525     my $cp = shift;     # now an object with call_number fleshed,
526                         # formerly just copy ID
527     my $limit = int(shift()) || 10;
528     my $age = shift() || '0 seconds';
529     my $fifo = shift();
530
531     $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
532
533     # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
534     # are working with a circ lib ID and not an object
535     my $cp_circ_lib;
536     if (ref $cp->circ_lib) {
537         $cp_circ_lib = $cp->circ_lib->id;
538     } else {
539         $cp_circ_lib = $cp->circ_lib;
540     }
541
542     my $cp_owning_lib;
543     if (ref $cp->call_number->owning_lib) {
544         $cp_owning_lib = $cp->call_number->owning_lib->id;
545     } else {
546         $cp_owning_lib = $cp->call_number->owning_lib;
547     }
548
549     my ($holdsort, $addl_cte, $addl_join) =
550         build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
551
552     local $OpenILS::Application::Storage::WRITE = 1;
553
554     my $ids = action::hold_request->db_Main->selectcol_arrayref(<<"    SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
555         WITH go_home_interval AS (
556             SELECT OILS_JSON_TO_TEXT(
557                 (SELECT value FROM actor.org_unit_ancestor_setting(
558                     'circ.hold_go_home_interval', ?
559                 )
560             ))::INTERVAL AS value
561         )
562         $addl_cte
563         SELECT  h.id
564           FROM  action.hold_request h
565             JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
566             JOIN action.hold_copy_map hm ON (hm.hold = h.id)
567             JOIN actor.usr au ON (au.id = h.usr)
568             JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
569             LEFT JOIN actor.usr_standing_penalty ausp
570                 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
571             LEFT JOIN config.standing_penalty csp
572                 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
573             $addl_join
574           WHERE hm.target_copy = ?
575             AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
576             AND h.capture_time IS NULL
577             AND h.cancel_time IS NULL
578             AND (h.expire_time IS NULL OR h.expire_time > NOW())
579             AND h.frozen IS FALSE
580             AND csp.id IS NULL
581         ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
582         LIMIT $limit
583     SQL
584     
585     $client->respond( $_ ) for ( @$ids );
586     return undef;
587 }
588 __PACKAGE__->register_method(
589     api_name    => 'open-ils.storage.action.hold_request.nearest_hold',
590     api_level   => 1,
591     stream      => 1,
592     method      => 'nearest_hold',
593 );
594
595 sub targetable_holds {
596     my $self = shift;
597     my $client = shift;
598     my $check_expire = shift;
599
600     $check_expire ||= '12h';
601
602     local $OpenILS::Application::Storage::WRITE = 1;
603
604     # json_query can *almost* represent this query, but can't
605     # handle the CASE statement or the interval arithmetic
606     my $query = <<"    SQL";
607         SELECT ahr.id, mmsm.metarecord
608         FROM action.hold_request ahr
609         JOIN reporter.hold_request_record USING (id)
610         JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
611         WHERE capture_time IS NULL
612         AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
613         AND fulfillment_time IS NULL
614         AND cancel_time IS NULL
615         AND NOT frozen
616         ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
617     SQL
618     my $sth = action::hold_request->db_Main->prepare_cached($query);
619     $sth->execute($check_expire);
620     $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
621
622     return undef;
623 }
624
625 __PACKAGE__->register_method(
626     api_name    => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
627     api_level   => 1,
628     stream      => 1,
629     method      => 'targetable_holds',
630     signature   => q/
631         Returns ordered list of hold request and metarecord IDs
632         for all hold requests that are available for initial targeting
633         or retargeting.
634         @param check interval
635         @return list of pairs of hold request and metarecord IDs
636 /,
637 );
638
639 sub next_resp_group_id {
640     my $self = shift;
641     my $client = shift;
642
643     # XXX This is not replication safe!!!
644
645     my ($id) = action::survey->db_Main->selectrow_array(<<"    SQL");
646         SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
647     SQL
648     return $id;
649 }
650 __PACKAGE__->register_method(
651     api_name        => 'open-ils.storage.action.survey_response.next_group_id',
652     api_level       => 1,
653     method          => 'next_resp_group_id',
654 );
655
656 sub patron_circ_summary {
657     my $self = shift;
658     my $client = shift;
659     my $id = ''.shift();
660
661     return undef unless ($id);
662     my $c_table = action::circulation->table;
663     my $b_table = money::billing->table;
664
665     $log->debug("Retrieving patron summary for id $id", DEBUG);
666
667     my $select = <<"    SQL";
668         SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
669           FROM  $c_table c
670             LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
671           WHERE c.usr = ?
672             AND c.xact_finish IS NULL
673             AND (
674                 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
675                 OR c.stop_fines IS NULL
676             )
677     SQL
678
679     return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
680 }
681 __PACKAGE__->register_method(
682     api_name        => 'open-ils.storage.action.circulation.patron_summary',
683     api_level       => 1,
684     method          => 'patron_circ_summary',
685 );
686
687 #XXX Fix stored proc calls
688 sub find_local_surveys {
689     my $self = shift;
690     my $client = shift;
691     my $ou = ''.shift();
692
693     return undef unless ($ou);
694     my $s_table = action::survey->table;
695
696     my $select = <<"    SQL";
697         SELECT  s.*
698           FROM  $s_table s
699             JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
700           WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
701     SQL
702
703     my $sth = action::survey->db_Main->prepare_cached($select);
704     $sth->execute($ou);
705
706     $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
707
708     return undef;
709 }
710 __PACKAGE__->register_method(
711     api_name        => 'open-ils.storage.action.survey.all',
712     api_level       => 1,
713     stream          => 1,
714     method          => 'find_local_surveys',
715 );
716
717 #XXX Fix stored proc calls
718 sub find_opac_surveys {
719     my $self = shift;
720     my $client = shift;
721     my $ou = ''.shift();
722
723     return undef unless ($ou);
724     my $s_table = action::survey->table;
725
726     my $select = <<"    SQL";
727         SELECT  s.*
728           FROM  $s_table s
729             JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
730           WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
731             AND s.opac IS TRUE;
732     SQL
733
734     my $sth = action::survey->db_Main->prepare_cached($select);
735     $sth->execute($ou);
736
737     $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
738
739     return undef;
740 }
741 __PACKAGE__->register_method(
742     api_name        => 'open-ils.storage.action.survey.opac',
743     api_level       => 1,
744     stream          => 1,
745     method          => 'find_opac_surveys',
746 );
747
748 sub hold_pull_list {
749     my $self = shift;
750     my $client = shift;
751     my $ou = shift;
752     my $limit = shift || 10;
753     my $offset = shift || 0;
754
755     return undef unless ($ou);
756     my $h_table = action::hold_request->table;
757     my $a_table = asset::copy->table;
758     my $ord_table = asset::copy_location_order->table;
759
760     my $idlist = 1 if ($self->api_name =~/id_list/o);
761     my $count = 1 if ($self->api_name =~/count$/o);
762
763     my $status_filter = '';
764     $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
765
766     my $select = <<"    SQL";
767         SELECT  h.*
768           FROM  $h_table h
769             JOIN $a_table a ON (h.current_copy = a.id)
770             LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
771           WHERE a.circ_lib = ?
772             AND h.capture_time IS NULL
773             AND h.cancel_time IS NULL
774             AND (h.expire_time IS NULL OR h.expire_time > NOW())
775             AND NOT EXISTS (
776                 SELECT  1
777                   FROM  actor.usr_standing_penalty ausp
778                         JOIN config.standing_penalty csp ON (
779                             csp.id = ausp.standing_penalty
780                             AND csp.block_list LIKE '%CAPTURE%'
781                         )
782                   WHERE h.usr = ausp.usr
783                         AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
784             )
785             $status_filter
786           ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
787           LIMIT $limit
788           OFFSET $offset
789     SQL
790
791     if ($count) {
792         $select = <<"        SQL";
793             SELECT    count(DISTINCT h.id)
794               FROM    $h_table h
795                   JOIN $a_table a ON (h.current_copy = a.id)
796               WHERE    a.circ_lib = ?
797                   AND h.capture_time IS NULL
798                   AND h.cancel_time IS NULL
799                   AND (h.expire_time IS NULL OR h.expire_time > NOW())
800                   AND NOT EXISTS (
801                     SELECT  1
802                       FROM  actor.usr_standing_penalty ausp
803                             JOIN config.standing_penalty csp ON (
804                                 csp.id = ausp.standing_penalty
805                                 AND csp.block_list LIKE '%CAPTURE%'
806                             )
807                       WHERE h.usr = ausp.usr
808                             AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
809                 )
810                 $status_filter
811         SQL
812     }
813
814     my $sth = action::survey->db_Main->prepare_cached($select);
815     $sth->execute($ou);
816
817     if ($count) {
818         $client->respond( $sth->fetchall_arrayref()->[0][0] );
819     } elsif ($idlist) {
820         $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
821     } else {
822         $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
823     }
824
825     return undef;
826 }
827 __PACKAGE__->register_method(
828     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
829     api_level       => 1,
830     stream          => 1,
831     signature   => [
832         "Returns a count of holds for a specific library's pull list.",
833         [ [org_unit => "The library's org id", "number"] ],
834         ['A count of holds for the stated library to pull ', 'number']
835     ],
836     method          => 'hold_pull_list',
837 );
838 __PACKAGE__->register_method(
839     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
840     api_level       => 1,
841     stream          => 1,
842     signature   => [
843         "Returns a status filtered count of holds for a specific library's pull list.",
844         [ [org_unit => "The library's org id", "number"] ],
845         ['A status filtered count of holds for the stated library to pull ', 'number']
846     ],
847     method          => 'hold_pull_list',
848 );
849 __PACKAGE__->register_method(
850     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
851     api_level       => 1,
852     stream          => 1,
853     signature   => [
854         "Returns the hold ids for a specific library's pull list.",
855         [ [org_unit => "The library's org id", "number"],
856           [limit => 'An optional page size, defaults to 10', 'number'],
857           [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
858         ],
859         ['A list of holds for the stated library to pull for', 'array']
860     ],
861     method          => 'hold_pull_list',
862 );
863 __PACKAGE__->register_method(
864     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
865     api_level       => 1,
866     stream          => 1,
867     signature   => [
868         "Returns the holds for a specific library's pull list.",
869         [ [org_unit => "The library's org id", "number"],
870           [limit => 'An optional page size, defaults to 10', 'number'],
871           [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
872         ],
873         ['A list of holds for the stated library to pull for', 'array']
874     ],
875     method          => 'hold_pull_list',
876 );
877 __PACKAGE__->register_method(
878     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
879     api_level       => 1,
880     stream          => 1,
881     signature   => [
882         "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
883         [ [org_unit => "The library's org id", "number"],
884           [limit => 'An optional page size, defaults to 10', 'number'],
885           [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
886         ],
887         ['A list of holds for the stated library to pull for', 'array']
888     ],
889     method          => 'hold_pull_list',
890 );
891 __PACKAGE__->register_method(
892     api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
893     api_level       => 1,
894     stream          => 1,
895     signature   => [
896         "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
897         [ [org_unit => "The library's org id", "number"],
898           [limit => 'An optional page size, defaults to 10', 'number'],
899           [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
900         ],
901         ['A list of holds for the stated library to pull for', 'array']
902     ],
903     method          => 'hold_pull_list',
904 );
905
906 sub find_optional_surveys {
907     my $self = shift;
908     my $client = shift;
909     my $ou = ''.shift();
910
911     return undef unless ($ou);
912     my $s_table = action::survey->table;
913
914     my $select = <<"    SQL";
915         SELECT  s.*
916           FROM  $s_table s
917             JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
918           WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
919             AND s.required IS FALSE;
920     SQL
921
922     my $sth = action::survey->db_Main->prepare_cached($select);
923     $sth->execute($ou);
924
925     $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
926
927     return undef;
928 }
929 __PACKAGE__->register_method(
930     api_name        => 'open-ils.storage.action.survey.optional',
931     api_level       => 1,
932     stream          => 1,
933     method          => 'find_optional_surveys',
934 );
935
936 sub find_required_surveys {
937     my $self = shift;
938     my $client = shift;
939     my $ou = ''.shift();
940
941     return undef unless ($ou);
942     my $s_table = action::survey->table;
943
944     my $select = <<"    SQL";
945         SELECT  s.*
946           FROM  $s_table s
947             JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
948           WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
949             AND s.required IS TRUE;
950     SQL
951
952     my $sth = action::survey->db_Main->prepare_cached($select);
953     $sth->execute($ou);
954
955     $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
956
957     return undef;
958 }
959 __PACKAGE__->register_method(
960     api_name        => 'open-ils.storage.action.survey.required',
961     api_level       => 1,
962     stream          => 1,
963     method          => 'find_required_surveys',
964 );
965
966 sub find_usr_summary_surveys {
967     my $self = shift;
968     my $client = shift;
969     my $ou = ''.shift();
970
971     return undef unless ($ou);
972     my $s_table = action::survey->table;
973
974     my $select = <<"    SQL";
975         SELECT  s.*
976           FROM  $s_table s
977             JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
978           WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
979             AND s.usr_summary IS TRUE;
980     SQL
981
982     my $sth = action::survey->db_Main->prepare_cached($select);
983     $sth->execute($ou);
984
985     $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
986
987     return undef;
988 }
989 __PACKAGE__->register_method(
990     api_name        => 'open-ils.storage.action.survey.usr_summary',
991     api_level       => 1,
992     stream          => 1,
993     method          => 'find_usr_summary_surveys',
994 );
995
996 sub seconds_to_interval_hash {
997         my $interval = shift;
998         my $limit = shift || 's';
999         $limit =~ s/^(.)/$1/o;
1000
1001         my %output;
1002
1003         my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
1004         my ($year, $month, $week, $day, $hour, $minute, $second) =
1005                 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
1006
1007         if ($y = int($interval / (60 * 60 * 24 * 365))) {
1008                 $output{$year} = $y;
1009                 $ym = $interval % (60 * 60 * 24 * 365);
1010         } else {
1011                 $ym = $interval;
1012         }
1013         return %output if ($limit eq 'y');
1014
1015         if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
1016                 $output{$month} = $M;
1017                 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
1018         } else {
1019                 $Mm = $ym;
1020         }
1021         return %output if ($limit eq 'M');
1022
1023         if ($w = int($Mm / 604800)) {
1024                 $output{$week} = $w;
1025                 $wm = $Mm % 604800;
1026         } else {
1027                 $wm = $Mm;
1028         }
1029         return %output if ($limit eq 'w');
1030
1031         if ($d = int($wm / 86400)) {
1032                 $output{$day} = $d;
1033                 $dm = $wm % 86400;
1034         } else {
1035                 $dm = $wm;
1036         }
1037         return %output if ($limit eq 'd');
1038
1039         if ($h = int($dm / 3600)) {
1040                 $output{$hour} = $h;
1041                 $hm = $dm % 3600;
1042         } else {
1043                 $hm = $dm;
1044         }
1045         return %output if ($limit eq 'h');
1046
1047         if ($m = int($hm / 60)) {
1048                 $output{$minute} = $m;
1049                 $mm = $hm % 60;
1050         } else {
1051                 $mm = $hm;
1052         }
1053         return %output if ($limit eq 'm');
1054
1055         if ($s = int($mm)) {
1056                 $output{$second} = $s;
1057         } else {
1058                 $output{$second} = 0 unless (keys %output);
1059         }
1060         return %output;
1061 }
1062
1063
1064 sub generate_fines {
1065     my $self = shift;
1066     my $client = shift;
1067     my $circ = shift;
1068     my $overbill = shift;
1069
1070     local $OpenILS::Application::Storage::WRITE = 1;
1071
1072     my @circs;
1073     if ($circ) {
1074         push @circs,
1075             action::circulation->search_where( { id => $circ, stop_fines => undef } ),
1076             booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
1077     } else {
1078         push @circs, overdue_circs(undef, 1, 1, 1);
1079     }
1080
1081     $logger->info("fine generator processing ".scalar(@circs)." transactions");
1082
1083     my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
1084
1085     my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1086     my $handling_resvs = 0;
1087     for my $c (@circs) {
1088
1089         my $ctype = ref($c);
1090
1091         if (!$ctype) { # fetched via idlist
1092             if ($handling_resvs) {
1093                 $c = booking::reservation->retrieve($c);
1094             } elsif (not defined $c) {
1095                 # an undef value is the indicator that we are moving
1096                 # from processing circulations to reservations.
1097                 $handling_resvs = 1;
1098                 next;
1099             } else {
1100                 $c = action::circulation->retrieve($c);
1101             }
1102             $ctype = ref($c);
1103         }
1104
1105         $ctype =~ s/^.+::(\w+)$/$1/;
1106     
1107         my $due_date_method = 'due_date';
1108         my $target_copy_method = 'target_copy';
1109         my $circ_lib_method = 'circ_lib';
1110         my $recurring_fine_method = 'recurring_fine';
1111         my $is_reservation = 0;
1112         if ($ctype eq 'reservation') {
1113             $is_reservation = 1;
1114             $due_date_method = 'end_time';
1115             $target_copy_method = 'current_resource';
1116             $circ_lib_method = 'pickup_lib';
1117             $recurring_fine_method = 'fine_amount';
1118             next unless ($c->fine_interval);
1119         }
1120         #TODO: reservation grace periods
1121         my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1122
1123         eval {
1124             if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1125                 $log->debug("Cleaning up after previous transaction\n");
1126                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1127             }
1128             $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1129             $log->info(
1130                 sprintf("Processing %s %d...",
1131                     ($is_reservation ? "reservation" : "circ"), $c->id
1132                 )
1133             );
1134
1135
1136             my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1137     
1138             my $due = $due_dt->epoch;
1139             my $now = time;
1140
1141             my $fine_interval = $c->fine_interval;
1142             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1143             $fine_interval = interval_to_seconds( $fine_interval );
1144     
1145             if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1146                 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1147                 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1148                 return;
1149             }
1150
1151             if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {    
1152                 my $tz_offset_s = 0;
1153                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1154                     $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
1155                 }
1156     
1157                 $due -= ($due % $fine_interval) + $tz_offset_s;
1158                 $now -= ($now % $fine_interval) + $tz_offset_s;
1159             }
1160     
1161             $client->respond(
1162                 "ARG! Overdue $ctype ".$c->id.
1163                 " for item ".$c->$target_copy_method.
1164                 " (user ".$c->usr.").\n".
1165                 "\tItem was due on or before: ".localtime($due)."\n");
1166     
1167             my @fines = money::billing->search_where(
1168                 { xact => $c->id,
1169                   btype => 1,
1170                   billing_ts => { '>' => $c->$due_date_method } },
1171                 { order_by => 'billing_ts DESC'}
1172             );
1173
1174             my $f_idx = 0;
1175             my $fine = $fines[$f_idx] if (@fines);
1176             if ($overbill) {
1177                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1178             }
1179
1180             my $current_fine_total = 0;
1181             $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1182     
1183             my $last_fine;
1184             if ($fine) {
1185                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1186                 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1187             } else {
1188                 $log->info( "Potential first billing for circ ".$c->id );
1189                 $last_fine = $due;
1190
1191                 $grace_period = OpenILS::Application::Circ::CircCommon->extend_grace_period($c->$circ_lib_method->to_fieldmapper->id,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
1192             }
1193
1194             return if ($last_fine > $now);
1195             # Generate fines for each past interval, including the one we are inside
1196             my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1197
1198             if ( $last_fine == $due                         # we have no fines yet
1199                  && $grace_period                           # and we have a grace period
1200                  && $now < $due + $grace_period             # and some date math says were are within the grace period
1201             ) {
1202                 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1203                 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1204                 return;
1205             }
1206
1207             $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1208             return unless ($pending_fine_count);
1209
1210             my $recurring_fine = int($c->$recurring_fine_method * 100);
1211             my $max_fine = int($c->max_fine * 100);
1212
1213             my $skip_closed_check = $U->ou_ancestor_setting_value(
1214                 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1215             $skip_closed_check = $U->is_true($skip_closed_check);
1216
1217             my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
1218                 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
1219             $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
1220
1221             my ($latest_billing_ts, $latest_amount) = ('',0);
1222             for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1223     
1224                 if ($current_fine_total >= $max_fine) {
1225                     $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1226                     $client->respond(
1227                         "\tMaximum fine level of ".$c->max_fine.
1228                         " reached for this $ctype.\n".
1229                         "\tNo more fines will be generated.\n" );
1230                     last;
1231                 }
1232                 
1233                 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1234                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1235                 my $current_bill_count = $bill;
1236                 while ( $current_bill_count ) {
1237                     $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1238                     $current_bill_count--;
1239                 }
1240
1241                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1242                 if (!$skip_closed_check) {
1243                     my $dow = $billing_ts->day_of_week_0();
1244                     my $dow_open = "dow_${dow}_open";
1245                     my $dow_close = "dow_${dow}_close";
1246
1247                     if (my $h = $hoo{$c->$circ_lib_method}) {
1248                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1249                     }
1250     
1251                     my @cl = actor::org_unit::closed_date->search_where(
1252                             { close_start   => { '<=' => $timestamptz },
1253                               close_end => { '>=' => $timestamptz },
1254                               org_unit  => $c->$circ_lib_method }
1255                     );
1256                     next if (@cl);
1257                 }
1258
1259                 # The billing amount for this billing normally ought to be the recurring fine amount.
1260                 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
1261                 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
1262                 my $this_billing_amount = $recurring_fine;
1263                 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
1264                     $this_billing_amount = ($max_fine - $current_fine_total);
1265                 }
1266                 $current_fine_total += $this_billing_amount;
1267                 $latest_amount += $this_billing_amount;
1268                 $latest_billing_ts = $timestamptz;
1269
1270                 money::billing->create(
1271                     { xact      => ''.$c->id,
1272                       note      => "System Generated Overdue Fine",
1273                       billing_type  => "Overdue materials",
1274                       btype     => 1,
1275                       amount    => sprintf('%0.2f', $this_billing_amount/100),
1276                       billing_ts    => $timestamptz,
1277                     }
1278                 );
1279
1280             }
1281
1282             $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1283                 if ($latest_billing_ts and $latest_amount);
1284
1285             $self->method_lookup('open-ils.storage.transaction.commit')->run;
1286
1287             if(1) { 
1288
1289                 # Caluclate penalties inline
1290                 OpenILS::Utils::Penalty->calculate_penalties(
1291                     undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1292
1293             } else {
1294
1295                 # Calculate penalties with an aysnc call to the penalty server.  This approach
1296                 # may lead to duplicate penalties since multiple penalty processes for a
1297                 # given user may be running at the same time. Leave this here for reference 
1298                 # in case we later find that asyc calls are needed in some environments.
1299                 $penalty->request(
1300                     'open-ils.penalty.patron_penalty.calculate',
1301                     { patronid  => ''.$c->usr,
1302                     context_org => ''.$c->$circ_lib_method,
1303                     update  => 1,
1304                     background  => 1,
1305                     }
1306                 )->gather(1);
1307             }
1308
1309         };
1310
1311         if ($@) {
1312             my $e = $@;
1313             $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1314             $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1315             $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1316             last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1317         }
1318     }
1319 }
1320 __PACKAGE__->register_method(
1321     api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
1322     api_level       => 1,
1323     stream      => 1,
1324     method          => 'generate_fines',
1325 );
1326
1327
1328 sub MR_records_matching_format {
1329     my $self = shift;
1330     my $client = shift;
1331     my $MR = shift;
1332     my $filter = shift;
1333     my $org = shift;
1334     # include all visible copies, regardless of holdability
1335     my $opac_visible = shift;
1336
1337     # find filters for MR holds
1338     my $mr_filter;
1339     if (defined($filter)) {
1340         ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1341             'SELECT metabib.compile_composite_attr(?)',
1342             {},
1343             $filter
1344         )};
1345     }
1346
1347     my $records = [metabib::metarecord->retrieve($MR)->source_records];
1348
1349     my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1350     if ($opac_visible) {
1351         $vis_q = <<'        SQL';
1352             EXISTS(
1353                 SELECT 1 FROM asset.opac_visible_copies
1354                 WHERE record = ? AND circ_lib IN (
1355                     SELECT id FROM actor.org_unit_descendants(?)
1356                 )
1357             )
1358         SQL
1359     }
1360
1361     my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1362     my @args = ( $mr_filter, $org );
1363     if (!$mr_filter) {
1364         $q = "SELECT true WHERE $vis_q";
1365         @args = ( $org );
1366     }
1367
1368     for my $r ( map { isTrue($_->deleted) ?  () : ($_->id) } @$records ) {
1369         # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1370         $client->respond($r)
1371             if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1372     }
1373
1374     return; # discard final l-val
1375 }
1376 __PACKAGE__->register_method(
1377     api_name        => 'open-ils.storage.metarecord.filtered_records',
1378     api_level       => 1,
1379     stream          => 1,
1380     argc            => 2,
1381     method          => 'MR_records_matching_format',
1382 );
1383
1384
1385 sub new_hold_copy_targeter {
1386     my $self = shift;
1387     my $client = shift;
1388     my $check_expire = shift;
1389     my $one_hold = shift;
1390     my $find_copy = shift;
1391
1392     local $OpenILS::Application::Storage::WRITE = 1;
1393
1394     $self->{target_weight} = {};
1395     $self->{max_loops} = {};
1396
1397     my $holds;
1398
1399     try {
1400         if ($one_hold) {
1401             $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1402             $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1403         } elsif ( $check_expire ) {
1404
1405             # what's the retarget time threashold?
1406             my $time = time;
1407             $check_expire ||= '12h';
1408             $check_expire = interval_to_seconds( $check_expire );
1409
1410             my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1411             $year += 1900;
1412             $mon += 1;
1413             my $expire_threshold = sprintf(
1414                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1415                 $year, $mon, $mday, $hour, $min, $sec
1416             );
1417
1418             # find all the holds holds needing retargeting
1419             $holds = [ action::hold_request->search_where(
1420                             { capture_time => undef,
1421                               fulfillment_time => undef,
1422                               cancel_time => undef,
1423                               frozen => 'f',
1424                               prev_check_time => { '<=' => $expire_threshold },
1425                             },
1426                             { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1427
1428             # find all the holds holds needing first time targeting
1429             push @$holds, action::hold_request->search(
1430                             capture_time => undef,
1431                             fulfillment_time => undef,
1432                             prev_check_time => undef,
1433                             frozen => 'f',
1434                             cancel_time => undef,
1435                             { order_by => 'selection_depth DESC, request_time' } );
1436         } else {
1437
1438             # find all the holds holds needing first time targeting ONLY
1439             $holds = [ action::hold_request->search(
1440                             capture_time => undef,
1441                             fulfillment_time => undef,
1442                             prev_check_time => undef,
1443                             cancel_time => undef,
1444                             frozen => 'f',
1445                             { order_by => 'selection_depth DESC, request_time' } ) ];
1446         }
1447     } catch Error with {
1448         my $e = shift;
1449         die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1450     };
1451
1452     my @closed = actor::org_unit::closed_date->search_where(
1453         { close_start => { '<=', 'now' },
1454           close_end => { '>=', 'now' } }
1455     );
1456
1457     if ($check_expire) {
1458
1459         # $check_expire, if it exists, was already converted to seconds
1460         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1461         $year += 1900;
1462         $mon += 1;
1463
1464         my $next_check_time = sprintf(
1465             '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1466             $year, $mon, $mday, $hour, $min, $sec
1467         );
1468
1469
1470         my @closed_at_next = actor::org_unit::closed_date->search_where(
1471             { close_start => { '<=', $next_check_time },
1472               close_end => { '>=', $next_check_time } }
1473         );
1474
1475         my @new_closed;
1476         for my $c_at_n (@closed_at_next) {
1477             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1478                 push @new_closed, $c_at_n;
1479             }
1480         }
1481         @closed = @new_closed;
1482     }
1483
1484     my @successes;
1485     my $actor = OpenSRF::AppSession->create('open-ils.actor');
1486     my $editor = new_editor;
1487
1488     my $target_when_closed = {};
1489     my $target_when_closed_if_at_pickup_lib = {};
1490
1491     for my $hold (@$holds) {
1492         try {
1493             #start a transaction if needed
1494             if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1495                 $log->debug("Cleaning up after previous transaction\n");
1496                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1497             }
1498             $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1499             $log->info("Processing hold ".$hold->id."...\n");
1500
1501             #first, re-fetch the hold, to make sure it's not captured already
1502             $hold->remove_from_object_index();
1503             $hold = action::hold_request->retrieve( $hold->id );
1504
1505             die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1506
1507             # remove old auto-targeting maps
1508             my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1509             $_->delete for (@oldmaps);
1510
1511             if ($hold->expire_time) {
1512                 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1513                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1514
1515                     # cancel cause = un-targeted expiration
1516                     $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1517
1518                     # refresh fields from the DB while still in the xact
1519                     my $fm_hold = $hold->to_fieldmapper; 
1520
1521                     $self->method_lookup('open-ils.storage.transaction.commit')->run;
1522
1523                     # tell A/T the hold was cancelled
1524                     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1525                     $ses->request('open-ils.trigger.event.autocreate', 
1526                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1527
1528                     die "OK\n";
1529                 }
1530             }
1531
1532             my $all_copies = [];
1533
1534             # find all the potential copies
1535             if ($hold->hold_type eq 'M') {
1536                 for my $r_id (
1537                     $self->method_lookup(
1538                         'open-ils.storage.metarecord.filtered_records'
1539                     )->run( $hold->target, $hold->holdable_formats )
1540                 ) {
1541                     my ($rtree) = $self
1542                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1543                         ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1544
1545                     for my $cn ( @{ $rtree->call_numbers } ) {
1546                         push @$all_copies,
1547                             asset::copy->search_where(
1548                                 { id => [map {$_->id} @{ $cn->copies }],
1549                                   deleted => 'f' }
1550                             ) if ($cn && @{ $cn->copies });
1551                     }
1552                 }
1553             } elsif ($hold->hold_type eq 'T') {
1554                 my ($rtree) = $self
1555                     ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1556                     ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1557
1558                 unless ($rtree) {
1559                     push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1560                     die "OK\n";
1561                 }
1562
1563                 for my $cn ( @{ $rtree->call_numbers } ) {
1564                     push @$all_copies,
1565                         asset::copy->search_where(
1566                             { id => [map {$_->id} @{ $cn->copies }],
1567                               deleted => 'f' }
1568                         ) if ($cn && @{ $cn->copies });
1569                 }
1570             } elsif ($hold->hold_type eq 'V') {
1571                 my ($vtree) = $self
1572                     ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1573                     ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1574
1575                 push @$all_copies,
1576                     asset::copy->search_where(
1577                         { id => [map {$_->id} @{ $vtree->copies }],
1578                           deleted => 'f' }
1579                     ) if ($vtree && @{ $vtree->copies });
1580
1581             } elsif ($hold->hold_type eq 'P') {
1582                 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1583                 $all_copies = [
1584                     asset::copy->search_where(
1585                         { id => [map {$_->target_copy} @part_maps],
1586                           deleted => 'f' }
1587                     )
1588                 ] if (@part_maps);
1589                     
1590             } elsif ($hold->hold_type eq 'I') {
1591                 my ($itree) = $self
1592                     ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1593                     ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1594
1595                 push @$all_copies,
1596                     asset::copy->search_where(
1597                         { id => [map {$_->unit->id} @{ $itree->items }],
1598                           deleted => 'f' }
1599                     ) if ($itree && @{ $itree->items });
1600                     
1601             } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1602                 my $_cp = asset::copy->retrieve($hold->target);
1603                 push @$all_copies, $_cp if $_cp;
1604             }
1605
1606             # Force and recall holds bypass pretty much everything
1607             if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1608                 # trim unholdables
1609                 @$all_copies = grep {   isTrue($_->status->holdable) && 
1610                             isTrue($_->location->holdable) && 
1611                             isTrue($_->holdable) &&
1612                             !isTrue($_->deleted) &&
1613                             (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1614                             ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1615                                 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1616                         } @$all_copies;
1617             }
1618
1619             # let 'em know we're still working
1620             $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1621             
1622             # if we have no copies ...
1623             if (!ref $all_copies || !@$all_copies) {
1624                 $log->info("\tNo copies available for targeting at all!\n");
1625                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1626
1627                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1628                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1629                 die "OK\n";
1630             }
1631
1632             my $copy_count = @$all_copies;
1633             my $found_copy = undef;
1634             $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1635
1636             # map the potentials, so that we can pick up checkins
1637             my $hold_copy_map = {};
1638             $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1639                 for (
1640                     map {
1641                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1642                     } @$all_copies
1643                 );
1644
1645             my $pu_lib = ''.$hold->pickup_lib;
1646             my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1647             $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1648
1649             #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1650
1651             my @good_copies;
1652             for my $c (@$all_copies) {
1653                 # current target
1654                 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1655
1656                 # skip on circ lib is closed IFF we care
1657                 my $ignore_closing;
1658
1659                 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1660                     $ignore_closing = ou_ancestor_setting_value_or_cache(
1661                         $editor,
1662                         ''.$c->circ_lib,
1663                         'circ.holds.target_when_closed_if_at_pickup_lib',
1664                         $target_when_closed_if_at_pickup_lib
1665                     ) || 0;
1666                 }
1667                 if (not $ignore_closing) {  # one more chance to find a reason
1668                                             # to ignore OU closedness.
1669                     $ignore_closing = ou_ancestor_setting_value_or_cache(
1670                         $editor,
1671                         ''.$c->circ_lib,
1672                         'circ.holds.target_when_closed',
1673                         $target_when_closed
1674                     ) || 0;
1675                 }
1676
1677 #               $logger->info(
1678 #                   "For hold " . $hold->id . " and copy with circ_lib " .
1679 #                   $c->circ_lib . " we " .
1680 #                   ($ignore_closing ? "ignore" : "respect")
1681 #                   . " closed dates"
1682 #               );
1683
1684                 next if (
1685                     (not $ignore_closing) and
1686                     (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1687                 );
1688
1689                 # target of another hold
1690                 next if (action::hold_request
1691                         ->search_where(
1692                             { current_copy => $c->id,
1693                               fulfillment_time => undef,
1694                               cancel_time => undef,
1695                             }
1696                         )
1697                 );
1698
1699                 # we passed all three, keep it
1700                 push @good_copies, $c if ($c);
1701                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1702             }
1703
1704             $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1705
1706             my $old_best = $hold->current_copy;
1707             my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1708             $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1709             $hold->update({ current_copy => undef }) if ($old_best);
1710     
1711             if (!scalar(@good_copies)) {
1712                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1713                 if ( $old_best_still_valid ) {
1714                     # the old copy is still available
1715                     $log->debug("\tPushing current_copy back onto the targeting list");
1716                     push @good_copies, $old_best;
1717                 } else {
1718                     # oops, old copy is not available
1719                     $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1720                     $hold->update( { prev_check_time => 'today' } );
1721                     $self->method_lookup('open-ils.storage.transaction.commit')->run;
1722                     push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1723                     die "OK\n";
1724                 }
1725             }
1726
1727             # reset prox list after trimming good copies
1728             $prox_list = create_prox_list(
1729                 $self, $pu_lib,
1730                 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1731                 $hold, $hold_copy_map
1732             );
1733
1734             $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1735
1736             my $min_prox = [ sort keys %$prox_list ]->[0];
1737             my $best;
1738             if  ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1739                 $best = $good_copies[0] if(scalar @good_copies);
1740             } else {
1741                 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1742             }
1743
1744             $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1745
1746             if (!$best) {
1747                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1748
1749                 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1750                     $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1751                 );
1752
1753                 if (defined($self->{max_loops}{$pu_lib})) {
1754                     $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1755
1756                     my %circ_lib_map =  map { (''.$_->circ_lib => 1) } @$all_copies;
1757                     my $circ_lib_list = [keys %circ_lib_map];
1758     
1759                     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1760     
1761                     # Grab the "biggest" loop for this hold so far
1762                     my $current_loop = $cstore->request(
1763                         'open-ils.cstore.json_query',
1764                         { distinct => 1,
1765                           select => { aufhmxl => ['max'] },
1766                           from => 'aufhmxl',
1767                           where => { hold => $hold->id}
1768                         }
1769                     )->gather(1);
1770     
1771                     $current_loop = $current_loop->{max} if ($current_loop);
1772                     $current_loop ||= 1;
1773     
1774                     my $exclude_list = $cstore->request(
1775                         'open-ils.cstore.json_query.atomic',
1776                         { distinct => 1,
1777                           select => { aufhol => ['circ_lib'] },
1778                           from => 'aufhol',
1779                           where => { hold => $hold->id}
1780                         }
1781                     )->gather(1);
1782     
1783                     my @keepers;
1784                     if ($exclude_list && @$exclude_list) {
1785                         $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1786                         # check to see if we've used up every library in the potentials list
1787                         for my $l ( @$circ_lib_list ) {
1788                             my $keep = 1;
1789                             for my $ex ( @$exclude_list ) {
1790                                 if ($ex eq $l) {
1791                                     $keep = 0;
1792                                     last;
1793                                 }
1794                             }
1795                             push(@keepers, $l) if ($keep);
1796                         }
1797                     } else {
1798                         @keepers = @$circ_lib_list;
1799                     }
1800     
1801                     $current_loop++ if (!@keepers);
1802     
1803                     if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1804                         # We haven't exceeded max_loops yet
1805                         my @keeper_copies;
1806                         for my $cp ( @$all_copies ) {
1807                             push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1808
1809                         }
1810                         $all_copies = [@keeper_copies];
1811                     } else {
1812                         # We have, and should remove potentials and cancel the hold
1813                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1814                         $_->delete for (@oldmaps);
1815
1816                         # cancel cause = un-targeted expiration
1817                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1818
1819                         # refresh fields from the DB while still in the xact
1820                         my $fm_hold = $hold->to_fieldmapper; 
1821
1822                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1823
1824                         # tell A/T the hold was cancelled
1825                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1826                         $ses->request('open-ils.trigger.event.autocreate', 
1827                             'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1828
1829                         die "OK\n";
1830                     }
1831
1832                     $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1833
1834                     $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1835
1836                 }
1837
1838                 $best = choose_nearest_copy($hold, $prox_list);
1839             }
1840
1841             $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1842             if ($old_best) {
1843                 # hold wasn't fulfilled, record the fact
1844             
1845                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1846                 action::unfulfilled_hold_list->create(
1847                         { hold => ''.$hold->id,
1848                           current_copy => ''.$old_best->id,
1849                           circ_lib => ''.$old_best->circ_lib,
1850                         });
1851             }
1852
1853             if ($best) {
1854                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1855                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1856             } elsif (
1857                 $old_best_still_valid &&
1858                 !action::hold_request
1859                     ->search_where(
1860                         { current_copy => $old_best->id,
1861                           fulfillment_time => undef,
1862                           cancel_time => undef,
1863                         }       
1864                     ) &&
1865                 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1866                     { title => $old_best->call_number->record->to_fieldmapper,
1867                       patron => $hold->usr->to_fieldmapper,
1868                       copy => $old_best->to_fieldmapper,
1869                       requestor => $hold->requestor->to_fieldmapper,
1870                       request_lib => $hold->request_lib->to_fieldmapper,
1871                       pickup_lib => $hold->pickup_lib->id,
1872                       retarget => 1
1873                     }
1874                 ))
1875             ) {     
1876                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1877                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1878             } else {
1879                 $hold->update( { prev_check_time => 'now' } );
1880                 $log->info( "\tThere were no targetable copies for the hold" );
1881                 process_recall($actor, $log, $hold, \@good_copies);
1882             }
1883
1884             $self->method_lookup('open-ils.storage.transaction.commit')->run;
1885             $log->info("\tProcessing of hold ".$hold->id." complete.");
1886
1887             push @successes,
1888                 { hold => $hold->id,
1889                   old_target => ($old_best ? $old_best->id : undef),
1890                   eligible_copies => $copy_count,
1891                   target => ($best ? $best->id : undef),
1892                   found_copy => $found_copy };
1893
1894         } otherwise {
1895             my $e = shift;
1896             if ($e !~ /^OK/o) {
1897                 $log->error("Processing of hold failed:  $e");
1898                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1899                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1900             }
1901         };
1902     }
1903
1904     return \@successes;
1905 }
1906 __PACKAGE__->register_method(
1907     api_name    => 'open-ils.storage.action.hold_request.copy_targeter',
1908     api_level   => 1,
1909     method      => 'new_hold_copy_targeter',
1910 );
1911
1912 sub process_recall {
1913     my ($actor, $log, $hold, $good_copies) = @_;
1914
1915     # Bail early if we don't have required settings to avoid spurious requests
1916     my ($recall_threshold, $return_interval, $fine_rules);
1917
1918     my $rv = $actor->request(
1919         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1920     )->gather(1);
1921
1922     if (!$rv) {
1923         $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1924         return;
1925     }
1926     $recall_threshold = $rv->{value};
1927
1928     $rv = $actor->request(
1929         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1930     )->gather(1);
1931
1932     if (!$rv) {
1933         $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1934         return;
1935     }
1936     $return_interval = $rv->{value};
1937
1938     $rv = $actor->request(
1939         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1940     )->gather(1);
1941
1942     if ($rv) {
1943         $fine_rules = $rv->{value};
1944     }
1945
1946     $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1947
1948     # We want checked out copies (status = 1) at the hold pickup lib
1949     my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1950
1951     my @copy_ids = map { $_->id } @$all_copies;
1952
1953     $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1954
1955     my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1956
1957     # Iterate over the checked-out copies to find a copy with a
1958     # loan period longer than the recall threshold:
1959     my $circs = [ action::circulation->search_where(
1960         { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1961         { order_by => 'due_date ASC' }
1962     )];
1963
1964     # If we have a candidate copy, then:
1965     if (scalar(@$circs)) {
1966         my $circ = $circs->[0];
1967         $log->info("Recalling circ ID : " . $circ->id);
1968
1969         # Give the user a new due date of either a full recall threshold,
1970         # or the return interval, whichever is further in the future
1971         my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1972         if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1973             $return_date = $threshold_date;
1974         }
1975
1976         my $update_fields = {
1977             due_date => $return_date,
1978             renewal_remaining => 0,
1979         };
1980
1981         # If the OU hasn't defined new fine rules for recalls, keep them
1982         # as they were
1983         if ($fine_rules) {
1984             $log->info("Apply recall fine rules: $fine_rules");
1985             my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1986             $update_fields->{recurring_fine} = $rules->[0];
1987             $update_fields->{fine_interval} = $rules->[1];
1988             $update_fields->{max_fine} = $rules->[2];
1989         }
1990
1991         # Adjust circ for current user
1992         $circ->update($update_fields);
1993
1994         # Create trigger event for notifying current user
1995         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1996         $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1997     }
1998
1999     $log->info("Processing of hold ".$hold->id." for recall is now complete.");
2000 }
2001
2002 sub reservation_targeter {
2003     my $self = shift;
2004     my $client = shift;
2005     my $one_reservation = shift;
2006
2007     local $OpenILS::Application::Storage::WRITE = 1;
2008
2009     my $reservations;
2010
2011     try {
2012         if ($one_reservation) {
2013             $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2014             $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
2015         } else {
2016
2017             # find all the reservations needing targeting
2018             $reservations = [
2019                 booking::reservation->search_where(
2020                     { current_resource => undef,
2021                       cancel_time => undef,
2022                       start_time => { '>' => 'now' }
2023                     },
2024                     { order_by => 'start_time' }
2025                 )
2026             ];
2027         }
2028     } catch Error with {
2029         my $e = shift;
2030         die "Could not retrieve reservation requests:\n\n$e\n";
2031     };
2032
2033     my @successes = ();
2034     for my $bresv (@$reservations) {
2035         try {
2036             #start a transaction if needed
2037             if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
2038                 $log->debug("Cleaning up after previous transaction\n");
2039                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2040             }
2041             $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2042             $log->info("Processing reservation ".$bresv->id."...\n");
2043
2044             #first, re-fetch the hold, to make sure it's not captured already
2045             $bresv->remove_from_object_index();
2046             $bresv = booking::reservation->retrieve( $bresv->id );
2047
2048             die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
2049
2050             my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
2051             if (DateTime->compare($end_time, DateTime->now) < 0) {
2052
2053                 # cancel cause = un-targeted expiration
2054                 $bresv->update( { cancel_time => 'now' } ); 
2055
2056                 # refresh fields from the DB while still in the xact
2057                 my $fm_bresv = $bresv->to_fieldmapper;
2058
2059                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2060
2061                 # tell A/T the reservation was cancelled
2062                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2063                 $ses->request('open-ils.trigger.event.autocreate', 
2064                     'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
2065
2066                 die "OK\n";
2067             }
2068
2069             my $possible_resources;
2070
2071             # find all the potential resources
2072             if (!$bresv->target_resource) {
2073                 my $filter = { type => $bresv->target_resource_type };
2074                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
2075
2076                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
2077
2078                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
2079                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
2080                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
2081             } else {
2082                 $possible_resources = $bresv->target_resource;
2083             }
2084
2085             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
2086             @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
2087
2088
2089             my @good_resources = ();
2090             my %conflicts = ();
2091             for my $res (@$all_resources) {
2092                 unless (isTrue($res->type->catalog_item)) {
2093                     push @good_resources, $res;
2094                     next;
2095                 }
2096
2097                 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
2098
2099                 unless ($copy) {
2100                     push @good_resources, $res;
2101                     next;
2102                 }
2103
2104                 # At this point, if we're just targeting one specific
2105                 # resource, just succeed. We don't care about its present
2106                 # copy status.
2107                 if ($bresv->target_resource) {
2108                     push @good_resources, $res;
2109                     next;
2110                 }
2111
2112                 if ($copy->status->id == 0 || $copy->status->id == 7) {
2113                     push @good_resources, $res;
2114                     next;
2115                 }
2116
2117                 if ($copy->status->id == 1) {
2118                     my $circs = [ action::circulation->search_where(
2119                         {target_copy => $copy->id, checkin_time => undef },
2120                         { order_by => 'id DESC' }
2121                     ) ];
2122
2123                     if (@$circs) {
2124                         my $due_date = $circs->[0]->due_date;
2125                         $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
2126                         my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
2127                         if (DateTime->compare($start_time, $due_date) < 0) {
2128                             $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
2129                             next;
2130                         }
2131
2132                         push @good_resources, $res;
2133                     }
2134
2135                     next;
2136                 }
2137
2138                 push @good_resources, $res if (isTrue($copy->status->holdable));
2139             }
2140
2141             # let 'em know we're still working
2142             $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2143             
2144             # if we have no copies ...
2145             if (!@good_resources) {
2146                 $log->info("\tNo resources available for targeting at all!\n");
2147                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
2148
2149
2150                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2151                 die "OK\n";
2152             }
2153
2154             $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
2155
2156             # LFW: note that after the inclusion of hold proximity
2157             # adjustment, this prox_list is the only prox_list
2158             # array in this perl package.  Other occurences are
2159             # hashes.
2160             my $prox_list = [];
2161             $$prox_list[0] =
2162             [
2163                 grep {
2164                     $_->owner == $bresv->pickup_lib
2165                 } @good_resources
2166             ];
2167
2168             $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2169             # $all_copies is now a list of copies not at the pickup library
2170
2171             my $best = shift @good_resources;
2172             $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2173
2174             if (!$best) {
2175                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2176
2177                 $prox_list =
2178                     map  { $_->[1] }
2179                     sort { $a->[0] <=> $b->[0] }
2180                     map  {
2181                         [   actor::org_unit_proximity->search_where(
2182                                 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2183                             )->[0]->prox,
2184                             $_
2185                         ]
2186                     } @$all_resources;
2187
2188                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2189
2190                 $best = shift @$prox_list
2191             }
2192
2193             if ($best) {
2194                 $bresv->update( { current_resource => ''.$best->id } );
2195                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2196             }
2197
2198             $self->method_lookup('open-ils.storage.transaction.commit')->run;
2199             $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2200
2201             push @successes,
2202                 { reservation => $bresv->id,
2203                   current_resource => ($best ? $best->id : undef) };
2204
2205         } otherwise {
2206             my $e = shift;
2207             if ($e !~ /^OK/o) {
2208                 $log->error("Processing of bresv failed:  $e");
2209                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2210                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2211             }
2212         };
2213     }
2214
2215     return \@successes;
2216 }
2217 __PACKAGE__->register_method(
2218     api_name    => 'open-ils.storage.booking.reservation.resource_targeter',
2219     api_level   => 1,
2220     method      => 'reservation_targeter',
2221 );
2222
2223 my $locations;
2224 my $statuses;
2225 my %cache = (titles => {}, cns => {});
2226
2227 sub copy_hold_capture {
2228     my $self = shift;
2229     my $hold = shift;
2230     my $cps = shift;
2231
2232     if (!defined($cps)) {
2233         try {
2234             $cps = [ asset::copy->search( id => $hold->target ) ];
2235         } catch Error with {
2236             my $e = shift;
2237             die "Could not retrieve initial volume list:\n\n$e\n";
2238         };
2239     }
2240
2241     my @copies = grep { $_->holdable } @$cps;
2242
2243     for (my $i = 0; $i < @$cps; $i++) {
2244         next unless $$cps[$i];
2245         
2246         my $cn = $cache{cns}{$copies[$i]->call_number};
2247         my $rec = $cache{titles}{$cn->record};
2248         $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2249         $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2250         $copies[$i] = undef if (
2251             !$copies[$i] ||
2252             !$self->{user_filter}->request(
2253                 'open-ils.circ.permit_hold',
2254                 $hold->to_fieldmapper, do {
2255                     my $cp_fm = $copies[$i]->to_fieldmapper;
2256                     $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2257                     $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2258                     $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2259                     $cp_fm;
2260                 },
2261                 { title => $rec->to_fieldmapper,
2262                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2263                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2264                 })->gather(1)
2265         );
2266         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2267     }
2268
2269     @copies = grep { $_ } @copies;
2270
2271     my $count = @copies;
2272
2273     return unless ($count);
2274     
2275     action::hold_copy_map->search( hold => $hold->id )->delete_all;
2276     
2277     my @maps;
2278     $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2279     for my $c (@copies) {
2280         push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2281     }
2282     $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2283
2284     return \@copies;
2285 }
2286
2287
2288 sub choose_nearest_copy {
2289     my $hold = shift;
2290     my $prox_list = shift;
2291
2292     for my $p ( sort keys %$prox_list ) {
2293         next unless (ref $$prox_list{$p});
2294
2295         my @capturable = @{ $$prox_list{$p} };
2296         next unless (@capturable);
2297
2298         my $rand = int(rand(scalar(@capturable)));
2299         my %seen = ();
2300         while (my ($c) = splice(@capturable, $rand, 1)) {
2301             return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2302                 { title => $c->call_number->record->to_fieldmapper,
2303                   patron => $hold->usr->to_fieldmapper,
2304                   copy => $c->to_fieldmapper,
2305                   requestor => $hold->requestor->to_fieldmapper,
2306                   request_lib => $hold->request_lib->to_fieldmapper,
2307                   pickup_lib => $hold->pickup_lib->id,
2308                   retarget => 1
2309                 }
2310             ));
2311             $seen{$c->id}++;
2312
2313             last unless(@capturable);
2314             $rand = int(rand(scalar(@capturable)));
2315         }
2316     }
2317 }
2318
2319 sub create_prox_list {
2320     my $self = shift;
2321     my $lib = shift;
2322     my $copies = shift;
2323     my $hold = shift;
2324     my $hold_copy_map = shift || {};
2325
2326     my %prox_list;
2327     my $editor = new_editor;
2328     for my $cp (@$copies) {
2329         my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2330         ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2331         next unless (defined($prox));
2332
2333         my $copy_circ_lib = ''.$cp->circ_lib;
2334         # Fetch the weighting value for hold targeting, defaulting to 1
2335         $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2336             $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2337         );
2338         $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2339         $self->{target_weight}{$copy_circ_lib} ||= 1;
2340
2341         $prox_list{$prox} = [] unless defined($prox_list{$prox});
2342         for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2343             push @{$prox_list{$prox}}, $cp;
2344         }
2345     }
2346     return \%prox_list;
2347 }
2348
2349 sub volume_hold_capture {
2350     my $self = shift;
2351     my $hold = shift;
2352     my $vols = shift;
2353
2354     if (!defined($vols)) {
2355         try {
2356             $vols = [ asset::call_number->search( id => $hold->target ) ];
2357             $cache{cns}{$_->id} = $_ for (@$vols);
2358         } catch Error with {
2359             my $e = shift;
2360             die "Could not retrieve initial volume list:\n\n$e\n";
2361         };
2362     }
2363
2364     my @v_ids = map { $_->id } @$vols;
2365
2366     my $cp_list;
2367     try {
2368         $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2369     
2370     } catch Error with {
2371         my $e = shift;
2372         warn "Could not retrieve copy list:\n\n$e\n";
2373     };
2374
2375     $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2376 }
2377
2378 sub title_hold_capture {
2379     my $self = shift;
2380     my $hold = shift;
2381     my $titles = shift;
2382
2383     if (!defined($titles)) {
2384         try {
2385             $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2386             $cache{titles}{$_->id} = $_ for (@$titles);
2387         } catch Error with {
2388             my $e = shift;
2389             die "Could not retrieve initial title list:\n\n$e\n";
2390         };
2391     }
2392
2393     my @t_ids = map { $_->id } @$titles;
2394     my $cn_list;
2395     try {
2396         ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2397     
2398     } catch Error with {
2399         my $e = shift;
2400         warn "Could not retrieve volume list:\n\n$e\n";
2401     };
2402
2403     $cache{cns}{$_->id} = $_ for (@$cn_list);
2404
2405     $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2406 }
2407
2408
2409 1;