1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
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/;
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";
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 = (
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',
32 rtime => 'h.request_time',
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)
40 !, # $cp->call_number->owning_lib x 2
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)
48 !, # $cp->call_number->owning_lib x 2
54 return 1 if ($v == 1);
55 return 1 if ($v =~ /^t/io);
56 return 1 if ($v =~ /^y/io);
60 sub ou_ancestor_setting_value_or_cache {
61 # cache should be specific to setting
62 my ($e, $org_id, $setting, $cache) = @_;
64 if (not exists $cache->{$org_id}) {
65 my $r = $U->ou_ancestor_setting(
66 $org_id, $setting, $e # undef $e is ok
70 $cache->{$org_id} = $r->{value};
72 $cache->{$org_id} = undef;
75 return $cache->{$org_id};
78 my $parser = DateTime::Format::ISO8601->new;
79 my $log = 'OpenSRF::Utils::Logger';
81 sub open_noncat_circs {
86 my $a = action::non_cataloged_circulation->table;
87 my $c = config::non_cataloged_type->table;
92 JOIN $c c ON (a.item_type = c.id)
93 WHERE a.circ_time + c.circ_duration > current_timestamp
97 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
99 __PACKAGE__->register_method(
100 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
101 method => 'open_noncat_circs',
107 sub ou_hold_requests {
112 my $h_table = action::hold_request->table;
113 my $c_table = asset::copy->table;
114 my $o_table = actor::org_unit->table;
119 JOIN $c_table cp ON (cp.id = h.current_copy)
120 JOIN $o_table ou ON (ou.id = cp.circ_lib)
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
128 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
131 $client->respond($_) for (
134 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
138 } @{ $sth->fetchall_arrayref }
142 __PACKAGE__->register_method(
143 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
147 method => 'ou_hold_requests',
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.
158 my $upper_interval = shift || '1 millennium';
160 my $partition = shift;
161 my $skip_no_fines = shift;
163 # Only retrieve ID's in the initial query if that's all the caller needs.
164 my $contents = $idlist ? 'id' : '*';
166 my $fines_filter = $skip_no_fines ?
167 'AND recurring_fine <> 0 AND max_fine <> 0' : '';
169 my $c_t = action::circulation->table;
174 WHERE stop_fines IS NULL
176 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
177 AND fine_interval < ?::INTERVAL
180 my $sth = action::circulation->db_Main->prepare_cached($sql);
181 $sth->execute($upper_interval);
183 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
185 push (@circs, undef) if $partition;
187 $fines_filter = $skip_no_fines ?
188 'AND fine_amount <> 0 AND max_fine <> 0' : '';
190 $c_t = booking::reservation->table;
194 WHERE return_time IS NULL
196 AND end_time < ( CURRENT_TIMESTAMP )
197 AND fine_interval IS NOT NULL
198 AND cancel_time IS NULL
201 $sth = action::circulation->db_Main->prepare_cached($sql);
204 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
209 sub complete_reshelving {
214 local $OpenILS::Application::Storage::WRITE = 1;
216 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
217 unless (interval_to_seconds( $window ));
219 my $cp = asset::copy->table;
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)
232 my $sth = action::circulation->db_Main->prepare_cached($sql);
233 $sth->execute($window);
238 __PACKAGE__->register_method(
239 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
242 method => 'complete_reshelving',
245 sub mark_longoverdue {
250 local $OpenILS::Application::Storage::WRITE = 1;
252 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
253 unless (interval_to_seconds( $window ));
255 my $setting = actor::org_unit_setting->table;
256 my $circ = action::circulation->table;
260 SET stop_fines = 'LONGOVERDUE',
261 stop_fines_time = now()
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)
272 my $sth = action::circulation->db_Main->prepare_cached($sql);
273 $sth->execute($window);
278 __PACKAGE__->register_method(
279 api_name => 'open-ils.storage.action.circulation.long_overdue',
282 method => 'mark_longoverdue',
285 sub auto_thaw_frozen_holds {
289 local $OpenILS::Application::Storage::WRITE = 1;
291 my $holds = action::hold_request->table;
293 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
295 my $sth = action::hold_request->db_Main->prepare_cached($sql);
301 __PACKAGE__->register_method(
302 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
306 method => 'auto_thaw_frozen_holds',
313 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
315 $client->respond( $idlist ? $_ : $_->to_fieldmapper )
316 for ( overdue_circs('', $idlist, undef, 1) );
321 __PACKAGE__->register_method(
322 api_name => 'open-ils.storage.action.circulation.overdue',
325 method => 'grab_overdue',
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.
333 __PACKAGE__->register_method(
334 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
337 method => 'grab_overdue',
340 sub get_hold_sort_order {
343 my $dbh = action::hold_request->db_Main;
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.
349 my $row = $dbh->selectrow_hashref(
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
357 SELECT oils_json_to_text(value)::INT
358 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
362 pprox => 1, hprox => 8, aprox => 2, priority => 3,
363 cut => 4, depth => 5, htime => 7, rtime => 6
366 # Return only the keys of our hash, sorted by value,
367 # keys for null values omitted.
369 sort { $row->{$a} <=> $row->{$b} } (
370 grep { defined $row->{$_} } keys %$row
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) = @_;
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]
391 foreach my $col (@$columns) {
392 if ($col eq 'htime' and not $ctes_needed) {
394 } elsif ($col eq 'shtime') {
399 @args = @{$order_by_sprintf_args{$col}} if
400 exists $order_by_sprintf_args{$col};
402 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
404 last if $col eq 'rtime'; # rtime is effectively unique, no need for
405 # more order-by clauses after that.
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".
416 if ($ctes_needed == 2) {
418 , last_event_on_copy AS ( -- combined circ and transit version
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
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
442 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
443 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
446 , last_event_on_copy AS ( -- circ only version
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
459 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
460 ) !, $cp->id, $cp->call_number->owning_lib);
464 JOIN last_event_on_copy ON (true)
467 # For our next auxiliary query, the question we seek to answer is,
468 # "has our copy been circulating away from home too long?"
470 # Have there been no checkouts at the copy's circ_lib since the
471 # beginning of our go-home interval?
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.]
479 , copy_has_not_been_home AS (
482 SELECT MIN(circ.id) FROM action.circulation circ
483 JOIN go_home_interval ON (true)
485 circ.target_copy = %d AND
486 circ.circ_lib = %d AND
487 circ.xact_start >= NOW() - go_home_interval.value
489 ) !, $cp->id, $cp->circ_lib);
492 JOIN copy_has_not_been_home ON (true)
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).
501 # There have been no homebound transits that arrived for this copy
502 # since the beginning of the go-home interval.
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
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) ";
520 join(", ", @clauses),
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';
536 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
538 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
539 # are working with a circ lib ID and not an object
541 if (ref $cp->circ_lib) {
542 $cp_circ_lib = $cp->circ_lib->id;
544 $cp_circ_lib = $cp->circ_lib;
548 if (ref $cp->call_number->owning_lib) {
549 $cp_owning_lib = $cp->call_number->owning_lib->id;
551 $cp_owning_lib = $cp->call_number->owning_lib;
554 my ($holdsort, $addl_cte, $addl_join) =
555 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
557 local $OpenILS::Application::Storage::WRITE = 1;
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', ?
565 ))::INTERVAL AS value
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%' )
581 WHERE hm.target_copy = ?
582 /* not protected, or protection is expired or we're in range */
583 AND (cahp.id IS NULL OR (AGE(NOW(),acp.active_date) >= cahp.age OR cahp.prox >= hm.proximity))
584 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
585 AND h.capture_time IS NULL
586 AND h.cancel_time IS NULL
587 AND (h.expire_time IS NULL OR h.expire_time > NOW())
588 AND h.frozen IS FALSE
590 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
594 $client->respond( $_ ) for ( @$ids );
597 __PACKAGE__->register_method(
598 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
601 method => 'nearest_hold',
604 sub targetable_holds {
607 my $check_expire = shift;
609 $check_expire ||= '12h';
611 local $OpenILS::Application::Storage::WRITE = 1;
613 # json_query can *almost* represent this query, but can't
614 # handle the CASE statement or the interval arithmetic
615 my $query = <<" SQL";
616 SELECT ahr.id, mmsm.metarecord
617 FROM action.hold_request ahr
618 JOIN reporter.hold_request_record USING (id)
619 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
620 WHERE capture_time IS NULL
621 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
622 AND fulfillment_time IS NULL
623 AND cancel_time IS NULL
625 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
627 my $sth = action::hold_request->db_Main->prepare_cached($query);
628 $sth->execute($check_expire);
629 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
634 __PACKAGE__->register_method(
635 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
638 method => 'targetable_holds',
640 Returns ordered list of hold request and metarecord IDs
641 for all hold requests that are available for initial targeting
643 @param check interval
644 @return list of pairs of hold request and metarecord IDs
648 sub next_resp_group_id {
652 # XXX This is not replication safe!!!
654 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
655 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
659 __PACKAGE__->register_method(
660 api_name => 'open-ils.storage.action.survey_response.next_group_id',
662 method => 'next_resp_group_id',
665 sub patron_circ_summary {
670 return undef unless ($id);
671 my $c_table = action::circulation->table;
672 my $b_table = money::billing->table;
674 $log->debug("Retrieving patron summary for id $id", DEBUG);
676 my $select = <<" SQL";
677 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
679 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
681 AND c.xact_finish IS NULL
683 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
684 OR c.stop_fines IS NULL
688 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
690 __PACKAGE__->register_method(
691 api_name => 'open-ils.storage.action.circulation.patron_summary',
693 method => 'patron_circ_summary',
696 #XXX Fix stored proc calls
697 sub find_local_surveys {
702 return undef unless ($ou);
703 my $s_table = action::survey->table;
705 my $select = <<" SQL";
708 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
709 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
712 my $sth = action::survey->db_Main->prepare_cached($select);
715 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
719 __PACKAGE__->register_method(
720 api_name => 'open-ils.storage.action.survey.all',
723 method => 'find_local_surveys',
726 #XXX Fix stored proc calls
727 sub find_opac_surveys {
732 return undef unless ($ou);
733 my $s_table = action::survey->table;
735 my $select = <<" SQL";
738 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
739 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
743 my $sth = action::survey->db_Main->prepare_cached($select);
746 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
750 __PACKAGE__->register_method(
751 api_name => 'open-ils.storage.action.survey.opac',
754 method => 'find_opac_surveys',
761 my $limit = shift || 10;
762 my $offset = shift || 0;
764 return undef unless ($ou);
765 my $h_table = action::hold_request->table;
766 my $a_table = asset::copy->table;
767 my $ord_table = asset::copy_location_order->table;
769 my $idlist = 1 if ($self->api_name =~/id_list/o);
770 my $count = 1 if ($self->api_name =~/count$/o);
772 my $status_filter = '';
773 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
775 my $select = <<" SQL";
778 JOIN $a_table a ON (h.current_copy = a.id)
779 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
781 AND h.capture_time IS NULL
782 AND h.cancel_time IS NULL
783 AND (h.expire_time IS NULL OR h.expire_time > NOW())
786 FROM actor.usr_standing_penalty ausp
787 JOIN config.standing_penalty csp ON (
788 csp.id = ausp.standing_penalty
789 AND csp.block_list LIKE '%CAPTURE%'
791 WHERE h.usr = ausp.usr
792 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
795 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
802 SELECT count(DISTINCT h.id)
804 JOIN $a_table a ON (h.current_copy = a.id)
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())
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%'
816 WHERE h.usr = ausp.usr
817 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
823 my $sth = action::survey->db_Main->prepare_cached($select);
827 $client->respond( $sth->fetchall_arrayref()->[0][0] );
829 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
831 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
836 __PACKAGE__->register_method(
837 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
841 "Returns a count of holds for a specific library's pull list.",
842 [ [org_unit => "The library's org id", "number"] ],
843 ['A count of holds for the stated library to pull ', 'number']
845 method => 'hold_pull_list',
847 __PACKAGE__->register_method(
848 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
852 "Returns a status filtered count of holds for a specific library's pull list.",
853 [ [org_unit => "The library's org id", "number"] ],
854 ['A status filtered count of holds for the stated library to pull ', 'number']
856 method => 'hold_pull_list',
858 __PACKAGE__->register_method(
859 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
863 "Returns the hold ids for a specific library's pull list.",
864 [ [org_unit => "The library's org id", "number"],
865 [limit => 'An optional page size, defaults to 10', 'number'],
866 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
868 ['A list of holds for the stated library to pull for', 'array']
870 method => 'hold_pull_list',
872 __PACKAGE__->register_method(
873 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
877 "Returns the holds for a specific library's pull list.",
878 [ [org_unit => "The library's org id", "number"],
879 [limit => 'An optional page size, defaults to 10', 'number'],
880 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
882 ['A list of holds for the stated library to pull for', 'array']
884 method => 'hold_pull_list',
886 __PACKAGE__->register_method(
887 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
891 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
892 [ [org_unit => "The library's org id", "number"],
893 [limit => 'An optional page size, defaults to 10', 'number'],
894 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
896 ['A list of holds for the stated library to pull for', 'array']
898 method => 'hold_pull_list',
900 __PACKAGE__->register_method(
901 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
905 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
906 [ [org_unit => "The library's org id", "number"],
907 [limit => 'An optional page size, defaults to 10', 'number'],
908 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
910 ['A list of holds for the stated library to pull for', 'array']
912 method => 'hold_pull_list',
915 sub find_optional_surveys {
920 return undef unless ($ou);
921 my $s_table = action::survey->table;
923 my $select = <<" SQL";
926 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
927 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
928 AND s.required IS FALSE;
931 my $sth = action::survey->db_Main->prepare_cached($select);
934 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
938 __PACKAGE__->register_method(
939 api_name => 'open-ils.storage.action.survey.optional',
942 method => 'find_optional_surveys',
945 sub find_required_surveys {
950 return undef unless ($ou);
951 my $s_table = action::survey->table;
953 my $select = <<" SQL";
956 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
957 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
958 AND s.required IS TRUE;
961 my $sth = action::survey->db_Main->prepare_cached($select);
964 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
968 __PACKAGE__->register_method(
969 api_name => 'open-ils.storage.action.survey.required',
972 method => 'find_required_surveys',
975 sub find_usr_summary_surveys {
980 return undef unless ($ou);
981 my $s_table = action::survey->table;
983 my $select = <<" SQL";
986 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
987 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
988 AND s.usr_summary IS TRUE;
991 my $sth = action::survey->db_Main->prepare_cached($select);
994 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
998 __PACKAGE__->register_method(
999 api_name => 'open-ils.storage.action.survey.usr_summary',
1002 method => 'find_usr_summary_surveys',
1005 sub generate_fines {
1008 my $circ_id = shift;
1011 my $editor = new_editor;
1013 $circs = $editor->search_action_circulation( { id => $circ_id, stop_fines => undef } );
1015 $circs = $editor->search_booking_reservation( { id => $circ_id, return_time => undef, cancel_time => undef } );
1018 $circs = [overdue_circs(undef, 1, 1, 1)];
1021 return OpenILS::Application::Circ::CircCommon->generate_fines({circs => $circs, conn => $client})
1023 __PACKAGE__->register_method(
1024 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1027 method => 'generate_fines',
1031 sub MR_records_matching_format {
1037 # include all visible copies, regardless of holdability
1038 my $opac_visible = shift;
1040 # find filters for MR holds
1042 if (defined($filter)) {
1043 ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1044 'SELECT metabib.compile_composite_attr(?)',
1050 my $records = [metabib::metarecord->retrieve($MR)->source_records];
1052 my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1053 if ($opac_visible) {
1057 FROM asset.patron_default_visibility_mask() mask,
1058 asset.copy_vis_attr_cache v
1059 JOIN asset.copy c ON (
1060 c.id = v.target_copy
1063 SELECT id FROM actor.org_unit_descendants(?)
1066 WHERE v.vis_attr_vector @@ mask.c_attrs::query_int
1071 my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1072 my @args = ( $mr_filter, $org );
1074 $q = "SELECT true WHERE $vis_q";
1078 for my $r ( map { isTrue($_->deleted) ? () : ($_->id) } @$records ) {
1079 # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1080 $client->respond($r)
1081 if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1084 return; # discard final l-val
1086 __PACKAGE__->register_method(
1087 api_name => 'open-ils.storage.metarecord.filtered_records',
1091 method => 'MR_records_matching_format',
1095 sub new_hold_copy_targeter {
1098 my $check_expire = shift;
1099 my $one_hold = shift;
1100 my $find_copy = shift;
1102 local $OpenILS::Application::Storage::WRITE = 1;
1104 $self->{target_weight} = {};
1105 $self->{max_loops} = {};
1111 $self->method_lookup('open-ils.storage.transaction.begin')->run();
1112 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1113 } elsif ( $check_expire ) {
1115 # what's the retarget time threashold?
1117 $check_expire ||= '12h';
1118 $check_expire = interval_to_seconds( $check_expire );
1120 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1123 my $expire_threshold = sprintf(
1124 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1125 $year, $mon, $mday, $hour, $min, $sec
1128 # find all the holds holds needing retargeting
1129 $holds = [ action::hold_request->search_where(
1130 { capture_time => undef,
1131 fulfillment_time => undef,
1132 cancel_time => undef,
1134 prev_check_time => { '<=' => $expire_threshold },
1136 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1138 # find all the holds holds needing first time targeting
1139 push @$holds, action::hold_request->search(
1140 capture_time => undef,
1141 fulfillment_time => undef,
1142 prev_check_time => undef,
1144 cancel_time => undef,
1145 { order_by => 'selection_depth DESC, request_time' } );
1148 # find all the holds holds needing first time targeting ONLY
1149 $holds = [ action::hold_request->search(
1150 capture_time => undef,
1151 fulfillment_time => undef,
1152 prev_check_time => undef,
1153 cancel_time => undef,
1155 { order_by => 'selection_depth DESC, request_time' } ) ];
1157 } catch Error with {
1159 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1162 my @closed = actor::org_unit::closed_date->search_where(
1163 { close_start => { '<=', 'now' },
1164 close_end => { '>=', 'now' } }
1167 if ($check_expire) {
1169 # $check_expire, if it exists, was already converted to seconds
1170 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1174 my $next_check_time = sprintf(
1175 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1176 $year, $mon, $mday, $hour, $min, $sec
1180 my @closed_at_next = actor::org_unit::closed_date->search_where(
1181 { close_start => { '<=', $next_check_time },
1182 close_end => { '>=', $next_check_time } }
1186 for my $c_at_n (@closed_at_next) {
1187 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1188 push @new_closed, $c_at_n;
1191 @closed = @new_closed;
1195 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1196 my $editor = new_editor;
1198 my $target_when_closed = {};
1199 my $target_when_closed_if_at_pickup_lib = {};
1201 for my $hold (@$holds) {
1203 #start a transaction if needed
1204 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1205 $log->debug("Cleaning up after previous transaction\n");
1206 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1208 $self->method_lookup('open-ils.storage.transaction.begin')->run();
1209 $log->info("Processing hold ".$hold->id."...\n");
1211 #first, re-fetch the hold, to make sure it's not captured already
1212 $hold->remove_from_object_index();
1213 $hold = action::hold_request->retrieve( $hold->id );
1215 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1217 # remove old auto-targeting maps
1218 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1219 $_->delete for (@oldmaps);
1221 if ($hold->expire_time) {
1222 my $ex_time = $parser->parse_datetime( clean_ISO8601( $hold->expire_time ) );
1223 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1225 # cancel cause = un-targeted expiration
1226 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1228 # refresh fields from the DB while still in the xact
1229 my $fm_hold = $hold->to_fieldmapper;
1231 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1233 # tell A/T the hold was cancelled
1234 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1235 $ses->request('open-ils.trigger.event.autocreate',
1236 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1242 my $all_copies = [];
1244 # find all the potential copies
1245 if ($hold->hold_type eq 'M') {
1247 $self->method_lookup(
1248 'open-ils.storage.metarecord.filtered_records'
1249 )->run( $hold->target, $hold->holdable_formats )
1252 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1253 ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1255 for my $cn ( @{ $rtree->call_numbers } ) {
1257 asset::copy->search_where(
1258 { id => [map {$_->id} @{ $cn->copies }],
1260 ) if ($cn && @{ $cn->copies });
1263 } elsif ($hold->hold_type eq 'T') {
1265 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1266 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1269 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1273 for my $cn ( @{ $rtree->call_numbers } ) {
1275 asset::copy->search_where(
1276 { id => [map {$_->id} @{ $cn->copies }],
1278 ) if ($cn && @{ $cn->copies });
1280 } elsif ($hold->hold_type eq 'V') {
1282 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1283 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1286 asset::copy->search_where(
1287 { id => [map {$_->id} @{ $vtree->copies }],
1289 ) if ($vtree && @{ $vtree->copies });
1291 } elsif ($hold->hold_type eq 'P') {
1292 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1294 asset::copy->search_where(
1295 { id => [map {$_->target_copy} @part_maps],
1300 } elsif ($hold->hold_type eq 'I') {
1302 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1303 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1306 asset::copy->search_where(
1307 { id => [map {$_->unit->id} @{ $itree->items }],
1309 ) if ($itree && @{ $itree->items });
1311 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1312 my $_cp = asset::copy->retrieve($hold->target);
1313 push @$all_copies, $_cp if $_cp;
1316 # Force and recall holds bypass pretty much everything
1317 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1319 @$all_copies = grep { isTrue($_->status->holdable) &&
1320 isTrue($_->location->holdable) &&
1321 isTrue($_->holdable) &&
1322 !isTrue($_->deleted) &&
1323 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1324 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1325 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1329 # let 'em know we're still working
1330 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1332 # if we have no copies ...
1333 if (!ref $all_copies || !@$all_copies) {
1334 $log->info("\tNo copies available for targeting at all!\n");
1335 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1337 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1338 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1342 my $copy_count = @$all_copies;
1343 my $found_copy = undef;
1344 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1346 # map the potentials, so that we can pick up checkins
1347 my $hold_copy_map = {};
1348 $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1351 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1355 my $pu_lib = ''.$hold->pickup_lib;
1356 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1357 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1359 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1362 for my $c (@$all_copies) {
1364 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1366 # skip on circ lib is closed IFF we care
1369 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1370 $ignore_closing = ou_ancestor_setting_value_or_cache(
1373 'circ.holds.target_when_closed_if_at_pickup_lib',
1374 $target_when_closed_if_at_pickup_lib
1377 if (not $ignore_closing) { # one more chance to find a reason
1378 # to ignore OU closedness.
1379 $ignore_closing = ou_ancestor_setting_value_or_cache(
1382 'circ.holds.target_when_closed',
1388 # "For hold " . $hold->id . " and copy with circ_lib " .
1389 # $c->circ_lib . " we " .
1390 # ($ignore_closing ? "ignore" : "respect")
1395 (not $ignore_closing) and
1396 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1399 # target of another hold
1400 next if (action::hold_request
1402 { current_copy => $c->id,
1403 fulfillment_time => undef,
1404 cancel_time => undef,
1409 # we passed all three, keep it
1410 push @good_copies, $c if ($c);
1411 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1414 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1416 my $old_best = $hold->current_copy;
1417 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1418 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1419 $hold->update({ current_copy => undef }) if ($old_best);
1421 if (!scalar(@good_copies)) {
1422 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1423 if ( $old_best_still_valid ) {
1424 # the old copy is still available
1425 $log->debug("\tPushing current_copy back onto the targeting list");
1426 push @good_copies, $old_best;
1428 # oops, old copy is not available
1429 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1430 $hold->update( { prev_check_time => 'today' } );
1431 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1432 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1437 # reset prox list after trimming good copies
1438 $prox_list = create_prox_list(
1440 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1441 $hold, $hold_copy_map
1444 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1446 my $min_prox = [ sort {$a<=>$b} keys %$prox_list ]->[0];
1448 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1449 $best = $good_copies[0] if(scalar @good_copies);
1450 } elsif (defined $min_prox) {
1451 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1454 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1457 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1459 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1460 $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1463 if (defined($self->{max_loops}{$pu_lib})) {
1464 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1466 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1467 my $circ_lib_list = [keys %circ_lib_map];
1469 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1471 # Grab the "biggest" loop for this hold so far
1472 my $current_loop = $cstore->request(
1473 'open-ils.cstore.json_query',
1475 select => { aufhmxl => ['max'] },
1477 where => { hold => $hold->id}
1481 $current_loop = $current_loop->{max} if ($current_loop);
1482 $current_loop ||= 1;
1484 my $exclude_list = $cstore->request(
1485 'open-ils.cstore.json_query.atomic',
1487 select => { aufhol => ['circ_lib'] },
1489 where => { hold => $hold->id}
1494 if ($exclude_list && @$exclude_list) {
1495 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1496 # check to see if we've used up every library in the potentials list
1497 for my $l ( @$circ_lib_list ) {
1499 for my $ex ( @$exclude_list ) {
1505 push(@keepers, $l) if ($keep);
1508 @keepers = @$circ_lib_list;
1511 $current_loop++ if (!@keepers);
1513 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1514 # We haven't exceeded max_loops yet
1516 for my $cp ( @$all_copies ) {
1517 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1520 $all_copies = [@keeper_copies];
1522 # We have, and should remove potentials and cancel the hold
1523 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1524 $_->delete for (@oldmaps);
1526 # cancel cause = un-targeted expiration
1527 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1529 # refresh fields from the DB while still in the xact
1530 my $fm_hold = $hold->to_fieldmapper;
1532 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1534 # tell A/T the hold was cancelled
1535 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1536 $ses->request('open-ils.trigger.event.autocreate',
1537 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1542 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1544 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1548 $best = choose_nearest_copy($hold, $prox_list);
1551 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1553 # hold wasn't fulfilled, record the fact
1555 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1556 action::unfulfilled_hold_list->create(
1557 { hold => ''.$hold->id,
1558 current_copy => ''.$old_best->id,
1559 circ_lib => ''.$old_best->circ_lib,
1564 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1565 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1567 $old_best_still_valid &&
1568 !action::hold_request
1570 { current_copy => $old_best->id,
1571 fulfillment_time => undef,
1572 cancel_time => undef,
1575 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1576 { title => $old_best->call_number->record->to_fieldmapper,
1577 patron => $hold->usr->to_fieldmapper,
1578 copy => $old_best->to_fieldmapper,
1579 requestor => $hold->requestor->to_fieldmapper,
1580 request_lib => $hold->request_lib->to_fieldmapper,
1581 pickup_lib => $hold->pickup_lib->id,
1586 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1587 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1589 $hold->update( { prev_check_time => 'now' } );
1590 $log->info( "\tThere were no targetable copies for the hold" );
1591 process_recall($actor, $log, $hold, \@good_copies);
1594 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1595 $log->info("\tProcessing of hold ".$hold->id." complete.");
1598 { hold => $hold->id,
1599 old_target => ($old_best ? $old_best->id : undef),
1600 eligible_copies => $copy_count,
1601 target => ($best ? $best->id : undef),
1602 found_copy => $found_copy };
1607 $log->error("Processing of hold failed: $e");
1608 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1609 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1616 __PACKAGE__->register_method(
1617 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1619 method => 'new_hold_copy_targeter',
1622 sub process_recall {
1623 my ($actor, $log, $hold, $good_copies) = @_;
1625 # Bail early if we don't have required settings to avoid spurious requests
1626 my ($recall_threshold, $return_interval, $fine_rules);
1628 my $rv = $actor->request(
1629 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1633 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1636 $recall_threshold = $rv->{value};
1638 $rv = $actor->request(
1639 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1643 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1646 $return_interval = $rv->{value};
1648 $rv = $actor->request(
1649 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1653 $fine_rules = $rv->{value};
1656 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1658 # We want checked out copies (status = 1) at the hold pickup lib
1659 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1661 my @copy_ids = map { $_->id } @$all_copies;
1663 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1665 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval));
1667 # Iterate over the checked-out copies to find a copy with a
1668 # loan period longer than the recall threshold:
1669 my $circs = [ action::circulation->search_where(
1670 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1671 { order_by => 'due_date ASC' }
1674 # If we have a candidate copy, then:
1675 if (scalar(@$circs)) {
1676 my $circ = $circs->[0];
1677 $log->info("Recalling circ ID : " . $circ->id);
1679 my $old_due_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($circ->due_date));
1681 # Give the user a new due date of either a full recall threshold,
1682 # or the return interval, whichever is further in the future
1683 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold));
1684 if (DateTime->compare($threshold_date, $return_date) == 1) {
1685 # extend $return_date to threshold
1686 $return_date = $threshold_date;
1688 # But don't go past the original due date
1689 # (the threshold should not be past the due date, but manual edits can cause it to be)
1690 if (DateTime->compare($return_date, $old_due_date) == 1) {
1691 # truncate $return_date to due date
1692 $return_date = $old_due_date;
1695 my $update_fields = {
1696 due_date => $return_date->iso8601(),
1697 renewal_remaining => 0,
1700 # If the OU hasn't defined new fine rules for recalls, keep them
1703 $log->info("Apply recall fine rules: $fine_rules");
1704 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1705 $update_fields->{recurring_fine} = $rules->[0];
1706 $update_fields->{fine_interval} = $rules->[1];
1707 $update_fields->{max_fine} = $rules->[2];
1710 # Adjust circ for current user
1711 $circ->update($update_fields);
1713 # Create trigger event for notifying current user
1714 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1715 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1718 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1721 sub reservation_targeter {
1724 my $one_reservation = shift;
1726 local $OpenILS::Application::Storage::WRITE = 1;
1731 if ($one_reservation) {
1732 $self->method_lookup('open-ils.storage.transaction.begin')->run();
1733 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1736 # find all the reservations needing targeting
1738 booking::reservation->search_where(
1739 { current_resource => undef,
1740 cancel_time => undef,
1741 start_time => { '>' => 'now' }
1743 { order_by => 'start_time' }
1747 } catch Error with {
1749 die "Could not retrieve reservation requests:\n\n$e\n";
1753 for my $bresv (@$reservations) {
1755 #start a transaction if needed
1756 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1757 $log->debug("Cleaning up after previous transaction\n");
1758 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1760 $self->method_lookup('open-ils.storage.transaction.begin')->run();
1761 $log->info("Processing reservation ".$bresv->id."...\n");
1763 #first, re-fetch the hold, to make sure it's not captured already
1764 $bresv->remove_from_object_index();
1765 $bresv = booking::reservation->retrieve( $bresv->id );
1767 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1769 my $end_time = $parser->parse_datetime( clean_ISO8601( $bresv->end_time ) );
1770 if (DateTime->compare($end_time, DateTime->now) < 0) {
1772 # cancel cause = un-targeted expiration
1773 $bresv->update( { cancel_time => 'now' } );
1775 # refresh fields from the DB while still in the xact
1776 my $fm_bresv = $bresv->to_fieldmapper;
1778 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1780 # tell A/T the reservation was cancelled
1781 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1782 $ses->request('open-ils.trigger.event.autocreate',
1783 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1788 my $possible_resources;
1790 # find all the potential resources
1791 if (!$bresv->target_resource) {
1792 my $filter = { type => $bresv->target_resource_type };
1793 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1795 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1797 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1798 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1799 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1801 $possible_resources = $bresv->target_resource;
1804 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1805 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1808 my @good_resources = ();
1810 for my $res (@$all_resources) {
1811 unless (isTrue($res->type->catalog_item)) {
1812 push @good_resources, $res;
1816 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1819 push @good_resources, $res;
1823 # At this point, if we're just targeting one specific
1824 # resource, just succeed. We don't care about its present
1826 if ($bresv->target_resource) {
1827 push @good_resources, $res;
1831 if ($copy->status->id == 0 || $copy->status->id == 7) {
1832 push @good_resources, $res;
1836 if ($copy->status->id == 1) {
1837 my $circs = [ action::circulation->search_where(
1838 {target_copy => $copy->id, checkin_time => undef },
1839 { order_by => 'id DESC' }
1843 my $due_date = $circs->[0]->due_date;
1844 $due_date = $parser->parse_datetime( clean_ISO8601( $due_date ) );
1845 my $start_time = $parser->parse_datetime( clean_ISO8601( $bresv->start_time ) );
1846 if (DateTime->compare($start_time, $due_date) < 0) {
1847 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1851 push @good_resources, $res;
1857 push @good_resources, $res if (isTrue($copy->status->holdable));
1860 # let 'em know we're still working
1861 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1863 # if we have no copies ...
1864 if (!@good_resources) {
1865 $log->info("\tNo resources available for targeting at all!\n");
1866 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1869 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1873 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1875 # LFW: note that after the inclusion of hold proximity
1876 # adjustment, this prox_list is the only prox_list
1877 # array in this perl package. Other occurences are
1883 $_->owner == $bresv->pickup_lib
1887 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1888 # $all_copies is now a list of copies not at the pickup library
1890 my $best = shift @good_resources;
1891 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1894 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1898 sort { $a->[0] <=> $b->[0] }
1900 [ actor::org_unit_proximity->search_where(
1901 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1907 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1909 $best = shift @$prox_list
1913 $bresv->update( { current_resource => ''.$best->id } );
1914 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1917 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1918 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1921 { reservation => $bresv->id,
1922 current_resource => ($best ? $best->id : undef) };
1927 $log->error("Processing of bresv failed: $e");
1928 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1929 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1936 __PACKAGE__->register_method(
1937 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1939 method => 'reservation_targeter',
1944 my %cache = (titles => {}, cns => {});
1946 sub copy_hold_capture {
1951 if (!defined($cps)) {
1953 $cps = [ asset::copy->search( id => $hold->target ) ];
1954 } catch Error with {
1956 die "Could not retrieve initial volume list:\n\n$e\n";
1960 my @copies = grep { $_->holdable } @$cps;
1962 for (my $i = 0; $i < @$cps; $i++) {
1963 next unless $$cps[$i];
1965 my $cn = $cache{cns}{$copies[$i]->call_number};
1966 my $rec = $cache{titles}{$cn->record};
1967 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1968 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1969 $copies[$i] = undef if (
1971 !$self->{user_filter}->request(
1972 'open-ils.circ.permit_hold',
1973 $hold->to_fieldmapper, do {
1974 my $cp_fm = $copies[$i]->to_fieldmapper;
1975 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1976 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1977 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1980 { title => $rec->to_fieldmapper,
1981 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1982 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1985 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1988 @copies = grep { $_ } @copies;
1990 my $count = @copies;
1992 return unless ($count);
1994 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1997 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1998 for my $c (@copies) {
1999 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2001 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2007 sub choose_nearest_copy {
2009 my $prox_list = shift;
2011 for my $p ( sort {$a<=>$b} keys %$prox_list ) {
2012 next unless (ref $$prox_list{$p});
2014 my @capturable = @{ $$prox_list{$p} };
2015 next unless (@capturable);
2017 my $rand = int(rand(scalar(@capturable)));
2019 while (my ($c) = splice(@capturable, $rand, 1)) {
2020 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2021 { title => $c->call_number->record->to_fieldmapper,
2022 patron => $hold->usr->to_fieldmapper,
2023 copy => $c->to_fieldmapper,
2024 requestor => $hold->requestor->to_fieldmapper,
2025 request_lib => $hold->request_lib->to_fieldmapper,
2026 pickup_lib => $hold->pickup_lib->id,
2032 last unless(@capturable);
2033 $rand = int(rand(scalar(@capturable)));
2038 sub create_prox_list {
2043 my $hold_copy_map = shift || {};
2046 my $editor = new_editor;
2047 for my $cp (@$copies) {
2048 my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2049 ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2050 next unless (defined($prox));
2052 my $copy_circ_lib = ''.$cp->circ_lib;
2053 # Fetch the weighting value for hold targeting, defaulting to 1
2054 $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2055 $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2057 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2058 $self->{target_weight}{$copy_circ_lib} ||= 1;
2060 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2061 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2062 push @{$prox_list{$prox}}, $cp;
2068 sub volume_hold_capture {
2073 if (!defined($vols)) {
2075 $vols = [ asset::call_number->search( id => $hold->target ) ];
2076 $cache{cns}{$_->id} = $_ for (@$vols);
2077 } catch Error with {
2079 die "Could not retrieve initial volume list:\n\n$e\n";
2083 my @v_ids = map { $_->id } @$vols;
2087 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2089 } catch Error with {
2091 warn "Could not retrieve copy list:\n\n$e\n";
2094 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2097 sub title_hold_capture {
2102 if (!defined($titles)) {
2104 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2105 $cache{titles}{$_->id} = $_ for (@$titles);
2106 } catch Error with {
2108 die "Could not retrieve initial title list:\n\n$e\n";
2112 my @t_ids = map { $_->id } @$titles;
2115 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2117 } catch Error with {
2119 warn "Could not retrieve volume list:\n\n$e\n";
2122 $cache{cns}{$_->id} = $_ for (@$cn_list);
2124 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2128 sub wide_hold_data {
2131 my $restrictions = shift; # hashref of field restrictions {f1=>undef,f2=>[1,2,3],f3=>'foo',f4=>{not=>undef}}
2132 my $order_by = shift; # arrayref of hashrefs of ORDER BY clause, [{field =>{dir=>'desc',nulls=>'last'}}]
2136 $order_by = [$order_by] if (ref($order_by) !~ /ARRAY/);
2138 $log->info('Received '. keys(%$restrictions) .' restrictions');
2139 return 0 unless (ref $restrictions and keys %$restrictions);
2141 # force this to either 'true' or 'false'
2142 my $is_staff_request = delete($$restrictions{is_staff_request}) || 'false';
2143 $is_staff_request = 'false' if (!grep {$is_staff_request eq $_} qw/true false/);
2145 # option to filter for the latest captured hold for a given copy
2146 my $last_captured_hold = delete($$restrictions{last_captured_hold}) || 'false';
2147 $last_captured_hold = $last_captured_hold eq 'true' ? 1 : 0;
2149 # option to filter for hopeless holds by date range
2150 my $hopeless_holds = delete($$restrictions{hopeless_holds}) || 'false';
2152 my $initial_condition = 'TRUE';
2153 if ($last_captured_hold) {
2154 $initial_condition = <<" SQL";
2155 (h.capture_time IS NULL OR (h.id = (
2157 FROM action.hold_request recheck
2158 WHERE recheck.current_copy = cp.id
2159 AND recheck.capture_time IS NOT NULL
2160 ORDER BY capture_time DESC
2166 if (ref($hopeless_holds) =~ /HASH/ && $$hopeless_holds{start_date} && $$hopeless_holds{end_date}) {
2167 my $start_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($$hopeless_holds{start_date}));
2168 my $end_date = DateTime::Format::ISO8601->parse_datetime(clean_ISO8601($$hopeless_holds{end_date}));
2169 my $hopeless_condition = "(frozen IS FALSE AND h.hopeless_date >= '$start_date' AND h.hopeless_date <= '$end_date')";
2170 $initial_condition .= " AND $hopeless_condition";
2173 my $select = <<" SQL";
2175 t_field AS (SELECT field FROM config.display_field_map WHERE name = 'title'),
2176 a_field AS (SELECT field FROM config.display_field_map WHERE name = 'author')
2177 SELECT h.id, h.request_time, h.capture_time, h.fulfillment_time, h.checkin_time,
2178 h.return_time, h.prev_check_time, h.expire_time, h.cancel_time, h.cancel_cause,
2179 h.cancel_note, h.target, h.current_copy, h.fulfillment_staff, h.fulfillment_lib,
2180 h.request_lib, h.requestor, h.usr, h.selection_ou, h.selection_depth, h.pickup_lib,
2181 h.hold_type, h.holdable_formats, h.phone_notify, h.email_notify, h.sms_notify,
2182 (SELECT name FROM config.sms_carrier WHERE id = h.sms_carrier) AS "sms_carrier",
2183 h.frozen, h.thaw_date, h.shelf_time, h.cut_in_line, h.mint_condition,
2184 h.shelf_expire_time, h.current_shelf_lib, h.behind_desk, h.hopeless_date,
2186 CASE WHEN h.cancel_time IS NOT NULL THEN 6
2187 WHEN h.frozen AND h.capture_time IS NULL THEN 7
2188 WHEN h.current_shelf_lib IS NOT NULL AND h.current_shelf_lib <> h.pickup_lib THEN 8
2189 WHEN h.fulfillment_time IS NOT NULL THEN 9
2190 WHEN h.current_copy IS NULL THEN 1
2191 WHEN h.capture_time IS NULL THEN 2
2192 WHEN cp.status = 6 THEN 3
2193 WHEN EXTRACT(EPOCH FROM COALESCE(NULLIF(BTRIM(hold_wait_time.value,'"'),''),'0 seconds')::INTERVAL) = 0 THEN 4
2194 WHEN h.shelf_time + COALESCE(NULLIF(BTRIM(hold_wait_time.value,'"'),''),'0 seconds')::INTERVAL > NOW() THEN 5
2198 (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,
2200 (h.usr <> h.requestor) AS is_staff_hold,
2202 cc.id AS cc_id, cc.label AS cc_label,
2204 pl.id AS pl_id, pl.parent_ou AS pl_parent_ou, pl.ou_type AS pl_ou_type,
2205 pl.ill_address AS pl_ill_address, pl.holds_address AS pl_holds_address,
2206 pl.mailing_address AS pl_mailing_address, pl.billing_address AS pl_billing_address,
2207 pl.shortname AS pl_shortname, pl.name AS pl_name, pl.email AS pl_email,
2208 pl.phone AS pl_phone, pl.opac_visible AS pl_opac_visible, pl.fiscal_calendar AS pl_fiscal_calendar,
2210 tr.id AS tr_id, tr.source_send_time AS tr_source_send_time, tr.dest_recv_time AS tr_dest_recv_time,
2211 tr.target_copy AS tr_target_copy, tr.source AS tr_source, tr.dest AS tr_dest, tr.prev_hop AS tr_prev_hop,
2212 tr.copy_status AS tr_copy_status, tr.persistant_transfer AS tr_persistant_transfer,
2213 tr.prev_dest AS tr_prev_dest, tr.hold AS tr_hold, tr.cancel_time AS tr_cancel_time,
2215 notes.count AS note_count,
2217 u.id AS usr_id, u.card AS usr_card, u.profile AS usr_profile, u.usrname AS usr_usrname,
2218 u.email AS usr_email, u.standing AS usr_standing, u.ident_type AS usr_ident_type,
2219 u.ident_value AS usr_ident_value, u.ident_type2 AS usr_ident_type2,
2220 u.ident_value2 AS usr_ident_value2, u.net_access_level AS usr_net_access_level,
2221 u.photo_url AS usr_photo_url, u.prefix AS usr_prefix, u.first_given_name AS usr_first_given_name,
2222 u.second_given_name AS usr_second_given_name, u.family_name AS usr_family_name,
2223 u.suffix AS usr_suffix, u.alias AS usr_alias, u.day_phone AS usr_day_phone,
2224 u.evening_phone AS usr_evening_phone, u.other_phone AS usr_other_phone,
2225 u.mailing_address AS usr_mailing_address, u.billing_address AS usr_billing_address,
2226 u.home_ou AS usr_home_ou, u.dob AS usr_dob, u.active AS usr_active,
2227 u.master_account AS usr_master_account, u.super_user AS usr_super_user,
2228 u.barred AS usr_barred, u.deleted AS usr_deleted, u.juvenile AS usr_juvenile,
2229 u.usrgroup AS usr_usrgroup, u.claims_returned_count AS usr_claims_returned_count,
2230 u.credit_forward_balance AS usr_credit_forward_balance, u.last_xact_id AS usr_last_xact_id,
2231 u.alert_message AS usr_alert_message, u.create_date AS usr_create_date,
2232 u.expire_date AS usr_expire_date, u.claims_never_checked_out_count AS usr_claims_never_checked_out_count,
2233 u.last_update_time AS usr_last_update_time,
2235 CASE WHEN u.alias IS NOT NULL THEN
2239 END AS usr_alias_or_first_given_name,
2241 CASE WHEN u.alias IS NOT NULL THEN
2244 REGEXP_REPLACE(ARRAY_TO_STRING(ARRAY[
2245 COALESCE(u.family_name, ''),
2246 COALESCE(u.suffix, ''),
2248 COALESCE(u.prefix, ''),
2249 COALESCE(u.first_given_name, ''),
2250 COALESCE(u.second_given_name, '')
2251 ], ' '), E'\\s+,', ',')
2252 END AS usr_alias_or_display_name,
2254 REGEXP_REPLACE(ARRAY_TO_STRING(ARRAY[
2255 COALESCE(u.family_name, ''),
2256 COALESCE(u.suffix, ''),
2258 COALESCE(u.prefix, ''),
2259 COALESCE(u.first_given_name, ''),
2260 COALESCE(u.second_given_name, '')
2261 ], ' '), E'\\s+,', ',') AS usr_display_name,
2263 uc.id AS ucard_id, uc.barcode AS ucard_barcode, uc.usr AS ucard_usr, uc.active AS ucard_active,
2265 ru.id AS rusr_id, ru.card AS rusr_card, ru.profile AS rusr_profile, ru.usrname AS rusr_usrname,
2266 ru.email AS rusr_email, ru.standing AS rusr_standing, ru.ident_type AS rusr_ident_type,
2267 ru.ident_value AS rusr_ident_value, ru.ident_type2 AS rusr_ident_type2,
2268 ru.ident_value2 AS rusr_ident_value2, ru.net_access_level AS rusr_net_access_level,
2269 ru.photo_url AS rusr_photo_url, ru.prefix AS rusr_prefix, ru.first_given_name AS rusr_first_given_name,
2270 ru.second_given_name AS rusr_second_given_name, ru.family_name AS rusr_family_name,
2271 ru.suffix AS rusr_suffix, ru.alias AS rusr_alias, ru.day_phone AS rusr_day_phone,
2272 ru.evening_phone AS rusr_evening_phone, ru.other_phone AS rusr_other_phone,
2273 ru.mailing_address AS rusr_mailing_address, ru.billing_address AS rusr_billing_address,
2274 ru.home_ou AS rusr_home_ou, ru.dob AS rusr_dob, ru.active AS rusr_active,
2275 ru.master_account AS rusr_master_account, ru.super_user AS rusr_super_user,
2276 ru.barred AS rusr_barred, ru.deleted AS rusr_deleted, ru.juvenile AS rusr_juvenile,
2277 ru.usrgroup AS rusr_usrgroup, ru.claims_returned_count AS rusr_claims_returned_count,
2278 ru.credit_forward_balance AS rusr_credit_forward_balance, ru.last_xact_id AS rusr_last_xact_id,
2279 ru.alert_message AS rusr_alert_message, ru.create_date AS rusr_create_date,
2280 ru.expire_date AS rusr_expire_date, ru.claims_never_checked_out_count AS rusr_claims_never_checked_out_count,
2281 ru.last_update_time AS rusr_last_update_time,
2283 ruc.id AS rucard_id, ruc.barcode AS rucard_barcode, ruc.usr AS rucard_usr, ruc.active AS rucard_active,
2285 cp.id AS cp_id, cp.circ_lib AS cp_circ_lib, cp.creator AS cp_creator, cp.call_number AS cp_call_number,
2286 cp.editor AS cp_editor, cp.create_date AS cp_create_date, cp.edit_date AS cp_edit_date,
2287 cp.copy_number AS cp_copy_number, cp.status AS cp_status, cp.location AS cp_location,
2288 cp.loan_duration AS cp_loan_duration, cp.fine_level AS cp_fine_level, cp.age_protect AS cp_age_protect,
2289 cp.circulate AS cp_circulate, cp.deposit AS cp_deposit, cp.ref AS cp_ref, cp.holdable AS cp_holdable,
2290 cp.deposit_amount AS cp_deposit_amount, cp.price AS cp_price, cp.barcode AS cp_barcode,
2291 cp.circ_modifier AS cp_circ_modifier, cp.circ_as_type AS cp_circ_as_type, cp.dummy_title AS cp_dummy_title,
2292 cp.dummy_author AS cp_dummy_author, cp.alert_message AS cp_alert_message, cp.opac_visible AS cp_opac_visible,
2293 cp.deleted AS cp_deleted, cp.floating AS cp_floating, cp.dummy_isbn AS cp_dummy_isbn,
2294 cp.status_changed_time AS cp_status_change_time, cp.active_date AS cp_active_date,
2295 cp.mint_condition AS cp_mint_condition, cp.cost AS cp_cost,
2297 cs.id AS cs_id, cs.name AS cs_name, cs.holdable AS cs_holdable, cs.opac_visible AS cs_opac_visible,
2298 cs.copy_active AS cs_copy_active, cs.restrict_copy_delete AS cs_restrict_copy_delete,
2299 cs.is_available AS cs_is_available,
2301 siss.label AS issuance_label,
2303 cn.id AS cn_id, cn.creator AS cn_creator, cn.create_date AS cn_create_date, cn.editor AS cn_editor,
2304 cn.edit_date AS cn_edit_date, cn.record AS cn_record, cn.owning_lib AS cn_owning_lib, cn.label AS cn_label,
2305 cn.deleted AS cn_deleted, cn.prefix AS cn_prefix, cn.suffix AS cn_suffix, cn.label_class AS cn_label_class,
2306 cn.label_sortkey AS cn_label_sortkey,
2308 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,
2310 acnp.label AS ancp_label, acns.label AS ancs_label,
2311 TRIM(acnp.label || ' ' || cn.label || ' ' || acns.label) AS cn_full_label,
2313 r.bib_record AS record_id,
2318 acpl.id AS acpl_id, acpl.name AS acpl_name, acpl.owning_lib AS acpl_owning_lib, acpl.holdable AS acpl_holdable,
2319 acpl.hold_verify AS acpl_hold_verify, acpl.opac_visible AS acpl_opac_visible, acpl.circulate AS acpl_circulate,
2320 acpl.label_prefix AS acpl_label_prefix, acpl.label_suffix AS acpl_label_suffix,
2321 acpl.checkin_alert AS acpl_checkin_alert, acpl.deleted AS acpl_deleted, acpl.url AS acpl_url,
2323 COALESCE(acplo.position, acpl_ordered.fallback_position) AS copy_location_order_position,
2326 PARTITION BY r.bib_record
2327 ORDER BY h.cut_in_line DESC NULLS LAST, h.request_time ASC
2328 ) AS relative_queue_position,
2330 EXTRACT(EPOCH FROM COALESCE(
2331 NULLIF(BTRIM(default_estimated_wait_interval.value,'"'),''),
2333 )::INTERVAL) AS default_estimated_wait,
2335 EXTRACT(EPOCH FROM COALESCE(
2336 NULLIF(BTRIM(min_estimated_wait_interval.value,'"'),''),
2338 )::INTERVAL) AS min_estimated_wait,
2340 COALESCE(hold_wait.potenials,0) AS potentials,
2341 COALESCE(hold_wait.other_holds,0) AS other_holds,
2342 COALESCE(hold_wait.total_wait_time,0) AS total_wait_time,
2344 n.count AS notification_count,
2345 n.max AS last_notification_time
2347 FROM action.hold_request h
2348 JOIN reporter.hold_request_record r ON (r.id = h.id)
2349 JOIN actor.usr u ON (u.id = h.usr)
2350 JOIN actor.card uc ON (uc.id = u.card)
2351 JOIN actor.usr ru ON (ru.id = h.requestor)
2352 JOIN actor.card ruc ON (ruc.id = ru.card)
2353 JOIN actor.org_unit pl ON (h.pickup_lib = pl.id)
2354 JOIN t_field ON TRUE
2355 JOIN a_field ON TRUE
2356 LEFT JOIN action.hold_request_cancel_cause cc ON (h.cancel_cause = cc.id)
2357 LEFT JOIN biblio.monograph_part p ON (h.hold_type = 'P' AND p.id = h.target)
2358 LEFT JOIN serial.issuance siss ON (h.hold_type = 'I' AND siss.id = h.target)
2359 LEFT JOIN asset.copy cp ON (h.current_copy = cp.id OR (h.hold_type IN ('C','F','R') AND cp.id = h.target))
2360 LEFT JOIN config.copy_status cs ON (cp.status = cs.id)
2361 LEFT JOIN asset.copy_location acpl ON (cp.location = acpl.id)
2362 LEFT JOIN asset.copy_location_order acplo ON (cp.location = acplo.location AND cp.circ_lib = acplo.org)
2364 SELECT *, (ROW_NUMBER() OVER (ORDER BY name) + 1000000) AS fallback_position
2365 FROM asset.copy_location
2366 ) acpl_ordered ON (acpl_ordered.id = cp.location)
2367 LEFT JOIN asset.call_number cn ON (cn.id = cp.call_number OR (h.hold_type = 'V' AND cn.id = h.target))
2368 LEFT JOIN asset.call_number_prefix acnp ON (cn.prefix = acnp.id)
2369 LEFT JOIN asset.call_number_suffix acns ON (cn.suffix = acns.id)
2370 LEFT JOIN LATERAL (SELECT * FROM action.hold_transit_copy WHERE h.id = hold ORDER BY id DESC LIMIT 1) tr ON TRUE
2371 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
2372 LEFT JOIN LATERAL (SELECT COUNT(*), MAX(notify_time) FROM action.hold_notification WHERE h.id = hold) n ON TRUE
2373 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
2374 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
2375 LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.holds.default_estimated_wait_interval',u.home_ou) AS default_estimated_wait_interval ON TRUE
2376 LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.holds.min_estimated_wait_interval',u.home_ou) AS min_estimated_wait_interval ON TRUE
2377 LEFT JOIN LATERAL actor.org_unit_ancestor_setting('circ.hold_shelf_status_delay',h.pickup_lib) AS hold_wait_time ON TRUE,
2379 SELECT COUNT(*) AS potenials,
2380 COUNT(DISTINCT hold) AS other_holds,
2385 COALESCE(NULLIF(BTRIM(default_estimated_wait_interval.value,'"'),''),'0 seconds')::INTERVAL
2388 ) AS total_wait_time
2389 FROM action.hold_copy_map m
2390 JOIN asset.copy cp ON (cp.id = m.target_copy)
2391 LEFT JOIN config.circ_modifier cm ON (cp.circ_modifier = cm.code)
2394 WHERE $initial_condition
2398 record_id => 'r.bib_record',
2400 usr_alias => 'u.alias',
2403 cp_deleted => 'cp.deleted',
2404 cancel_time => 'h.cancel_time',
2405 tr_cancel_time => 'tr.cancel_time',
2409 for my $r (keys %$restrictions) {
2410 my $real = $field_map{$r} || $r;
2411 next if ($r =~ /[^a-z_.]/); # skip obvious bad inputs
2414 if (ref($$restrictions{$r}) and ref($$restrictions{$r}) =~ /HASH/) {
2416 $$restrictions{$r} = $$restrictions{$r}{not};
2419 if (!defined($$restrictions{$r})) {
2420 $select .= " AND $real IS $not NULL ";
2421 } elsif (ref($$restrictions{$r})) {
2422 $select .= " AND $real $not IN (\$_$$\$" . join("\$_$$\$,\$_$$\$", @{$$restrictions{$r}}) . "\$_$$\$)";
2425 $select .= " AND $real $not= \$_$$\$$$restrictions{$r}\$_$$\$";
2431 return 0 unless $restricted;
2434 for my $o (@$order_by) {
2437 next if ($r =~ /[^a-z_.]/); # skip obvious bad inputs
2438 my $real = $field_map{$r} || $r;
2440 $ob[-1] .= ' DESC' if ($$o{$r}->{dir} and $$o{$r}->{dir} =~ /^d/i);
2441 $ob[-1] .= ' NULLS LAST' if ($$o{$r}->{nulls} and $$o{$r}->{nulls} =~ /^l/i);
2442 $ob[-1] .= ' NULLS FIRST' if ($$o{$r}->{nulls} and $$o{$r}->{nulls} =~ /^f/i);
2445 $select .= ' ORDER BY ' . join(', ', @ob) if (@ob);
2446 $select .= ' LIMIT ' . $limit if ($limit and $limit =~ /^\d+$/);
2447 $select .= ' OFFSET ' . $offset if ($offset and $offset =~ /^\d+$/);
2449 my $sth = action::hold_request->db_Main->prepare($select);
2452 my @list = $sth->fetchall_hash;
2453 $client->respond(scalar(@list)); # send the row count first, for progress tracking
2454 $client->respond( $_ ) for (@list);
2456 $client->respond_complete;
2458 __PACKAGE__->register_method(
2459 api_name => 'open-ils.storage.action.live_holds.wide_hash',
2462 max_bundle_count=> 1,
2463 method => 'wide_hold_data',