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