1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage::Publisher/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::PermitHold;
10 use DateTime::Format::ISO8601;
11 use OpenILS::Utils::Penalty;
15 return 1 if ($v == 1);
16 return 1 if ($v =~ /^t/io);
17 return 1 if ($v =~ /^y/io);
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
24 sub open_noncat_circs {
29 my $a = action::non_cataloged_circulation->table;
30 my $c = config::non_cataloged_type->table;
35 JOIN $c c ON (a.item_type = c.id)
36 WHERE a.circ_time + c.circ_duration > current_timestamp
40 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
42 __PACKAGE__->register_method(
43 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
46 method => 'open_noncat_circs',
50 sub ou_hold_requests {
55 my $h_table = action::hold_request->table;
56 my $c_table = asset::copy->table;
57 my $o_table = actor::org_unit->table;
62 JOIN $c_table cp ON (cp.id = h.current_copy)
63 JOIN $o_table ou ON (ou.id = cp.circ_lib)
65 AND h.capture_time IS NULL
66 AND h.cancel_time IS NULL
67 AND (h.expire_time IS NULL OR h.expire_time > NOW())
68 ORDER BY h.request_time
71 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
74 $client->respond($_) for (
77 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
81 } @{ $sth->fetchall_arrayref }
85 __PACKAGE__->register_method(
86 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
90 method => 'ou_hold_requests',
96 my $upper_interval = shift || '1 millennium';
98 my $c_t = action::circulation->table;
100 if ($grace && $grace =~ /^\d+$/o) {
101 $grace = " - ($grace * (fine_interval))";
109 WHERE stop_fines IS NULL
110 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 AND fine_interval < ?::INTERVAL
114 my $sth = action::circulation->db_Main->prepare_cached($sql);
115 $sth->execute($upper_interval);
117 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
121 sub complete_reshelving {
126 local $OpenILS::Application::Storage::WRITE = 1;
128 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
129 unless (interval_to_seconds( $window ));
131 my $setting = actor::org_unit_setting->table;
132 my $circ = action::circulation->table;
133 my $cp = asset::copy->table;
140 FROM (SELECT cp.id, MAX(circ.checkin_time)
142 JOIN $circ circ ON (circ.target_copy = cp.id)
143 LEFT JOIN $setting setting
144 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
145 WHERE circ.checkin_time IS NOT NULL
148 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL)
153 LEFT JOIN $setting setting
154 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
155 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
157 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
161 my $sth = action::circulation->db_Main->prepare_cached($sql);
162 $sth->execute($window, $window);
167 __PACKAGE__->register_method(
168 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
171 method => 'complete_reshelving',
174 sub mark_longoverdue {
179 local $OpenILS::Application::Storage::WRITE = 1;
181 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
182 unless (interval_to_seconds( $window ));
184 my $setting = actor::org_unit_setting->table;
185 my $circ = action::circulation->table;
189 SET stop_fines = 'LONGOVERDUE',
190 stop_fines_time = now()
194 LEFT JOIN $setting setting
195 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
196 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
197 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
201 my $sth = action::circulation->db_Main->prepare_cached($sql);
202 $sth->execute($window);
207 __PACKAGE__->register_method(
208 api_name => 'open-ils.storage.action.circulation.long_overdue',
211 method => 'mark_longoverdue',
214 sub auto_thaw_frozen_holds {
218 local $OpenILS::Application::Storage::WRITE = 1;
220 my $holds = action::hold_request->table;
222 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
224 my $sth = action::hold_request->db_Main->prepare_cached($sql);
230 __PACKAGE__->register_method(
231 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
235 method => 'auto_thaw_frozen_holds',
241 my $grace = shift || '';
243 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
248 __PACKAGE__->register_method(
249 api_name => 'open-ils.storage.action.circulation.overdue',
252 method => 'grab_overdue',
260 my $limit = int(shift()) || 10;
261 my $age = shift() || '0 seconds';
263 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
265 FROM action.hold_request h
266 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
267 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
268 WHERE hm.target_copy = ?
269 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
270 AND h.capture_time IS NULL
271 AND h.cancel_time IS NULL
272 AND (h.expire_time IS NULL OR h.expire_time > NOW())
273 AND h.frozen IS FALSE
276 h.selection_depth DESC,
281 $client->respond( $_ ) for ( @$ids );
284 __PACKAGE__->register_method(
285 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
288 method => 'nearest_hold',
291 sub next_resp_group_id {
295 # XXX This is not replication safe!!!
297 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
298 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
302 __PACKAGE__->register_method(
303 api_name => 'open-ils.storage.action.survey_response.next_group_id',
305 method => 'next_resp_group_id',
308 sub patron_circ_summary {
313 return undef unless ($id);
314 my $c_table = action::circulation->table;
315 my $b_table = money::billing->table;
317 $log->debug("Retrieving patron summary for id $id", DEBUG);
319 my $select = <<" SQL";
320 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
322 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
324 AND c.xact_finish IS NULL
326 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
327 OR c.stop_fines IS NULL
331 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
333 __PACKAGE__->register_method(
334 api_name => 'open-ils.storage.action.circulation.patron_summary',
336 method => 'patron_circ_summary',
339 #XXX Fix stored proc calls
340 sub find_local_surveys {
345 return undef unless ($ou);
346 my $s_table = action::survey->table;
348 my $select = <<" SQL";
351 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
352 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
355 my $sth = action::survey->db_Main->prepare_cached($select);
358 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
362 __PACKAGE__->register_method(
363 api_name => 'open-ils.storage.action.survey.all',
366 method => 'find_local_surveys',
369 #XXX Fix stored proc calls
370 sub find_opac_surveys {
375 return undef unless ($ou);
376 my $s_table = action::survey->table;
378 my $select = <<" SQL";
381 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
382 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
386 my $sth = action::survey->db_Main->prepare_cached($select);
389 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
393 __PACKAGE__->register_method(
394 api_name => 'open-ils.storage.action.survey.opac',
397 method => 'find_opac_surveys',
404 my $limit = shift || 10;
405 my $offset = shift || 0;
407 return undef unless ($ou);
408 my $h_table = action::hold_request->table;
409 my $a_table = asset::copy->table;
411 my $idlist = 1 if ($self->api_name =~/id_list/o);
413 my $status_filter = '';
414 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
416 my $select = <<" SQL";
419 JOIN $a_table a ON (h.current_copy = a.id)
421 AND h.capture_time IS NULL
422 AND h.cancel_time IS NULL
423 AND (h.expire_time IS NULL OR h.expire_time > NOW())
425 ORDER BY h.request_time ASC
430 my $sth = action::survey->db_Main->prepare_cached($select);
434 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
436 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
441 __PACKAGE__->register_method(
442 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
446 "Returns the hold ids for a specific library's pull list.",
447 [ [org_unit => "The library's org id", "number"],
448 [limit => 'An optional page size, defaults to 10', 'number'],
449 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
451 ['A list of holds for the stated library to pull for', 'array']
453 method => 'hold_pull_list',
455 __PACKAGE__->register_method(
456 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
460 "Returns the holds for a specific library's pull list.",
461 [ [org_unit => "The library's org id", "number"],
462 [limit => 'An optional page size, defaults to 10', 'number'],
463 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
465 ['A list of holds for the stated library to pull for', 'array']
467 method => 'hold_pull_list',
469 __PACKAGE__->register_method(
470 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
474 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
475 [ [org_unit => "The library's org id", "number"],
476 [limit => 'An optional page size, defaults to 10', 'number'],
477 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
479 ['A list of holds for the stated library to pull for', 'array']
481 method => 'hold_pull_list',
483 __PACKAGE__->register_method(
484 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
488 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
489 [ [org_unit => "The library's org id", "number"],
490 [limit => 'An optional page size, defaults to 10', 'number'],
491 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
493 ['A list of holds for the stated library to pull for', 'array']
495 method => 'hold_pull_list',
498 sub find_optional_surveys {
503 return undef unless ($ou);
504 my $s_table = action::survey->table;
506 my $select = <<" SQL";
509 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
510 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
511 AND s.required IS FALSE;
514 my $sth = action::survey->db_Main->prepare_cached($select);
517 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
521 __PACKAGE__->register_method(
522 api_name => 'open-ils.storage.action.survey.optional',
525 method => 'find_optional_surveys',
528 sub find_required_surveys {
533 return undef unless ($ou);
534 my $s_table = action::survey->table;
536 my $select = <<" SQL";
539 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
540 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
541 AND s.required IS TRUE;
544 my $sth = action::survey->db_Main->prepare_cached($select);
547 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
551 __PACKAGE__->register_method(
552 api_name => 'open-ils.storage.action.survey.required',
555 method => 'find_required_surveys',
558 sub find_usr_summary_surveys {
563 return undef unless ($ou);
564 my $s_table = action::survey->table;
566 my $select = <<" SQL";
569 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
570 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
571 AND s.usr_summary IS TRUE;
574 my $sth = action::survey->db_Main->prepare_cached($select);
577 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
581 __PACKAGE__->register_method(
582 api_name => 'open-ils.storage.action.survey.usr_summary',
585 method => 'find_usr_summary_surveys',
594 my $overbill = shift;
596 local $OpenILS::Application::Storage::WRITE = 1;
600 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
602 push @circs, overdue_circs($grace);
605 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
607 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
611 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
612 $log->debug("Cleaning up after previous transaction\n");
613 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
615 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
616 $log->info("Processing circ ".$c->id."...\n");
619 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
621 my $due = $due_dt->epoch;
624 my $fine_interval = $c->fine_interval;
625 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
626 $fine_interval = interval_to_seconds( $fine_interval );
628 if ( $fine_interval >= interval_to_seconds('1d') ) {
630 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
631 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
634 $due -= ($due % $fine_interval) + $tz_offset_s;
635 $now -= ($now % $fine_interval) + $tz_offset_s;
639 "ARG! Overdue circulation ".$c->id.
640 " for item ".$c->target_copy.
641 " (user ".$c->usr.").\n".
642 "\tItem was due on or before: ".localtime($due)."\n");
644 my @fines = money::billing->search_where(
647 billing_ts => { '>' => $c->due_date } },
648 { order_by => 'billing_ts DESC'}
652 my $fine = $fines[$f_idx] if (@fines);
654 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
657 my $current_fine_total = 0;
658 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
662 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
663 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
665 $log->info( "Potential first billing for circ ".$c->id );
669 if (my $h = $hoo{$c->circ_lib}) {
671 $log->info( "Circ lib has an hours-of-operation entry" );
672 # find the day after the due date...
673 $due_dt = $due_dt->add( days => 1 );
675 # get the day of the week for that day...
676 my $dow = $due_dt->day_of_week_0;
677 my $dow_open = "dow_${dow}_open";
678 my $dow_close = "dow_${dow}_close";
681 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
682 # if the circ lib is closed, add a day to the grace period...
685 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
686 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
688 $due_dt = $due_dt->add( days => 1 );
689 $dow = $due_dt->day_of_week_0;
690 $dow_open = "dow_${dow}_open";
691 $dow_close = "dow_${dow}_close";
695 # and check for up to a week
696 last if ($count > 6);
703 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
704 if ($pending_fine_count < 1 + $grace) {
705 $client->respond( "\tNo fines to create. " );
706 if ($grace && $now < $due + $fine_interval * $grace) {
707 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
708 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
710 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
715 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
717 my $recuring_fine = int($c->recuring_fine * 100);
718 my $max_fine = int($c->max_fine * 100);
720 my ($latest_billing_ts, $latest_amount) = ('',0);
721 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
723 if ($current_fine_total >= $max_fine) {
724 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
726 "\tMaximum fine level of ".$c->max_fine.
727 " reached for this circulation.\n".
728 "\tNo more fines will be generated.\n" );
732 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
734 my $dow = $billing_ts->day_of_week_0();
735 my $dow_open = "dow_${dow}_open";
736 my $dow_close = "dow_${dow}_close";
738 if (my $h = $hoo{$c->circ_lib}) {
739 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
742 my $timestamptz = $billing_ts->strftime('%FT%T%z');
743 my @cl = actor::org_unit::closed_date->search_where(
744 { close_start => { '<=' => $timestamptz },
745 close_end => { '>=' => $timestamptz },
746 org_unit => $c->circ_lib }
750 $current_fine_total += $recuring_fine;
751 $latest_amount += $recuring_fine;
752 $latest_billing_ts = $timestamptz;
754 money::billing->create(
756 note => "System Generated Overdue Fine",
757 billing_type => "Overdue materials",
759 amount => sprintf('%0.2f', $recuring_fine/100),
760 billing_ts => $timestamptz,
766 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
767 if ($latest_billing_ts and $latest_amount);
769 $self->method_lookup('open-ils.storage.transaction.commit')->run;
771 if(0) { # caluclate penalties inline. Needs to be tested.
772 OpenILS::Utils::Penalty->calculate_penalties(
773 undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
777 'open-ils.penalty.patron_penalty.calculate',
778 { patron => $c->usr->to_fieldmapper,
787 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
788 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
789 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
790 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
794 __PACKAGE__->register_method(
795 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
798 method => 'generate_fines',
803 sub new_hold_copy_targeter {
806 my $check_expire = shift;
807 my $one_hold = shift;
809 local $OpenILS::Application::Storage::WRITE = 1;
815 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
816 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
817 } elsif ( $check_expire ) {
819 # what's the retarget time threashold?
821 $check_expire ||= '12h';
822 $check_expire = interval_to_seconds( $check_expire );
824 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
827 my $expire_threshold = sprintf(
828 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
829 $year, $mon, $mday, $hour, $min, $sec
832 # find all the holds holds needing retargeting
833 $holds = [ action::hold_request->search_where(
834 { capture_time => undef,
835 fulfillment_time => undef,
836 cancel_time => undef,
838 prev_check_time => { '<=' => $expire_threshold },
840 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
842 # find all the holds holds needing first time targeting
843 push @$holds, action::hold_request->search(
844 capture_time => undef,
845 fulfillment_time => undef,
846 prev_check_time => undef,
848 cancel_time => undef,
849 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
852 # find all the holds holds needing first time targeting ONLY
853 $holds = [ action::hold_request->search(
854 capture_time => undef,
855 fulfillment_time => undef,
856 prev_check_time => undef,
857 cancel_time => undef,
859 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
863 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
866 my @closed = actor::org_unit::closed_date->search_where(
867 { close_start => { '<=', 'now' },
868 close_end => { '>=', 'now' } }
874 for my $hold (@$holds) {
876 #start a transaction if needed
877 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
878 $log->debug("Cleaning up after previous transaction\n");
879 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
881 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
882 $log->info("Processing hold ".$hold->id."...\n");
884 #first, re-fetch the hold, to make sure it's not captured already
885 $hold->remove_from_object_index();
886 $hold = action::hold_request->retrieve( $hold->id );
888 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
890 # remove old auto-targeting maps
891 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
892 $_->delete for (@oldmaps);
894 if ($hold->expire_time) {
895 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
896 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
897 $hold->update( { cancel_time => 'now' } );
898 $self->method_lookup('open-ils.storage.transaction.commit')->run;
905 # find filters for MR holds
906 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
908 # find all the potential copies
909 if ($hold->hold_type eq 'M') {
912 metabib::record_descriptor
916 isTrue($_->deleted) ? () : ($_->id)
917 } metabib::metarecord->retrieve($hold->target)->source_records
919 ( $types ? (item_type => [split '', $types]) : () ),
920 ( $formats ? (item_form => [split '', $formats]) : () ),
921 ( $lang ? (item_lang => $lang) : () ),
925 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
926 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
928 for my $cn ( @{ $rtree->call_numbers } ) {
930 asset::copy->search_where(
931 { id => [map {$_->id} @{ $cn->copies }],
933 ) if ($cn && @{ $cn->copies });
936 } elsif ($hold->hold_type eq 'T') {
938 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
939 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
942 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
946 for my $cn ( @{ $rtree->call_numbers } ) {
948 asset::copy->search_where(
949 { id => [map {$_->id} @{ $cn->copies }],
951 ) if ($cn && @{ $cn->copies });
953 } elsif ($hold->hold_type eq 'V') {
955 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
956 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
959 asset::copy->search_where(
960 { id => [map {$_->id} @{ $vtree->copies }],
962 ) if ($vtree && @{ $vtree->copies });
964 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
965 my $_cp = asset::copy->retrieve($hold->target);
966 push @$all_copies, $_cp if $_cp;
970 @$all_copies = grep { isTrue($_->status->holdable) &&
971 isTrue($_->location->holdable) &&
972 isTrue($_->holdable) &&
976 # let 'em know we're still working
977 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
979 # if we have no copies ...
980 if (!ref $all_copies || !@$all_copies) {
981 $log->info("\tNo copies available for targeting at all!\n");
982 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
984 $hold->update( { prev_check_time => 'today', current_copy => undef } );
985 $self->method_lookup('open-ils.storage.transaction.commit')->run;
989 my $copy_count = @$all_copies;
991 # map the potentials, so that we can pick up checkins
992 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
993 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
994 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
995 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
997 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1000 for my $c (@$all_copies) {
1002 next if ($c->id eq $hold->current_copy);
1004 # circ lib is closed
1005 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1007 # target of another hold
1008 next if (action::hold_request
1010 { current_copy => $c->id,
1011 fulfillment_time => undef,
1012 cancel_time => undef,
1017 # we passed all three, keep it
1018 push @good_copies, $c if ($c);
1019 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1022 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1024 my $old_best = $hold->current_copy;
1025 $hold->update({ current_copy => undef }) if ($old_best);
1027 if (!scalar(@good_copies)) {
1028 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1029 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1030 # the old copy is still available
1031 $log->debug("\tPushing current_copy back onto the targeting list");
1032 push @good_copies, $old_best;
1034 # oops, old copy is not available
1035 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1036 $hold->update( { prev_check_time => 'today' } );
1037 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1038 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1047 $_->circ_lib == $hold->pickup_lib
1051 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1052 # $all_copies is now a list of copies not at the pickup library
1054 my $best = choose_nearest_copy($hold, $prox_list);
1055 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1058 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1060 my $max_loops = $actor->request(
1061 'open-ils.actor.ou_setting.ancestor_default' => $lib => 'circ.holds.max_org_unit_target_loops'
1064 if (defined($max_loops)) {
1065 my %circ_lib_map = map ( $_->circ_lib => 1 ) @$all_copies;
1066 my $circ_lib_list = [keys %circ_lib_map];
1068 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1070 # Grab the "biggest" loop for this hold so far
1071 my $current_loop = $cstore->request(
1072 'open-ils.cstore.json_query',
1074 select => { aufhmxl => [max] },
1076 where => { hold => $hold->id}
1080 $current_loop = $current_loop->{max} if ($current_loop);
1081 $current_loop ||= 1;
1083 my $exclude_list = $cstore->request(
1084 'open-ils.cstore.json_query.atomic',
1086 select => { aufhol => [circ_lib] },
1088 where => { hold => $hold->id}
1093 if ($exclude_list && @$exclude_list) {
1094 $exclude_list = [map ($_->{circ_lib}) @$exclude_list];
1095 # check to see if we've used up every library in the potentials list
1096 for my $l ( @$circ_lib_list ) {
1098 for my $ex ( @$exclude_list ) {
1104 push(@keepers, $l) if ($keep);
1107 @keepers = @$circ_lib_list;
1110 $current_loop++ if (!@keepers);
1112 if ($max_loops && $max_loops <= $current_loop) {
1113 # We haven't exceeded max_loops yet
1115 for my $cp ( @$all_copies ) {
1116 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1119 # We have, and should remove potentials and cancel the hold
1120 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1121 $_->delete for (@oldmaps);
1123 $hold->update( { cancel_time => 'now' } );
1124 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1129 $self->{target_weight} = {};
1130 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1132 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1134 $best = choose_nearest_copy($hold, $prox_list);
1137 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1139 # hold wasn't fulfilled, record the fact
1141 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1142 action::unfulfilled_hold_list->create(
1143 { hold => ''.$hold->id,
1144 current_copy => ''.$old_best->id,
1145 circ_lib => ''.$old_best->circ_lib,
1150 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1151 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1154 action::hold_request
1156 { current_copy => $old_best->id,
1157 fulfillment_time => undef,
1158 cancel_time => undef,
1162 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1163 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1165 $hold->update( { prev_check_time => 'now' } );
1166 $log->info( "\tThere were no targetable copies for the hold" );
1169 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1170 $log->info("\tProcessing of hold ".$hold->id." complete.");
1173 { hold => $hold->id,
1174 old_target => ($old_best ? $old_best->id : undef),
1175 eligible_copies => $copy_count,
1176 target => ($best ? $best->id : undef) };
1181 $log->error("Processing of hold failed: $e");
1182 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1183 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1190 __PACKAGE__->register_method(
1191 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1193 method => 'new_hold_copy_targeter',
1198 my %cache = (titles => {}, cns => {});
1199 sub hold_copy_targeter {
1202 my $check_expire = shift;
1203 my $one_hold = shift;
1205 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1206 $self->{user_filter}->connect;
1207 $self->{client} = $client;
1210 $check_expire ||= '12h';
1211 $check_expire = interval_to_seconds( $check_expire );
1213 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1216 my $expire_threshold = sprintf(
1217 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1218 $year, $mon, $mday, $hour, $min, $sec
1222 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1224 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1228 %cache = (titles => {}, cns => {});
1232 $holds = [ action::hold_request->search(id => $one_hold) ];
1234 $holds = [ action::hold_request->search_where(
1235 { capture_time => undef,
1236 prev_check_time => { '<=' => $expire_threshold },
1238 { order_by => 'request_time,prev_check_time' } ) ];
1239 push @$holds, action::hold_request->search_where(
1240 { capture_time => undef,
1241 prev_check_time => undef,
1243 { order_by => 'request_time' } );
1245 } catch Error with {
1247 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1250 for my $hold (@$holds) {
1252 #action::hold_request->db_Main->begin_work;
1253 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1254 $client->respond("Cleaning up after previous transaction\n");
1255 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1257 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1258 $client->respond("Processing hold ".$hold->id."...\n");
1262 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1263 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1265 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1266 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1268 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1269 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1271 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1273 unless (ref $copies || !@$copies) {
1274 $client->respond("\tNo copies available for targeting at all!\n");
1278 for my $c (@$copies) {
1279 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1280 push @good_copies, $c if ($c);
1283 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1285 my $old_best = $hold->current_copy;
1286 $hold->update({ current_copy => undef });
1288 if (!scalar(@good_copies)) {
1289 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1290 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1291 $client->respond("\tPushing current_copy back onto the targeting list\n");
1292 push @good_copies, asset::copy->retrieve( $old_best );
1294 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1300 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1301 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1303 my $best = choose_nearest_copy($hold, $prox_list);
1306 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1307 $best = choose_nearest_copy($hold, $prox_list);
1311 # hold wasn't fulfilled, record the fact
1313 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1314 action::unfulfilled_hold_list->create(
1315 { hold => ''.$hold->id,
1316 current_copy => ''.$old_best->id,
1317 circ_lib => ''.$old_best->circ_lib,
1322 $hold->update( { current_copy => ''.$best->id } );
1323 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1326 $hold->update( { prev_check_time => 'now' } );
1327 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1329 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1330 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1332 #action::hold_request->dbi_commit;
1336 $log->error("Processing of hold failed: $e");
1337 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1338 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1339 #action::hold_request->dbi_rollback;
1343 $self->{user_filter}->disconnect;
1344 $self->{user_filter}->finish;
1345 delete $$self{user_filter};
1348 #__PACKAGE__->register_method(
1349 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1352 # method => 'hold_copy_targeter',
1356 sub copy_hold_capture {
1361 if (!defined($cps)) {
1363 $cps = [ asset::copy->search( id => $hold->target ) ];
1364 } catch Error with {
1366 die "Could not retrieve initial volume list:\n\n$e\n";
1370 my @copies = grep { $_->holdable } @$cps;
1372 for (my $i = 0; $i < @$cps; $i++) {
1373 next unless $$cps[$i];
1375 my $cn = $cache{cns}{$copies[$i]->call_number};
1376 my $rec = $cache{titles}{$cn->record};
1377 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1378 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1379 $copies[$i] = undef if (
1381 !$self->{user_filter}->request(
1382 'open-ils.circ.permit_hold',
1383 $hold->to_fieldmapper, do {
1384 my $cp_fm = $copies[$i]->to_fieldmapper;
1385 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1386 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1387 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1390 { title => $rec->to_fieldmapper,
1391 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1392 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1395 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1398 @copies = grep { $_ } @copies;
1400 my $count = @copies;
1402 return unless ($count);
1404 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1407 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1408 for my $c (@copies) {
1409 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1411 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1417 sub choose_nearest_copy {
1419 my $prox_list = shift;
1421 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1422 next unless (ref $$prox_list[$p]);
1424 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1425 next unless (@capturable);
1427 my $rand = int(rand(scalar(@capturable)));
1428 while (my ($c) = splice(@capturable,$rand)) {
1429 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1430 { title => $c->call_number->record->to_fieldmapper,
1431 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1432 patron => $hold->usr->to_fieldmapper,
1433 copy => $c->to_fieldmapper,
1434 requestor => $hold->requestor->to_fieldmapper,
1435 request_lib => $hold->request_lib->to_fieldmapper,
1436 pickup_lib => $hold->pickup_lib->id,
1440 last unless(@capturable);
1441 $rand = int(rand(scalar(@capturable)));
1446 sub create_prox_list {
1451 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1454 for my $cp (@$copies) {
1455 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1456 next unless (defined($prox));
1458 # Fetch the weighting value for hold targeting, defaulting to 1
1459 $self->{target_weight} ||= $actor->request(
1460 'open-ils.actor.ou_setting.ancestor_default' => $lib => 'circ.holds.org_unit_target_weight'
1463 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1464 for my $w ( 1 .. $self->{target_weight} ) {
1465 push @{$prox_list[$prox]}, $cp;
1471 sub volume_hold_capture {
1476 if (!defined($vols)) {
1478 $vols = [ asset::call_number->search( id => $hold->target ) ];
1479 $cache{cns}{$_->id} = $_ for (@$vols);
1480 } catch Error with {
1482 die "Could not retrieve initial volume list:\n\n$e\n";
1486 my @v_ids = map { $_->id } @$vols;
1490 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1492 } catch Error with {
1494 warn "Could not retrieve copy list:\n\n$e\n";
1497 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1500 sub title_hold_capture {
1505 if (!defined($titles)) {
1507 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1508 $cache{titles}{$_->id} = $_ for (@$titles);
1509 } catch Error with {
1511 die "Could not retrieve initial title list:\n\n$e\n";
1515 my @t_ids = map { $_->id } @$titles;
1518 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1520 } catch Error with {
1522 warn "Could not retrieve volume list:\n\n$e\n";
1525 $cache{cns}{$_->id} = $_ for (@$cn_list);
1527 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1530 sub metarecord_hold_capture {
1536 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1538 } catch Error with {
1540 die "Could not retrieve initial title list:\n\n$e\n";
1544 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1546 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1548 } catch Error with {
1550 die "Could not retrieve format-pruned title list:\n\n$e\n";
1554 $cache{titles}{$_->id} = $_ for (@$titles);
1555 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);