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