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);
329 $client->respond( $id_list ? $_->id : $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
333 __PACKAGE__->register_method(
334 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
338 "Returns the hold ids for a specific library's pull list.",
339 [ [org_unit => "The library's org id", "number"],
340 [limit => 'An optional page size, defaults to 10', 'number'],
341 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
343 ['A list of holds for the stated library to pull for', 'array']
345 method => 'hold_pull_list',
347 __PACKAGE__->register_method(
348 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
352 "Returns the holds for a specific library's pull list.",
353 [ [org_unit => "The library's org id", "number"],
354 [limit => 'An optional page size, defaults to 10', 'number'],
355 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
357 ['A list of holds for the stated library to pull for', 'array']
359 method => 'hold_pull_list',
362 sub find_optional_surveys {
367 return undef unless ($ou);
368 my $s_table = action::survey->table;
370 my $select = <<" SQL";
373 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
374 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
375 AND s.required IS FALSE;
378 my $sth = action::survey->db_Main->prepare_cached($select);
381 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
385 __PACKAGE__->register_method(
386 api_name => 'open-ils.storage.action.survey.optional',
389 method => 'find_optional_surveys',
392 sub find_required_surveys {
397 return undef unless ($ou);
398 my $s_table = action::survey->table;
400 my $select = <<" SQL";
403 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
404 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
405 AND s.required IS TRUE;
408 my $sth = action::survey->db_Main->prepare_cached($select);
411 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
415 __PACKAGE__->register_method(
416 api_name => 'open-ils.storage.action.survey.required',
419 method => 'find_required_surveys',
422 sub find_usr_summary_surveys {
427 return undef unless ($ou);
428 my $s_table = action::survey->table;
430 my $select = <<" SQL";
433 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
434 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
435 AND s.usr_summary IS TRUE;
438 my $sth = action::survey->db_Main->prepare_cached($select);
441 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
445 __PACKAGE__->register_method(
446 api_name => 'open-ils.storage.action.survey.usr_summary',
449 method => 'find_usr_summary_surveys',
458 my $overbill = shift;
460 local $OpenILS::Application::Storage::WRITE = 1;
464 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
466 push @circs, overdue_circs($grace);
469 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
471 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
475 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
476 $log->debug("Cleaning up after previous transaction\n");
477 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
479 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
480 $log->info("Processing circ ".$c->id."...\n");
483 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
485 my $due = $due_dt->epoch;
487 my $fine_interval = interval_to_seconds( $c->fine_interval );
489 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
491 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
492 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
495 $due -= ($due % $fine_interval) + $tz_offset_s;
496 $now -= ($now % $fine_interval) + $tz_offset_s;
500 "ARG! Overdue circulation ".$c->id.
501 " for item ".$c->target_copy.
502 " (user ".$c->usr.").\n".
503 "\tItem was due on or before: ".localtime($due)."\n");
505 my @fines = money::billing->search_where(
506 { xact => $c->id, billing_type => 'Overdue materials' },
507 { order_by => 'billing_ts DESC'}
511 my $fine = $fines[$f_idx] if (@fines);
513 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
516 my $current_fine_total = 0;
517 $current_fine_total += $_->amount for (grep { $_ and !$_->voided } @fines);
521 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
522 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
526 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
527 #$last_fine += $fine_interval * $grace;
530 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
531 if ($pending_fine_count < 1) {
532 $client->respond( "\tNo fines to create. " );
533 if ($grace && $now < $due + $fine_interval * $grace) {
534 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
536 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
541 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
543 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
545 if ($current_fine_total > $c->max_fine) {
546 $c->update({stop_fines => 'MAXFINES'});
548 "\tMaximum fine level of ".$c->max_fine.
549 " reached for this circulation.\n".
550 "\tNo more fines will be generated.\n" );
554 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
556 my $dow = $billing_ts->dow;
557 my $dow_open = "dow_${dow}_open";
558 my $dow_close = "dow_${dow}_close";
560 if (my $h = $hoo{$c->circ_lib}) {
561 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
564 my $timestamptz = $billing_ts->strftime('%FT%T%z');
565 my @cl = actor::org_unit::closed_date->search_where(
566 { close_start => { '<=' => $timestamptz },
567 close_end => { '>=' => $timestamptz },
568 org_unit => $c->circ_lib }
572 my $billing = money::billing->create(
574 note => "System Generated Overdue Fine",
575 billing_type => "Overdue materials",
576 amount => ''.$c->recuring_fine,
577 billing_ts => $timestamptz,
581 $current_fine_total += $billing->amount;
583 $client->respond( "\t\tCreating fine of ".$billing->amount." for period starting ".$billing->billing_ts."\n" );
586 $self->method_lookup('open-ils.storage.transaction.commit')->run;
589 'open-ils.penalty.patron_penalty.calculate',
590 { patron => $c->usr->to_fieldmapper,
598 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
599 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
600 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
604 __PACKAGE__->register_method(
605 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
608 method => 'generate_fines',
613 sub new_hold_copy_targeter {
616 my $check_expire = shift;
617 my $one_hold = shift;
619 local $OpenILS::Application::Storage::WRITE = 1;
625 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
626 } elsif ( $check_expire ) {
629 $check_expire ||= '12h';
630 $check_expire = interval_to_seconds( $check_expire );
632 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
635 my $expire_threshold = sprintf(
636 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
637 $year, $mon, $mday, $hour, $min, $sec
640 $holds = [ action::hold_request->search_where(
641 { capture_time => undef,
642 fulfillment_time => undef,
643 cancel_time => undef,
644 prev_check_time => { '<=' => $expire_threshold },
646 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
647 push @$holds, action::hold_request->search(
648 capture_time => undef,
649 fulfillment_time => undef,
650 prev_check_time => undef,
651 cancel_time => undef,
652 { order_by => 'selection_depth DESC, request_time' } );
654 $holds = [ action::hold_request->search(
655 capture_time => undef,
656 fulfillment_time => undef,
657 prev_check_time => undef,
658 cancel_time => undef,
659 { order_by => 'selection_depth DESC, request_time' } ) ];
663 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
668 for my $hold (@$holds) {
670 #action::hold_request->db_Main->begin_work;
671 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
672 $log->debug("Cleaning up after previous transaction\n");
673 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
675 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
676 $log->info("Processing hold ".$hold->id."...\n");
678 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
679 $_->delete for (@oldmaps);
684 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
686 # find all the potential copies
687 if ($hold->hold_type eq 'M') {
690 metabib::record_descriptor
692 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
693 ( $types ? (item_type => [split '', $types]) : () ),
694 ( $formats ? (item_form => [split '', $formats]) : () ),
695 ( $lang ? (item_lang => $lang) : () ),
699 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
700 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
702 for my $cn ( @{ $rtree->call_numbers } ) {
704 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
707 } elsif ($hold->hold_type eq 'T') {
709 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
710 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
713 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
717 for my $cn ( @{ $rtree->call_numbers } ) {
719 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
721 } elsif ($hold->hold_type eq 'V') {
723 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
724 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
727 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
729 } elsif ($hold->hold_type eq 'C') {
731 $all_copies = [asset::copy->retrieve($hold->target)];
734 @$all_copies = grep { $_->status->holdable &&
735 $_->location->holdable &&
739 # let 'em know we're still working
740 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
742 if (!ref $all_copies || !@$all_copies) {
743 $log->info("\tNo copies available for targeting at all!\n");
744 $self->method_lookup('open-ils.storage.transaction.commit')->run;
745 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
749 my $copy_count = @$all_copies;
751 # map the potentials, so that we can pick up checkins
752 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
753 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
755 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
757 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
760 my $today= sprintf( '%s-%0.2d-%0.2d', $year, $mon, $mday );
762 my @closed = actor::org_unit::closed_date->search_where(
763 { close_start => { '<=', $today },
764 close_end => { '>=', $today } }
768 for my $c (@$all_copies) {
769 next if ($c->id == $hold->current_copy);
770 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
771 next if (action::hold_request
773 { current_copy => $c->id,
774 capture_time => undef,
775 cancel_time => undef,
779 push @good_copies, $c if ($c);
780 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
783 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
785 my $old_best = $hold->current_copy;
786 $hold->update({ current_copy => undef });
788 if (!scalar(@good_copies)) {
789 $log->info("\tNo (non-current) copies eligible to fill the hold.");
792 grep { $old_best eq $_ } @$all_copies &&
793 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
795 $log->debug("\tPushing current_copy back onto the targeting list");
796 push @good_copies, $old_best;
798 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
799 $self->method_lookup('open-ils.storage.transaction.commit')->run;
800 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
805 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
810 $_->circ_lib == $hold->pickup_lib
814 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
816 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
817 my $best = choose_nearest_copy($hold, $prox_list);
818 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
821 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
822 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
824 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
826 $best = choose_nearest_copy($hold, $prox_list);
829 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
831 # hold wasn't fulfilled, record the fact
833 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
834 action::unfulfilled_hold_list->create(
835 { hold => ''.$hold->id,
836 current_copy => ''.$old_best->id,
837 circ_lib => ''.$old_best->circ_lib,
842 $hold->update( { current_copy => ''.$best->id } );
843 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
845 $log->info( "\tThere were no targetable copies for the hold" );
848 $hold->update( { prev_check_time => 'now' } );
850 $self->method_lookup('open-ils.storage.transaction.commit')->run;
851 $log->info("\tProcessing of hold ".$hold->id." complete.");
855 old_target => ($old_best ? $old_best->id : undef),
856 eligible_copies => $copy_count,
857 target => ($best ? $best->id : undef) };
862 $log->error("Processing of hold failed: $e");
863 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
870 __PACKAGE__->register_method(
871 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
873 method => 'new_hold_copy_targeter',
878 my %cache = (titles => {}, cns => {});
879 sub hold_copy_targeter {
882 my $check_expire = shift;
883 my $one_hold = shift;
885 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
886 $self->{user_filter}->connect;
887 $self->{client} = $client;
890 $check_expire ||= '12h';
891 $check_expire = interval_to_seconds( $check_expire );
893 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
896 my $expire_threshold = sprintf(
897 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
898 $year, $mon, $mday, $hour, $min, $sec
902 $statuses ||= [ config::copy_status->search(holdable => 't') ];
904 $locations ||= [ asset::copy_location->search(holdable => 't') ];
908 %cache = (titles => {}, cns => {});
912 $holds = [ action::hold_request->search(id => $one_hold) ];
914 $holds = [ action::hold_request->search_where(
915 { capture_time => undef,
916 prev_check_time => { '<=' => $expire_threshold },
918 { order_by => 'request_time,prev_check_time' } ) ];
919 push @$holds, action::hold_request->search_where(
920 { capture_time => undef,
921 prev_check_time => undef,
923 { order_by => 'request_time' } );
927 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
930 for my $hold (@$holds) {
932 #action::hold_request->db_Main->begin_work;
933 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
934 $client->respond("Cleaning up after previous transaction\n");
935 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
937 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
938 $client->respond("Processing hold ".$hold->id."...\n");
942 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
943 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
945 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
946 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
948 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
949 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
951 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
953 unless (ref $copies || !@$copies) {
954 $client->respond("\tNo copies available for targeting at all!\n");
958 for my $c (@$copies) {
959 next if ( grep {$c->id == $hold->current_copy} @good_copies);
960 push @good_copies, $c if ($c);
963 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
965 my $old_best = $hold->current_copy;
966 $hold->update({ current_copy => undef });
968 if (!scalar(@good_copies)) {
969 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
970 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
971 $client->respond("\tPushing current_copy back onto the targeting list\n");
972 push @good_copies, asset::copy->retrieve( $old_best );
974 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
980 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
981 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
983 my $best = choose_nearest_copy($hold, $prox_list);
986 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
987 $best = choose_nearest_copy($hold, $prox_list);
991 # hold wasn't fulfilled, record the fact
993 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
994 action::unfulfilled_hold_list->create(
995 { hold => ''.$hold->id,
996 current_copy => ''.$old_best->id,
997 circ_lib => ''.$old_best->circ_lib,
1002 $hold->update( { current_copy => ''.$best->id } );
1003 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1006 $hold->update( { prev_check_time => 'now' } );
1007 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1009 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1010 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1012 #action::hold_request->dbi_commit;
1016 $log->error("Processing of hold failed: $e");
1017 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1018 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1019 #action::hold_request->dbi_rollback;
1023 $self->{user_filter}->disconnect;
1024 $self->{user_filter}->finish;
1025 delete $$self{user_filter};
1028 __PACKAGE__->register_method(
1029 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1032 method => 'hold_copy_targeter',
1036 sub copy_hold_capture {
1041 if (!defined($cps)) {
1043 $cps = [ asset::copy->search( id => $hold->target ) ];
1044 } catch Error with {
1046 die "Could not retrieve initial volume list:\n\n$e\n";
1050 my @copies = grep { $_->holdable } @$cps;
1052 for (my $i = 0; $i < @$cps; $i++) {
1053 next unless $$cps[$i];
1055 my $cn = $cache{cns}{$copies[$i]->call_number};
1056 my $rec = $cache{titles}{$cn->record};
1057 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1058 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1059 $copies[$i] = undef if (
1061 !$self->{user_filter}->request(
1062 'open-ils.circ.permit_hold',
1063 $hold->to_fieldmapper, do {
1064 my $cp_fm = $copies[$i]->to_fieldmapper;
1065 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1066 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1067 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1070 { title => $rec->to_fieldmapper,
1071 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1072 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1075 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1078 @copies = grep { $_ } @copies;
1080 my $count = @copies;
1082 return unless ($count);
1084 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1087 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1088 for my $c (@copies) {
1089 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1091 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1097 sub choose_nearest_copy {
1099 my $prox_list = shift;
1101 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1102 next unless (ref $$prox_list[$p]);
1104 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1105 next unless (@capturable);
1107 my $rand = int(rand(scalar(@capturable)));
1108 while (my ($c) = splice(@capturable,$rand)) {
1109 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1110 { title => $c->call_number->record->to_fieldmapper,
1111 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1112 patron => $hold->usr->to_fieldmapper,
1113 copy => $c->to_fieldmapper,
1114 requestor => $hold->requestor->to_fieldmapper,
1115 request_lib => $hold->request_lib->to_fieldmapper,
1118 last unless(@capturable);
1119 $rand = int(rand(scalar(@capturable)));
1127 sub create_prox_list {
1133 for my $cp (@$copies) {
1134 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1135 next unless (defined($prox));
1136 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1137 push @{$prox_list[$prox]}, $cp;
1142 sub volume_hold_capture {
1147 if (!defined($vols)) {
1149 $vols = [ asset::call_number->search( id => $hold->target ) ];
1150 $cache{cns}{$_->id} = $_ for (@$vols);
1151 } catch Error with {
1153 die "Could not retrieve initial volume list:\n\n$e\n";
1157 my @v_ids = map { $_->id } @$vols;
1161 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1163 } catch Error with {
1165 warn "Could not retrieve copy list:\n\n$e\n";
1168 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1171 sub title_hold_capture {
1176 if (!defined($titles)) {
1178 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1179 $cache{titles}{$_->id} = $_ for (@$titles);
1180 } catch Error with {
1182 die "Could not retrieve initial title list:\n\n$e\n";
1186 my @t_ids = map { $_->id } @$titles;
1189 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1191 } catch Error with {
1193 warn "Could not retrieve volume list:\n\n$e\n";
1196 $cache{cns}{$_->id} = $_ for (@$cn_list);
1198 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1201 sub metarecord_hold_capture {
1207 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1209 } catch Error with {
1211 die "Could not retrieve initial title list:\n\n$e\n";
1215 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1217 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1219 } catch Error with {
1221 die "Could not retrieve format-pruned title list:\n\n$e\n";
1225 $cache{titles}{$_->id} = $_ for (@$titles);
1226 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);