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;
13 my $parser = DateTime::Format::ISO8601->new;
14 my $log = 'OpenSRF::Utils::Logger';
16 sub open_noncat_circs {
21 my $a = action::non_cataloged_circulation->table;
22 my $c = config::non_cataloged_type->table;
27 JOIN $c c ON (a.item_type = c.id)
28 WHERE a.circ_time + c.circ_duration > current_timestamp
32 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
34 __PACKAGE__->register_method(
35 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
38 method => 'open_noncat_circs',
42 sub ou_hold_requests {
47 my $h_table = action::hold_request->table;
48 my $c_table = asset::copy->table;
49 my $o_table = actor::org_unit->table;
54 JOIN $c_table cp ON (cp.id = h.current_copy)
55 JOIN $o_table ou ON (ou.id = cp.circ_lib)
57 AND h.capture_time IS NULL
58 AND h.cancel_time IS NULL
59 ORDER BY h.request_time
62 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
65 $client->respond($_) for (
68 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
72 } @{ $sth->fetchall_arrayref }
76 __PACKAGE__->register_method(
77 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
81 method => 'ou_hold_requests',
88 my $c_t = action::circulation->table;
90 $grace = " - ($grace * (fine_interval))" if ($grace);
95 WHERE stop_fines IS NULL
96 AND due_date < ( CURRENT_TIMESTAMP $grace)
99 my $sth = action::circulation->db_Main->prepare_cached($sql);
102 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
106 sub complete_reshelving {
111 local $OpenILS::Application::Storage::WRITE = 1;
113 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
114 unless (interval_to_seconds( $window ));
116 my $circ = action::circulation->table;
117 my $cp = asset::copy->table;
122 WHERE id IN ( SELECT cp.id
124 JOIN $circ circ ON (circ.target_copy = cp.id)
125 WHERE circ.checkin_time IS NOT NULL
126 AND circ.checkin_time < NOW() - CAST(? AS INTERVAL)
130 my $sth = action::circulation->db_Main->prepare_cached($sql);
131 $sth->execute($window);
136 __PACKAGE__->register_method(
137 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
141 method => 'complete_reshelving',
147 my $grace = shift || '';
149 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
154 __PACKAGE__->register_method(
155 api_name => 'open-ils.storage.action.circulation.overdue',
158 method => 'grab_overdue',
166 my $limit = int(shift()) || 10;
168 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
170 FROM action.hold_request h
171 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
172 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
173 WHERE hm.target_copy = ?
175 AND h.capture_time IS NULL
176 AND h.cancel_time IS NULL
179 h.selection_depth DESC,
185 __PACKAGE__->register_method(
186 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
189 method => 'nearest_hold',
192 sub next_resp_group_id {
196 # XXX This is not replication safe!!!
198 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
199 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
203 __PACKAGE__->register_method(
204 api_name => 'open-ils.storage.action.survey_response.next_group_id',
206 method => 'next_resp_group_id',
209 sub patron_circ_summary {
214 return undef unless ($id);
215 my $c_table = action::circulation->table;
216 my $b_table = money::billing->table;
218 $log->debug("Retrieving patron summary for id $id", DEBUG);
220 my $select = <<" SQL";
221 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
223 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
225 AND c.xact_finish IS NULL
227 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
228 OR c.stop_fines IS NULL
232 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
234 __PACKAGE__->register_method(
235 api_name => 'open-ils.storage.action.circulation.patron_summary',
237 method => 'patron_circ_summary',
240 #XXX Fix stored proc calls
241 sub find_local_surveys {
246 return undef unless ($ou);
247 my $s_table = action::survey->table;
249 my $select = <<" SQL";
252 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
253 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
256 my $sth = action::survey->db_Main->prepare_cached($select);
259 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
263 __PACKAGE__->register_method(
264 api_name => 'open-ils.storage.action.survey.all',
267 method => 'find_local_surveys',
270 #XXX Fix stored proc calls
271 sub find_opac_surveys {
276 return undef unless ($ou);
277 my $s_table = action::survey->table;
279 my $select = <<" SQL";
282 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
283 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
287 my $sth = action::survey->db_Main->prepare_cached($select);
290 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
294 __PACKAGE__->register_method(
295 api_name => 'open-ils.storage.action.survey.opac',
298 method => 'find_opac_surveys',
305 my $limit = shift || 10;
306 my $offset = shift || 0;
308 return undef unless ($ou);
309 my $h_table = action::hold_request->table;
310 my $a_table = asset::copy->table;
312 my $idlist = 1 if ($self->api_name =~/id_list/o);
314 my $select = <<" SQL";
317 JOIN $a_table a ON (h.current_copy = a.id)
319 AND h.capture_time IS NULL
320 AND h.cancel_time IS NULL
321 ORDER BY h.request_time ASC
326 my $sth = action::survey->db_Main->prepare_cached($select);
330 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
332 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
337 __PACKAGE__->register_method(
338 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
342 "Returns the hold ids for a specific library's pull list.",
343 [ [org_unit => "The library's org id", "number"],
344 [limit => 'An optional page size, defaults to 10', 'number'],
345 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
347 ['A list of holds for the stated library to pull for', 'array']
349 method => 'hold_pull_list',
351 __PACKAGE__->register_method(
352 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
356 "Returns the holds for a specific library's pull list.",
357 [ [org_unit => "The library's org id", "number"],
358 [limit => 'An optional page size, defaults to 10', 'number'],
359 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
361 ['A list of holds for the stated library to pull for', 'array']
363 method => 'hold_pull_list',
366 sub find_optional_surveys {
371 return undef unless ($ou);
372 my $s_table = action::survey->table;
374 my $select = <<" SQL";
377 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
378 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
379 AND s.required IS FALSE;
382 my $sth = action::survey->db_Main->prepare_cached($select);
385 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
389 __PACKAGE__->register_method(
390 api_name => 'open-ils.storage.action.survey.optional',
393 method => 'find_optional_surveys',
396 sub find_required_surveys {
401 return undef unless ($ou);
402 my $s_table = action::survey->table;
404 my $select = <<" SQL";
407 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
408 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
409 AND s.required IS TRUE;
412 my $sth = action::survey->db_Main->prepare_cached($select);
415 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
419 __PACKAGE__->register_method(
420 api_name => 'open-ils.storage.action.survey.required',
423 method => 'find_required_surveys',
426 sub find_usr_summary_surveys {
431 return undef unless ($ou);
432 my $s_table = action::survey->table;
434 my $select = <<" SQL";
437 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
438 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
439 AND s.usr_summary IS TRUE;
442 my $sth = action::survey->db_Main->prepare_cached($select);
445 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
449 __PACKAGE__->register_method(
450 api_name => 'open-ils.storage.action.survey.usr_summary',
453 method => 'find_usr_summary_surveys',
462 my $overbill = shift;
464 local $OpenILS::Application::Storage::WRITE = 1;
468 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
470 push @circs, overdue_circs($grace);
473 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
475 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
479 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
480 $log->debug("Cleaning up after previous transaction\n");
481 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
483 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
484 $log->info("Processing circ ".$c->id."...\n");
487 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
489 my $due = $due_dt->epoch;
491 my $fine_interval = interval_to_seconds( $c->fine_interval );
493 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
495 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
496 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
499 $due -= ($due % $fine_interval) + $tz_offset_s;
500 $now -= ($now % $fine_interval) + $tz_offset_s;
504 "ARG! Overdue circulation ".$c->id.
505 " for item ".$c->target_copy.
506 " (user ".$c->usr.").\n".
507 "\tItem was due on or before: ".localtime($due)."\n");
509 my @fines = money::billing->search_where(
510 { xact => $c->id, billing_type => 'Overdue materials' },
511 { order_by => 'billing_ts DESC'}
515 my $fine = $fines[$f_idx] if (@fines);
517 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
520 my $current_fine_total = 0;
521 $current_fine_total += $_->amount for (grep { $_ and !$_->voided } @fines);
525 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
526 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
530 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
531 #$last_fine += $fine_interval * $grace;
534 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
535 if ($pending_fine_count < 1) {
536 $client->respond( "\tNo fines to create. " );
537 if ($grace && $now < $due + $fine_interval * $grace) {
538 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
540 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
545 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
547 my ($latest_billing_ts, $latest_amount);
548 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
550 if ($current_fine_total > $c->max_fine) {
551 $c->update({stop_fines => 'MAXFINES'});
553 "\tMaximum fine level of ".$c->max_fine.
554 " reached for this circulation.\n".
555 "\tNo more fines will be generated.\n" );
559 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
561 my $dow = $billing_ts->dow;
562 my $dow_open = "dow_${dow}_open";
563 my $dow_close = "dow_${dow}_close";
565 if (my $h = $hoo{$c->circ_lib}) {
566 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
569 my $timestamptz = $billing_ts->strftime('%FT%T%z');
570 my @cl = actor::org_unit::closed_date->search_where(
571 { close_start => { '<=' => $timestamptz },
572 close_end => { '>=' => $timestamptz },
573 org_unit => $c->circ_lib }
577 $current_fine_total += $c->recuring_fine;
578 $latest_amount += $c->recuring_fine;
579 $latest_billing_ts = $timestamptz;
581 $client->respond( "\t\tAdding aggregate fine of ".$c->recuring_fine." for period starting ".$$timestamptz."\n" );
584 money::billing->create(
586 note => "System Generated Overdue Fine",
587 billing_type => "Overdue materials",
588 amount => ''.$latest_amount
589 billing_ts => $latest_billing_ts,
591 ) if ($latest_billing_ts and $latest_amount > 0.0);
594 $self->method_lookup('open-ils.storage.transaction.commit')->run;
597 'open-ils.penalty.patron_penalty.calculate',
598 { patron => $c->usr->to_fieldmapper,
606 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
607 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
608 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
609 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
613 __PACKAGE__->register_method(
614 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
617 method => 'generate_fines',
622 sub new_hold_copy_targeter {
625 my $check_expire = shift;
626 my $one_hold = shift;
628 local $OpenILS::Application::Storage::WRITE = 1;
634 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
635 } elsif ( $check_expire ) {
638 $check_expire ||= '12h';
639 $check_expire = interval_to_seconds( $check_expire );
641 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
644 my $expire_threshold = sprintf(
645 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
646 $year, $mon, $mday, $hour, $min, $sec
649 $holds = [ action::hold_request->search_where(
650 { capture_time => undef,
651 fulfillment_time => undef,
652 cancel_time => undef,
653 prev_check_time => { '<=' => $expire_threshold },
655 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
656 push @$holds, action::hold_request->search(
657 capture_time => undef,
658 fulfillment_time => undef,
659 prev_check_time => undef,
660 cancel_time => undef,
661 { order_by => 'selection_depth DESC, request_time' } );
663 $holds = [ action::hold_request->search(
664 capture_time => undef,
665 fulfillment_time => undef,
666 prev_check_time => undef,
667 cancel_time => undef,
668 { order_by => 'selection_depth DESC, request_time' } ) ];
672 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
677 for my $hold (@$holds) {
679 #action::hold_request->db_Main->begin_work;
680 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
681 $log->debug("Cleaning up after previous transaction\n");
682 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
684 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
685 $log->info("Processing hold ".$hold->id."...\n");
687 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
688 $_->delete for (@oldmaps);
693 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
695 # find all the potential copies
696 if ($hold->hold_type eq 'M') {
699 metabib::record_descriptor
701 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
702 ( $types ? (item_type => [split '', $types]) : () ),
703 ( $formats ? (item_form => [split '', $formats]) : () ),
704 ( $lang ? (item_lang => $lang) : () ),
708 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
709 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
711 for my $cn ( @{ $rtree->call_numbers } ) {
713 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
716 } elsif ($hold->hold_type eq 'T') {
718 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
719 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
722 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
726 for my $cn ( @{ $rtree->call_numbers } ) {
728 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
730 } elsif ($hold->hold_type eq 'V') {
732 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
733 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
736 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
738 } elsif ($hold->hold_type eq 'C') {
740 $all_copies = [asset::copy->retrieve($hold->target)];
743 @$all_copies = grep { $_->status->holdable &&
744 $_->location->holdable &&
748 # let 'em know we're still working
749 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
751 if (!ref $all_copies || !@$all_copies) {
752 $log->info("\tNo copies available for targeting at all!\n");
753 $self->method_lookup('open-ils.storage.transaction.commit')->run;
754 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
758 my $copy_count = @$all_copies;
760 # map the potentials, so that we can pick up checkins
761 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
762 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
764 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
766 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
769 my $today= sprintf( '%s-%0.2d-%0.2d', $year, $mon, $mday );
771 my @closed = actor::org_unit::closed_date->search_where(
772 { close_start => { '<=', $today },
773 close_end => { '>=', $today } }
777 for my $c (@$all_copies) {
778 next if ($c->id == $hold->current_copy);
779 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
780 next if (action::hold_request
782 { current_copy => $c->id,
783 capture_time => undef,
784 cancel_time => undef,
788 push @good_copies, $c if ($c);
789 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
792 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
794 my $old_best = $hold->current_copy;
795 $hold->update({ current_copy => undef });
797 if (!scalar(@good_copies)) {
798 $log->info("\tNo (non-current) copies eligible to fill the hold.");
801 grep { $old_best eq $_ } @$all_copies &&
802 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
804 $log->debug("\tPushing current_copy back onto the targeting list");
805 push @good_copies, $old_best;
807 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
808 $self->method_lookup('open-ils.storage.transaction.commit')->run;
809 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
814 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
819 $_->circ_lib == $hold->pickup_lib
823 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
825 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
826 my $best = choose_nearest_copy($hold, $prox_list);
827 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
830 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
831 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
833 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
835 $best = choose_nearest_copy($hold, $prox_list);
838 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
840 # hold wasn't fulfilled, record the fact
842 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
843 action::unfulfilled_hold_list->create(
844 { hold => ''.$hold->id,
845 current_copy => ''.$old_best->id,
846 circ_lib => ''.$old_best->circ_lib,
851 $hold->update( { current_copy => ''.$best->id } );
852 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
854 $log->info( "\tThere were no targetable copies for the hold" );
857 $hold->update( { prev_check_time => 'now' } );
859 $self->method_lookup('open-ils.storage.transaction.commit')->run;
860 $log->info("\tProcessing of hold ".$hold->id." complete.");
864 old_target => ($old_best ? $old_best->id : undef),
865 eligible_copies => $copy_count,
866 target => ($best ? $best->id : undef) };
871 $log->error("Processing of hold failed: $e");
872 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
879 __PACKAGE__->register_method(
880 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
882 method => 'new_hold_copy_targeter',
887 my %cache = (titles => {}, cns => {});
888 sub hold_copy_targeter {
891 my $check_expire = shift;
892 my $one_hold = shift;
894 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
895 $self->{user_filter}->connect;
896 $self->{client} = $client;
899 $check_expire ||= '12h';
900 $check_expire = interval_to_seconds( $check_expire );
902 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
905 my $expire_threshold = sprintf(
906 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
907 $year, $mon, $mday, $hour, $min, $sec
911 $statuses ||= [ config::copy_status->search(holdable => 't') ];
913 $locations ||= [ asset::copy_location->search(holdable => 't') ];
917 %cache = (titles => {}, cns => {});
921 $holds = [ action::hold_request->search(id => $one_hold) ];
923 $holds = [ action::hold_request->search_where(
924 { capture_time => undef,
925 prev_check_time => { '<=' => $expire_threshold },
927 { order_by => 'request_time,prev_check_time' } ) ];
928 push @$holds, action::hold_request->search_where(
929 { capture_time => undef,
930 prev_check_time => undef,
932 { order_by => 'request_time' } );
936 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
939 for my $hold (@$holds) {
941 #action::hold_request->db_Main->begin_work;
942 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
943 $client->respond("Cleaning up after previous transaction\n");
944 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
946 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
947 $client->respond("Processing hold ".$hold->id."...\n");
951 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
952 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
954 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
955 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
957 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
958 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
960 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
962 unless (ref $copies || !@$copies) {
963 $client->respond("\tNo copies available for targeting at all!\n");
967 for my $c (@$copies) {
968 next if ( grep {$c->id == $hold->current_copy} @good_copies);
969 push @good_copies, $c if ($c);
972 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
974 my $old_best = $hold->current_copy;
975 $hold->update({ current_copy => undef });
977 if (!scalar(@good_copies)) {
978 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
979 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
980 $client->respond("\tPushing current_copy back onto the targeting list\n");
981 push @good_copies, asset::copy->retrieve( $old_best );
983 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
989 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
990 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
992 my $best = choose_nearest_copy($hold, $prox_list);
995 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
996 $best = choose_nearest_copy($hold, $prox_list);
1000 # hold wasn't fulfilled, record the fact
1002 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1003 action::unfulfilled_hold_list->create(
1004 { hold => ''.$hold->id,
1005 current_copy => ''.$old_best->id,
1006 circ_lib => ''.$old_best->circ_lib,
1011 $hold->update( { current_copy => ''.$best->id } );
1012 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1015 $hold->update( { prev_check_time => 'now' } );
1016 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1018 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1019 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1021 #action::hold_request->dbi_commit;
1025 $log->error("Processing of hold failed: $e");
1026 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1027 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1028 #action::hold_request->dbi_rollback;
1032 $self->{user_filter}->disconnect;
1033 $self->{user_filter}->finish;
1034 delete $$self{user_filter};
1037 __PACKAGE__->register_method(
1038 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1041 method => 'hold_copy_targeter',
1045 sub copy_hold_capture {
1050 if (!defined($cps)) {
1052 $cps = [ asset::copy->search( id => $hold->target ) ];
1053 } catch Error with {
1055 die "Could not retrieve initial volume list:\n\n$e\n";
1059 my @copies = grep { $_->holdable } @$cps;
1061 for (my $i = 0; $i < @$cps; $i++) {
1062 next unless $$cps[$i];
1064 my $cn = $cache{cns}{$copies[$i]->call_number};
1065 my $rec = $cache{titles}{$cn->record};
1066 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1067 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1068 $copies[$i] = undef if (
1070 !$self->{user_filter}->request(
1071 'open-ils.circ.permit_hold',
1072 $hold->to_fieldmapper, do {
1073 my $cp_fm = $copies[$i]->to_fieldmapper;
1074 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1075 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1076 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1079 { title => $rec->to_fieldmapper,
1080 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1081 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1084 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1087 @copies = grep { $_ } @copies;
1089 my $count = @copies;
1091 return unless ($count);
1093 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1096 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1097 for my $c (@copies) {
1098 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1100 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1106 sub choose_nearest_copy {
1108 my $prox_list = shift;
1110 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1111 next unless (ref $$prox_list[$p]);
1113 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1114 next unless (@capturable);
1116 my $rand = int(rand(scalar(@capturable)));
1117 while (my ($c) = splice(@capturable,$rand)) {
1118 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1119 { title => $c->call_number->record->to_fieldmapper,
1120 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1121 patron => $hold->usr->to_fieldmapper,
1122 copy => $c->to_fieldmapper,
1123 requestor => $hold->requestor->to_fieldmapper,
1124 request_lib => $hold->request_lib->to_fieldmapper,
1127 last unless(@capturable);
1128 $rand = int(rand(scalar(@capturable)));
1136 sub create_prox_list {
1142 for my $cp (@$copies) {
1143 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1144 next unless (defined($prox));
1145 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1146 push @{$prox_list[$prox]}, $cp;
1151 sub volume_hold_capture {
1156 if (!defined($vols)) {
1158 $vols = [ asset::call_number->search( id => $hold->target ) ];
1159 $cache{cns}{$_->id} = $_ for (@$vols);
1160 } catch Error with {
1162 die "Could not retrieve initial volume list:\n\n$e\n";
1166 my @v_ids = map { $_->id } @$vols;
1170 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1172 } catch Error with {
1174 warn "Could not retrieve copy list:\n\n$e\n";
1177 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1180 sub title_hold_capture {
1185 if (!defined($titles)) {
1187 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1188 $cache{titles}{$_->id} = $_ for (@$titles);
1189 } catch Error with {
1191 die "Could not retrieve initial title list:\n\n$e\n";
1195 my @t_ids = map { $_->id } @$titles;
1198 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1200 } catch Error with {
1202 warn "Could not retrieve volume list:\n\n$e\n";
1205 $cache{cns}{$_->id} = $_ for (@$cn_list);
1207 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1210 sub metarecord_hold_capture {
1216 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1218 } catch Error with {
1220 die "Could not retrieve initial title list:\n\n$e\n";
1224 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1226 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1228 } catch Error with {
1230 die "Could not retrieve format-pruned title list:\n\n$e\n";
1234 $cache{titles}{$_->id} = $_ for (@$titles);
1235 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);