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