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;
14 return 1 if ($v == 1);
15 return 1 if ($v =~ /^t/io);
16 return 1 if ($v =~ /^y/io);
20 my $parser = DateTime::Format::ISO8601->new;
21 my $log = 'OpenSRF::Utils::Logger';
23 sub open_noncat_circs {
28 my $a = action::non_cataloged_circulation->table;
29 my $c = config::non_cataloged_type->table;
34 JOIN $c c ON (a.item_type = c.id)
35 WHERE a.circ_time + c.circ_duration > current_timestamp
39 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
41 __PACKAGE__->register_method(
42 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
45 method => 'open_noncat_circs',
49 sub ou_hold_requests {
54 my $h_table = action::hold_request->table;
55 my $c_table = asset::copy->table;
56 my $o_table = actor::org_unit->table;
61 JOIN $c_table cp ON (cp.id = h.current_copy)
62 JOIN $o_table ou ON (ou.id = cp.circ_lib)
64 AND h.capture_time IS NULL
65 AND h.cancel_time IS NULL
66 AND (h.expire_time IS NULL OR h.expire_time > NOW())
67 ORDER BY h.request_time
70 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
73 $client->respond($_) for (
76 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
80 } @{ $sth->fetchall_arrayref }
84 __PACKAGE__->register_method(
85 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
89 method => 'ou_hold_requests',
96 my $c_t = action::circulation->table;
99 $grace = " - ($grace * (fine_interval))";
107 WHERE stop_fines IS NULL
108 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 my $sth = action::circulation->db_Main->prepare_cached($sql);
114 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
118 sub complete_reshelving {
123 local $OpenILS::Application::Storage::WRITE = 1;
125 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
126 unless (interval_to_seconds( $window ));
128 my $setting = actor::org_unit_setting->table;
129 my $circ = action::circulation->table;
130 my $cp = asset::copy->table;
137 FROM (SELECT cp.id, MAX(circ.checkin_time)
139 JOIN $circ circ ON (circ.target_copy = cp.id)
140 LEFT JOIN $setting setting
141 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
142 WHERE circ.checkin_time IS NOT NULL
145 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
150 LEFT JOIN $setting setting
151 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
152 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
154 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
158 my $sth = action::circulation->db_Main->prepare_cached($sql);
159 $sth->execute($window, $window);
164 __PACKAGE__->register_method(
165 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
169 method => 'complete_reshelving',
172 sub auto_thaw_frozen_holds {
176 local $OpenILS::Application::Storage::WRITE = 1;
178 my $holds = action::hold_request->table;
180 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
182 my $sth = action::hold_request->db_Main->prepare_cached($sql);
188 __PACKAGE__->register_method(
189 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
193 method => 'auto_thaw_frozen_holds',
199 my $grace = shift || '';
201 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
206 __PACKAGE__->register_method(
207 api_name => 'open-ils.storage.action.circulation.overdue',
210 method => 'grab_overdue',
218 my $limit = int(shift()) || 10;
219 my $age = shift() || '0 seconds';
221 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
223 FROM action.hold_request h
224 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
225 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
226 WHERE hm.target_copy = ?
227 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
228 AND h.capture_time IS NULL
229 AND h.cancel_time IS NULL
230 AND (h.expire_time IS NULL OR h.expire_time > NOW())
231 AND h.frozen IS FALSE
234 h.selection_depth DESC,
239 $client->respond( $_ ) for ( @$ids );
242 __PACKAGE__->register_method(
243 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
246 method => 'nearest_hold',
249 sub next_resp_group_id {
253 # XXX This is not replication safe!!!
255 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
256 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
260 __PACKAGE__->register_method(
261 api_name => 'open-ils.storage.action.survey_response.next_group_id',
263 method => 'next_resp_group_id',
266 sub patron_circ_summary {
271 return undef unless ($id);
272 my $c_table = action::circulation->table;
273 my $b_table = money::billing->table;
275 $log->debug("Retrieving patron summary for id $id", DEBUG);
277 my $select = <<" SQL";
278 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
280 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
282 AND c.xact_finish IS NULL
284 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
285 OR c.stop_fines IS NULL
289 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
291 __PACKAGE__->register_method(
292 api_name => 'open-ils.storage.action.circulation.patron_summary',
294 method => 'patron_circ_summary',
297 #XXX Fix stored proc calls
298 sub find_local_surveys {
303 return undef unless ($ou);
304 my $s_table = action::survey->table;
306 my $select = <<" SQL";
309 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
310 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
313 my $sth = action::survey->db_Main->prepare_cached($select);
316 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
320 __PACKAGE__->register_method(
321 api_name => 'open-ils.storage.action.survey.all',
324 method => 'find_local_surveys',
327 #XXX Fix stored proc calls
328 sub find_opac_surveys {
333 return undef unless ($ou);
334 my $s_table = action::survey->table;
336 my $select = <<" SQL";
339 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
340 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
344 my $sth = action::survey->db_Main->prepare_cached($select);
347 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
351 __PACKAGE__->register_method(
352 api_name => 'open-ils.storage.action.survey.opac',
355 method => 'find_opac_surveys',
362 my $limit = shift || 10;
363 my $offset = shift || 0;
365 return undef unless ($ou);
366 my $h_table = action::hold_request->table;
367 my $a_table = asset::copy->table;
369 my $idlist = 1 if ($self->api_name =~/id_list/o);
371 my $status_filter = '';
372 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
374 my $select = <<" SQL";
377 JOIN $a_table a ON (h.current_copy = a.id)
379 AND h.capture_time IS NULL
380 AND h.cancel_time IS NULL
381 AND (h.expire_time IS NULL OR h.expire_time > NOW())
383 ORDER BY h.request_time ASC
388 my $sth = action::survey->db_Main->prepare_cached($select);
392 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
394 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
399 __PACKAGE__->register_method(
400 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
404 "Returns the hold ids for a specific library's pull list.",
405 [ [org_unit => "The library's org id", "number"],
406 [limit => 'An optional page size, defaults to 10', 'number'],
407 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
409 ['A list of holds for the stated library to pull for', 'array']
411 method => 'hold_pull_list',
413 __PACKAGE__->register_method(
414 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
418 "Returns the holds for a specific library's pull list.",
419 [ [org_unit => "The library's org id", "number"],
420 [limit => 'An optional page size, defaults to 10', 'number'],
421 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
423 ['A list of holds for the stated library to pull for', 'array']
425 method => 'hold_pull_list',
427 __PACKAGE__->register_method(
428 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
432 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
433 [ [org_unit => "The library's org id", "number"],
434 [limit => 'An optional page size, defaults to 10', 'number'],
435 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
437 ['A list of holds for the stated library to pull for', 'array']
439 method => 'hold_pull_list',
441 __PACKAGE__->register_method(
442 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
446 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
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',
456 sub find_optional_surveys {
461 return undef unless ($ou);
462 my $s_table = action::survey->table;
464 my $select = <<" SQL";
467 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
468 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
469 AND s.required IS FALSE;
472 my $sth = action::survey->db_Main->prepare_cached($select);
475 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
479 __PACKAGE__->register_method(
480 api_name => 'open-ils.storage.action.survey.optional',
483 method => 'find_optional_surveys',
486 sub find_required_surveys {
491 return undef unless ($ou);
492 my $s_table = action::survey->table;
494 my $select = <<" SQL";
497 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
498 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
499 AND s.required IS TRUE;
502 my $sth = action::survey->db_Main->prepare_cached($select);
505 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
509 __PACKAGE__->register_method(
510 api_name => 'open-ils.storage.action.survey.required',
513 method => 'find_required_surveys',
516 sub find_usr_summary_surveys {
521 return undef unless ($ou);
522 my $s_table = action::survey->table;
524 my $select = <<" SQL";
527 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
528 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
529 AND s.usr_summary IS TRUE;
532 my $sth = action::survey->db_Main->prepare_cached($select);
535 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
539 __PACKAGE__->register_method(
540 api_name => 'open-ils.storage.action.survey.usr_summary',
543 method => 'find_usr_summary_surveys',
552 my $overbill = shift;
554 local $OpenILS::Application::Storage::WRITE = 1;
558 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
560 push @circs, overdue_circs($grace);
563 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
565 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
569 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
570 $log->debug("Cleaning up after previous transaction\n");
571 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
573 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
574 $log->info("Processing circ ".$c->id."...\n");
577 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
579 my $due = $due_dt->epoch;
582 my $fine_interval = $c->fine_interval;
583 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
584 $fine_interval = interval_to_seconds( $fine_interval );
586 if ( $fine_interval >= interval_to_seconds('1d') ) {
588 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
589 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
592 $due -= ($due % $fine_interval) + $tz_offset_s;
593 $now -= ($now % $fine_interval) + $tz_offset_s;
597 "ARG! Overdue circulation ".$c->id.
598 " for item ".$c->target_copy.
599 " (user ".$c->usr.").\n".
600 "\tItem was due on or before: ".localtime($due)."\n");
602 my @fines = money::billing->search_where(
604 billing_type => 'Overdue materials',
605 billing_ts => { '>' => $c->due_date } },
606 { order_by => 'billing_ts DESC'}
610 my $fine = $fines[$f_idx] if (@fines);
612 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
615 my $current_fine_total = 0;
616 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
620 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
621 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
623 $log->info( "Potential first billing for circ ".$c->id );
627 if (my $h = $hoo{$c->circ_lib}) {
629 $log->info( "Circ lib has an hours-of-operation entry" );
630 # find the day after the due date...
631 $due_dt = $due_dt->add( days => 1 );
633 # get the day of the week for that day...
634 my $dow = $due_dt->day_of_week_0;
635 my $dow_open = "dow_${dow}_open";
636 my $dow_close = "dow_${dow}_close";
639 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
640 # if the circ lib is closed, add a day to the grace period...
643 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
644 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
646 $due_dt = $due_dt->add( days => 1 );
647 $dow = $due_dt->day_of_week_0;
648 $dow_open = "dow_${dow}_open";
649 $dow_close = "dow_${dow}_close";
653 # and check for up to a week
654 last if ($count > 6);
661 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
662 if ($pending_fine_count < 1 + $grace) {
663 $client->respond( "\tNo fines to create. " );
664 if ($grace && $now < $due + $fine_interval * $grace) {
665 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
666 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
668 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
673 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
675 my $recuring_fine = int($c->recuring_fine * 100);
676 my $max_fine = int($c->max_fine * 100);
678 my ($latest_billing_ts, $latest_amount) = ('',0);
679 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
681 if ($current_fine_total >= $max_fine) {
682 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
684 "\tMaximum fine level of ".$c->max_fine.
685 " reached for this circulation.\n".
686 "\tNo more fines will be generated.\n" );
690 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
692 my $dow = $billing_ts->day_of_week_0();
693 my $dow_open = "dow_${dow}_open";
694 my $dow_close = "dow_${dow}_close";
696 if (my $h = $hoo{$c->circ_lib}) {
697 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
700 my $timestamptz = $billing_ts->strftime('%FT%T%z');
701 my @cl = actor::org_unit::closed_date->search_where(
702 { close_start => { '<=' => $timestamptz },
703 close_end => { '>=' => $timestamptz },
704 org_unit => $c->circ_lib }
708 $current_fine_total += $recuring_fine;
709 $latest_amount += $recuring_fine;
710 $latest_billing_ts = $timestamptz;
712 money::billing->create(
714 note => "System Generated Overdue Fine",
715 billing_type => "Overdue materials",
716 amount => sprintf('%0.2f', $recuring_fine/100),
717 billing_ts => $timestamptz,
723 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
724 if ($latest_billing_ts and $latest_amount);
726 $self->method_lookup('open-ils.storage.transaction.commit')->run;
729 'open-ils.penalty.patron_penalty.calculate',
730 { patron => $c->usr->to_fieldmapper,
738 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
739 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
740 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
741 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
745 __PACKAGE__->register_method(
746 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
749 method => 'generate_fines',
754 sub new_hold_copy_targeter {
757 my $check_expire = shift;
758 my $one_hold = shift;
760 local $OpenILS::Application::Storage::WRITE = 1;
766 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
767 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
768 } elsif ( $check_expire ) {
770 # what's the retarget time threashold?
772 $check_expire ||= '12h';
773 $check_expire = interval_to_seconds( $check_expire );
775 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
778 my $expire_threshold = sprintf(
779 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
780 $year, $mon, $mday, $hour, $min, $sec
783 # find all the holds holds needing retargeting
784 $holds = [ action::hold_request->search_where(
785 { capture_time => undef,
786 fulfillment_time => undef,
787 cancel_time => undef,
789 prev_check_time => { '<=' => $expire_threshold },
791 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
793 # find all the holds holds needing first time targeting
794 push @$holds, action::hold_request->search(
795 capture_time => undef,
796 fulfillment_time => undef,
797 prev_check_time => undef,
799 cancel_time => undef,
800 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
803 # find all the holds holds needing first time targeting ONLY
804 $holds = [ action::hold_request->search(
805 capture_time => undef,
806 fulfillment_time => undef,
807 prev_check_time => undef,
808 cancel_time => undef,
810 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
814 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
817 my @closed = actor::org_unit::closed_date->search_where(
818 { close_start => { '<=', 'now' },
819 close_end => { '>=', 'now' } }
825 for my $hold (@$holds) {
827 #start a transaction if needed
828 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
829 $log->debug("Cleaning up after previous transaction\n");
830 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
832 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
833 $log->info("Processing hold ".$hold->id."...\n");
835 #first, re-fetch the hold, to make sure it's not captured already
836 $hold->remove_from_object_index();
837 $hold = action::hold_request->retrieve( $hold->id );
839 # remove old auto-targeting maps
840 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
841 $_->delete for (@oldmaps);
843 if ($hold->expire_time) {
844 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
845 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
846 $self->method_lookup('open-ils.storage.transaction.commit')->run;
849 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
853 # find filters for MR holds
854 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
856 # find all the potential copies
857 if ($hold->hold_type eq 'M') {
860 metabib::record_descriptor
864 isTrue($_->deleted) ? () : ($_->id)
865 } metabib::metarecord->retrieve($hold->target)->source_records
867 ( $types ? (item_type => [split '', $types]) : () ),
868 ( $formats ? (item_form => [split '', $formats]) : () ),
869 ( $lang ? (item_lang => $lang) : () ),
873 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
874 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
876 for my $cn ( @{ $rtree->call_numbers } ) {
878 asset::copy->search_where(
879 { id => [map {$_->id} @{ $cn->copies }],
881 ) if ($cn && @{ $cn->copies });
884 } elsif ($hold->hold_type eq 'T') {
886 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
887 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
890 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
894 for my $cn ( @{ $rtree->call_numbers } ) {
896 asset::copy->search_where(
897 { id => [map {$_->id} @{ $cn->copies }],
899 ) if ($cn && @{ $cn->copies });
901 } elsif ($hold->hold_type eq 'V') {
903 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
904 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
907 asset::copy->search_where(
908 { id => [map {$_->id} @{ $vtree->copies }],
910 ) if ($vtree && @{ $vtree->copies });
912 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
913 my $_cp = asset::copy->retrieve($hold->target);
914 push @$all_copies, $_cp if $_cp;
918 @$all_copies = grep { isTrue($_->status->holdable) &&
919 isTrue($_->location->holdable) &&
920 isTrue($_->holdable) &&
924 # let 'em know we're still working
925 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
927 # if we have no copies ...
928 if (!ref $all_copies || !@$all_copies) {
929 $log->info("\tNo copies available for targeting at all!\n");
930 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
932 $hold->update( { prev_check_time => 'today', current_copy => undef } );
933 $self->method_lookup('open-ils.storage.transaction.commit')->run;
937 my $copy_count = @$all_copies;
939 # map the potentials, so that we can pick up checkins
940 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
941 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
943 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
946 for my $c (@$all_copies) {
948 next if ($c->id eq $hold->current_copy);
951 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
953 # target of another hold
954 next if (action::hold_request
956 { current_copy => $c->id,
957 fulfillment_time => undef,
958 cancel_time => undef,
963 # we passed all three, keep it
964 push @good_copies, $c if ($c);
965 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
968 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
970 my $old_best = $hold->current_copy;
971 $hold->update({ current_copy => undef }) if ($old_best);
973 if (!scalar(@good_copies)) {
974 $log->info("\tNo (non-current) copies eligible to fill the hold.");
975 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
976 # the old copy is still available
977 $log->debug("\tPushing current_copy back onto the targeting list");
978 push @good_copies, $old_best;
980 # oops, old copy is not available
981 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
982 $hold->update( { prev_check_time => 'today' } );
983 $self->method_lookup('open-ils.storage.transaction.commit')->run;
984 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
989 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
994 $_->circ_lib == $hold->pickup_lib
998 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1000 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1001 my $best = choose_nearest_copy($hold, $prox_list);
1002 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1005 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1006 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1008 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1010 $best = choose_nearest_copy($hold, $prox_list);
1013 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1015 # hold wasn't fulfilled, record the fact
1017 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1018 action::unfulfilled_hold_list->create(
1019 { hold => ''.$hold->id,
1020 current_copy => ''.$old_best->id,
1021 circ_lib => ''.$old_best->circ_lib,
1026 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1027 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1030 action::hold_request
1032 { current_copy => $old_best->id,
1033 fulfillment_time => undef,
1034 cancel_time => undef,
1038 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1039 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1041 $hold->update( { prev_check_time => 'now' } );
1042 $log->info( "\tThere were no targetable copies for the hold" );
1045 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1046 $log->info("\tProcessing of hold ".$hold->id." complete.");
1049 { hold => $hold->id,
1050 old_target => ($old_best ? $old_best->id : undef),
1051 eligible_copies => $copy_count,
1052 target => ($best ? $best->id : undef) };
1057 $log->error("Processing of hold failed: $e");
1058 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1059 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1066 __PACKAGE__->register_method(
1067 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1069 method => 'new_hold_copy_targeter',
1074 my %cache = (titles => {}, cns => {});
1075 sub hold_copy_targeter {
1078 my $check_expire = shift;
1079 my $one_hold = shift;
1081 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1082 $self->{user_filter}->connect;
1083 $self->{client} = $client;
1086 $check_expire ||= '12h';
1087 $check_expire = interval_to_seconds( $check_expire );
1089 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1092 my $expire_threshold = sprintf(
1093 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1094 $year, $mon, $mday, $hour, $min, $sec
1098 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1100 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1104 %cache = (titles => {}, cns => {});
1108 $holds = [ action::hold_request->search(id => $one_hold) ];
1110 $holds = [ action::hold_request->search_where(
1111 { capture_time => undef,
1112 prev_check_time => { '<=' => $expire_threshold },
1114 { order_by => 'request_time,prev_check_time' } ) ];
1115 push @$holds, action::hold_request->search_where(
1116 { capture_time => undef,
1117 prev_check_time => undef,
1119 { order_by => 'request_time' } );
1121 } catch Error with {
1123 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1126 for my $hold (@$holds) {
1128 #action::hold_request->db_Main->begin_work;
1129 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1130 $client->respond("Cleaning up after previous transaction\n");
1131 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1133 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1134 $client->respond("Processing hold ".$hold->id."...\n");
1138 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1139 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1141 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1142 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1144 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1145 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1147 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1149 unless (ref $copies || !@$copies) {
1150 $client->respond("\tNo copies available for targeting at all!\n");
1154 for my $c (@$copies) {
1155 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1156 push @good_copies, $c if ($c);
1159 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1161 my $old_best = $hold->current_copy;
1162 $hold->update({ current_copy => undef });
1164 if (!scalar(@good_copies)) {
1165 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1166 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1167 $client->respond("\tPushing current_copy back onto the targeting list\n");
1168 push @good_copies, asset::copy->retrieve( $old_best );
1170 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1176 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1177 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1179 my $best = choose_nearest_copy($hold, $prox_list);
1182 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1183 $best = choose_nearest_copy($hold, $prox_list);
1187 # hold wasn't fulfilled, record the fact
1189 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1190 action::unfulfilled_hold_list->create(
1191 { hold => ''.$hold->id,
1192 current_copy => ''.$old_best->id,
1193 circ_lib => ''.$old_best->circ_lib,
1198 $hold->update( { current_copy => ''.$best->id } );
1199 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1202 $hold->update( { prev_check_time => 'now' } );
1203 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1205 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1206 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1208 #action::hold_request->dbi_commit;
1212 $log->error("Processing of hold failed: $e");
1213 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1214 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1215 #action::hold_request->dbi_rollback;
1219 $self->{user_filter}->disconnect;
1220 $self->{user_filter}->finish;
1221 delete $$self{user_filter};
1224 __PACKAGE__->register_method(
1225 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1228 method => 'hold_copy_targeter',
1232 sub copy_hold_capture {
1237 if (!defined($cps)) {
1239 $cps = [ asset::copy->search( id => $hold->target ) ];
1240 } catch Error with {
1242 die "Could not retrieve initial volume list:\n\n$e\n";
1246 my @copies = grep { $_->holdable } @$cps;
1248 for (my $i = 0; $i < @$cps; $i++) {
1249 next unless $$cps[$i];
1251 my $cn = $cache{cns}{$copies[$i]->call_number};
1252 my $rec = $cache{titles}{$cn->record};
1253 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1254 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1255 $copies[$i] = undef if (
1257 !$self->{user_filter}->request(
1258 'open-ils.circ.permit_hold',
1259 $hold->to_fieldmapper, do {
1260 my $cp_fm = $copies[$i]->to_fieldmapper;
1261 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1262 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1263 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1266 { title => $rec->to_fieldmapper,
1267 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1268 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1271 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1274 @copies = grep { $_ } @copies;
1276 my $count = @copies;
1278 return unless ($count);
1280 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1283 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1284 for my $c (@copies) {
1285 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1287 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1293 sub choose_nearest_copy {
1295 my $prox_list = shift;
1297 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1298 next unless (ref $$prox_list[$p]);
1300 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1301 next unless (@capturable);
1303 my $rand = int(rand(scalar(@capturable)));
1304 while (my ($c) = splice(@capturable,$rand)) {
1305 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1306 { title => $c->call_number->record->to_fieldmapper,
1307 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1308 patron => $hold->usr->to_fieldmapper,
1309 copy => $c->to_fieldmapper,
1310 requestor => $hold->requestor->to_fieldmapper,
1311 request_lib => $hold->request_lib->to_fieldmapper,
1312 pickup_lib => $hold->pickup_lib->id,
1316 last unless(@capturable);
1317 $rand = int(rand(scalar(@capturable)));
1322 sub create_prox_list {
1328 for my $cp (@$copies) {
1329 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1330 next unless (defined($prox));
1331 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1332 push @{$prox_list[$prox]}, $cp;
1337 sub volume_hold_capture {
1342 if (!defined($vols)) {
1344 $vols = [ asset::call_number->search( id => $hold->target ) ];
1345 $cache{cns}{$_->id} = $_ for (@$vols);
1346 } catch Error with {
1348 die "Could not retrieve initial volume list:\n\n$e\n";
1352 my @v_ids = map { $_->id } @$vols;
1356 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1358 } catch Error with {
1360 warn "Could not retrieve copy list:\n\n$e\n";
1363 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1366 sub title_hold_capture {
1371 if (!defined($titles)) {
1373 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1374 $cache{titles}{$_->id} = $_ for (@$titles);
1375 } catch Error with {
1377 die "Could not retrieve initial title list:\n\n$e\n";
1381 my @t_ids = map { $_->id } @$titles;
1384 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1386 } catch Error with {
1388 warn "Could not retrieve volume list:\n\n$e\n";
1391 $cache{cns}{$_->id} = $_ for (@$cn_list);
1393 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1396 sub metarecord_hold_capture {
1402 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1404 } catch Error with {
1406 die "Could not retrieve initial title list:\n\n$e\n";
1410 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1412 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1414 } catch Error with {
1416 die "Could not retrieve format-pruned title list:\n\n$e\n";
1420 $cache{titles}{$_->id} = $_ for (@$titles);
1421 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);