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 ORDER BY h.request_time
69 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
72 $client->respond($_) for (
75 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
79 } @{ $sth->fetchall_arrayref }
83 __PACKAGE__->register_method(
84 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
88 method => 'ou_hold_requests',
95 my $c_t = action::circulation->table;
97 $grace = " - ($grace * (fine_interval))" if ($grace);
102 WHERE stop_fines IS NULL
103 AND due_date < ( CURRENT_TIMESTAMP $grace)
106 my $sth = action::circulation->db_Main->prepare_cached($sql);
109 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
113 sub complete_reshelving {
118 local $OpenILS::Application::Storage::WRITE = 1;
120 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
121 unless (interval_to_seconds( $window ));
123 my $circ = action::circulation->table;
124 my $cp = asset::copy->table;
129 WHERE id IN ( SELECT cp.id
131 JOIN $circ circ ON (circ.target_copy = cp.id)
132 WHERE circ.checkin_time IS NOT NULL
133 AND circ.checkin_time < NOW() - CAST(? AS INTERVAL)
137 my $sth = action::circulation->db_Main->prepare_cached($sql);
138 $sth->execute($window);
143 __PACKAGE__->register_method(
144 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
148 method => 'complete_reshelving',
154 my $grace = shift || '';
156 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
161 __PACKAGE__->register_method(
162 api_name => 'open-ils.storage.action.circulation.overdue',
165 method => 'grab_overdue',
173 my $limit = int(shift()) || 10;
175 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
177 FROM action.hold_request h
178 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
179 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
180 WHERE hm.target_copy = ?
182 AND h.capture_time IS NULL
183 AND h.cancel_time IS NULL
186 h.selection_depth DESC,
192 __PACKAGE__->register_method(
193 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
196 method => 'nearest_hold',
199 sub next_resp_group_id {
203 # XXX This is not replication safe!!!
205 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
206 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
210 __PACKAGE__->register_method(
211 api_name => 'open-ils.storage.action.survey_response.next_group_id',
213 method => 'next_resp_group_id',
216 sub patron_circ_summary {
221 return undef unless ($id);
222 my $c_table = action::circulation->table;
223 my $b_table = money::billing->table;
225 $log->debug("Retrieving patron summary for id $id", DEBUG);
227 my $select = <<" SQL";
228 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
230 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
232 AND c.xact_finish IS NULL
234 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
235 OR c.stop_fines IS NULL
239 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
241 __PACKAGE__->register_method(
242 api_name => 'open-ils.storage.action.circulation.patron_summary',
244 method => 'patron_circ_summary',
247 #XXX Fix stored proc calls
248 sub find_local_surveys {
253 return undef unless ($ou);
254 my $s_table = action::survey->table;
256 my $select = <<" SQL";
259 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
260 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
263 my $sth = action::survey->db_Main->prepare_cached($select);
266 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
270 __PACKAGE__->register_method(
271 api_name => 'open-ils.storage.action.survey.all',
274 method => 'find_local_surveys',
277 #XXX Fix stored proc calls
278 sub find_opac_surveys {
283 return undef unless ($ou);
284 my $s_table = action::survey->table;
286 my $select = <<" SQL";
289 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
290 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
294 my $sth = action::survey->db_Main->prepare_cached($select);
297 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
301 __PACKAGE__->register_method(
302 api_name => 'open-ils.storage.action.survey.opac',
305 method => 'find_opac_surveys',
312 my $limit = shift || 10;
313 my $offset = shift || 0;
315 return undef unless ($ou);
316 my $h_table = action::hold_request->table;
317 my $a_table = asset::copy->table;
319 my $idlist = 1 if ($self->api_name =~/id_list/o);
321 my $select = <<" SQL";
324 JOIN $a_table a ON (h.current_copy = a.id)
326 AND h.capture_time IS NULL
327 AND h.cancel_time IS NULL
328 ORDER BY h.request_time ASC
333 my $sth = action::survey->db_Main->prepare_cached($select);
337 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
339 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
344 __PACKAGE__->register_method(
345 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
349 "Returns the hold ids for a specific library's pull list.",
350 [ [org_unit => "The library's org id", "number"],
351 [limit => 'An optional page size, defaults to 10', 'number'],
352 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
354 ['A list of holds for the stated library to pull for', 'array']
356 method => 'hold_pull_list',
358 __PACKAGE__->register_method(
359 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
363 "Returns the holds for a specific library's pull list.",
364 [ [org_unit => "The library's org id", "number"],
365 [limit => 'An optional page size, defaults to 10', 'number'],
366 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
368 ['A list of holds for the stated library to pull for', 'array']
370 method => 'hold_pull_list',
373 sub find_optional_surveys {
378 return undef unless ($ou);
379 my $s_table = action::survey->table;
381 my $select = <<" SQL";
384 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
385 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
386 AND s.required IS FALSE;
389 my $sth = action::survey->db_Main->prepare_cached($select);
392 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
396 __PACKAGE__->register_method(
397 api_name => 'open-ils.storage.action.survey.optional',
400 method => 'find_optional_surveys',
403 sub find_required_surveys {
408 return undef unless ($ou);
409 my $s_table = action::survey->table;
411 my $select = <<" SQL";
414 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
415 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
416 AND s.required IS TRUE;
419 my $sth = action::survey->db_Main->prepare_cached($select);
422 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
426 __PACKAGE__->register_method(
427 api_name => 'open-ils.storage.action.survey.required',
430 method => 'find_required_surveys',
433 sub find_usr_summary_surveys {
438 return undef unless ($ou);
439 my $s_table = action::survey->table;
441 my $select = <<" SQL";
444 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
445 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
446 AND s.usr_summary IS TRUE;
449 my $sth = action::survey->db_Main->prepare_cached($select);
452 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
456 __PACKAGE__->register_method(
457 api_name => 'open-ils.storage.action.survey.usr_summary',
460 method => 'find_usr_summary_surveys',
469 my $overbill = shift;
471 local $OpenILS::Application::Storage::WRITE = 1;
475 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
477 push @circs, overdue_circs($grace);
480 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
482 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
486 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
487 $log->debug("Cleaning up after previous transaction\n");
488 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
490 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
491 $log->info("Processing circ ".$c->id."...\n");
494 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
496 my $due = $due_dt->epoch;
498 my $fine_interval = interval_to_seconds( $c->fine_interval );
500 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
502 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
503 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
506 $due -= ($due % $fine_interval) + $tz_offset_s;
507 $now -= ($now % $fine_interval) + $tz_offset_s;
511 "ARG! Overdue circulation ".$c->id.
512 " for item ".$c->target_copy.
513 " (user ".$c->usr.").\n".
514 "\tItem was due on or before: ".localtime($due)."\n");
516 my @fines = money::billing->search_where(
517 { xact => $c->id, billing_type => 'Overdue materials' },
518 { order_by => 'billing_ts DESC'}
522 my $fine = $fines[$f_idx] if (@fines);
524 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
527 my $current_fine_total = 0;
528 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
532 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
533 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
537 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
538 #$last_fine += $fine_interval * $grace;
541 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
542 if ($pending_fine_count < 1) {
543 $client->respond( "\tNo fines to create. " );
544 if ($grace && $now < $due + $fine_interval * $grace) {
545 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
547 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
552 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
554 my $recuring_fine = int($c->recuring_fine * 100);
555 my $max_fine = int($c->max_fine * 100);
557 my ($latest_billing_ts, $latest_amount) = ('',0);;
558 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
560 if ($current_fine_total >= $max_fine) {
561 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
563 "\tMaximum fine level of ".$c->max_fine.
564 " reached for this circulation.\n".
565 "\tNo more fines will be generated.\n" );
569 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
571 my $dow = $billing_ts->dow;
572 my $dow_open = "dow_${dow}_open";
573 my $dow_close = "dow_${dow}_close";
575 if (my $h = $hoo{$c->circ_lib}) {
576 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
579 my $timestamptz = $billing_ts->strftime('%FT%T%z');
580 my @cl = actor::org_unit::closed_date->search_where(
581 { close_start => { '<=' => $timestamptz },
582 close_end => { '>=' => $timestamptz },
583 org_unit => $c->circ_lib }
587 $current_fine_total += $recuring_fine;
588 $latest_amount += $recuring_fine;
589 $latest_billing_ts = $timestamptz;
591 $client->respond( "\t\tAdding aggregate fine of ".$c->recuring_fine." for period starting ".$$timestamptz."\n" );
594 money::billing->create(
596 note => "System Generated Overdue Fine",
597 billing_type => "Overdue materials",
598 amount => sprintf('%0.2f', $latest_amount/100),
599 billing_ts => $latest_billing_ts,
601 ) if ($latest_billing_ts and $latest_amount);
604 $self->method_lookup('open-ils.storage.transaction.commit')->run;
607 'open-ils.penalty.patron_penalty.calculate',
608 { patron => $c->usr->to_fieldmapper,
616 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
617 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
618 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
619 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
623 __PACKAGE__->register_method(
624 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
627 method => 'generate_fines',
632 sub new_hold_copy_targeter {
635 my $check_expire = shift;
636 my $one_hold = shift;
638 local $OpenILS::Application::Storage::WRITE = 1;
644 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
645 } elsif ( $check_expire ) {
647 # what's the retarget time threashold?
649 $check_expire ||= '12h';
650 $check_expire = interval_to_seconds( $check_expire );
652 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
655 my $expire_threshold = sprintf(
656 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
657 $year, $mon, $mday, $hour, $min, $sec
660 # find all the holds holds needing retargeting
661 $holds = [ action::hold_request->search_where(
662 { capture_time => undef,
663 fulfillment_time => undef,
664 cancel_time => undef,
665 prev_check_time => { '<=' => $expire_threshold },
667 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
669 # find all the holds holds needing first time targeting
670 push @$holds, action::hold_request->search(
671 capture_time => undef,
672 fulfillment_time => undef,
673 prev_check_time => undef,
674 cancel_time => undef,
675 { order_by => 'selection_depth DESC, request_time' } );
678 # find all the holds holds needing first time targeting ONLY
679 $holds = [ action::hold_request->search(
680 capture_time => undef,
681 fulfillment_time => undef,
682 prev_check_time => undef,
683 cancel_time => undef,
684 { order_by => 'selection_depth DESC, request_time' } ) ];
688 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
691 my @closed = actor::org_unit::closed_date->search_where(
692 { close_start => { '<=', 'today' },
693 close_end => { '>=', 'today' } }
699 for my $hold (@$holds) {
701 #start a transaction if needed
702 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
703 $log->debug("Cleaning up after previous transaction\n");
704 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
706 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
707 $log->info("Processing hold ".$hold->id."...\n");
709 # remove old auto-targeting maps
710 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
711 $_->delete for (@oldmaps);
716 # find filters for MR holds
717 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
719 # find all the potential copies
720 if ($hold->hold_type eq 'M') {
723 metabib::record_descriptor
725 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
726 ( $types ? (item_type => [split '', $types]) : () ),
727 ( $formats ? (item_form => [split '', $formats]) : () ),
728 ( $lang ? (item_lang => $lang) : () ),
732 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
733 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
735 for my $cn ( @{ $rtree->call_numbers } ) {
737 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
740 } elsif ($hold->hold_type eq 'T') {
742 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
743 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
746 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
750 for my $cn ( @{ $rtree->call_numbers } ) {
752 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
754 } elsif ($hold->hold_type eq 'V') {
756 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
757 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
760 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
762 } elsif ($hold->hold_type eq 'C') {
764 $all_copies = [asset::copy->retrieve($hold->target)];
768 @$all_copies = grep { isTrue($_->status->holdable) &&
769 isTrue($_->location->holdable) &&
773 # let 'em know we're still working
774 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
776 # if we have no copies ...
777 if (!ref $all_copies || !@$all_copies) {
778 $log->info("\tNo copies available for targeting at all!\n");
779 $self->method_lookup('open-ils.storage.transaction.commit')->run;
780 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
782 $hold->update( { prev_check_time => 'today' } );
783 $self->method_lookup('open-ils.storage.transaction.commit')->run;
787 my $copy_count = @$all_copies;
789 # map the potentials, so that we can pick up checkins
790 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
791 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
793 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
796 for my $c (@$all_copies) {
798 next if ($c->id == $hold->current_copy);
801 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
803 # target of another hold
804 next if (action::hold_request
806 { current_copy => $c->id,
807 capture_time => undef,
808 cancel_time => undef,
813 # we passed all three, keep it
814 push @good_copies, $c if ($c);
815 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
818 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
820 my $old_best = $hold->current_copy;
821 $hold->update({ current_copy => undef }) if ($old_best);
823 if (!scalar(@good_copies)) {
824 $log->info("\tNo (non-current) copies eligible to fill the hold.");
827 grep { $old_best eq $_ } @$all_copies &&
828 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
830 # the old copy is still available
831 $log->debug("\tPushing current_copy back onto the targeting list");
832 push @good_copies, $old_best;
834 # oops, old copy is not available
835 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
836 $hold->update( { prev_check_time => 'today' } );
837 $self->method_lookup('open-ils.storage.transaction.commit')->run;
838 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
843 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
848 $_->circ_lib == $hold->pickup_lib
852 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
854 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
855 my $best = choose_nearest_copy($hold, $prox_list);
856 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
859 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
860 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
862 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
864 $best = choose_nearest_copy($hold, $prox_list);
867 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
869 # hold wasn't fulfilled, record the fact
871 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
872 action::unfulfilled_hold_list->create(
873 { hold => ''.$hold->id,
874 current_copy => ''.$old_best->id,
875 circ_lib => ''.$old_best->circ_lib,
880 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
881 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
883 $hold->update( { prev_check_time => 'now' } );
884 $log->info( "\tThere were no targetable copies for the hold" );
887 $self->method_lookup('open-ils.storage.transaction.commit')->run;
888 $log->info("\tProcessing of hold ".$hold->id." complete.");
892 old_target => ($old_best ? $old_best->id : undef),
893 eligible_copies => $copy_count,
894 target => ($best ? $best->id : undef) };
899 $log->error("Processing of hold failed: $e");
900 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
901 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
908 __PACKAGE__->register_method(
909 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
911 method => 'new_hold_copy_targeter',
916 my %cache = (titles => {}, cns => {});
917 sub hold_copy_targeter {
920 my $check_expire = shift;
921 my $one_hold = shift;
923 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
924 $self->{user_filter}->connect;
925 $self->{client} = $client;
928 $check_expire ||= '12h';
929 $check_expire = interval_to_seconds( $check_expire );
931 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
934 my $expire_threshold = sprintf(
935 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
936 $year, $mon, $mday, $hour, $min, $sec
940 $statuses ||= [ config::copy_status->search(holdable => 't') ];
942 $locations ||= [ asset::copy_location->search(holdable => 't') ];
946 %cache = (titles => {}, cns => {});
950 $holds = [ action::hold_request->search(id => $one_hold) ];
952 $holds = [ action::hold_request->search_where(
953 { capture_time => undef,
954 prev_check_time => { '<=' => $expire_threshold },
956 { order_by => 'request_time,prev_check_time' } ) ];
957 push @$holds, action::hold_request->search_where(
958 { capture_time => undef,
959 prev_check_time => undef,
961 { order_by => 'request_time' } );
965 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
968 for my $hold (@$holds) {
970 #action::hold_request->db_Main->begin_work;
971 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
972 $client->respond("Cleaning up after previous transaction\n");
973 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
975 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
976 $client->respond("Processing hold ".$hold->id."...\n");
980 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
981 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
983 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
984 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
986 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
987 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
989 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
991 unless (ref $copies || !@$copies) {
992 $client->respond("\tNo copies available for targeting at all!\n");
996 for my $c (@$copies) {
997 next if ( grep {$c->id == $hold->current_copy} @good_copies);
998 push @good_copies, $c if ($c);
1001 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1003 my $old_best = $hold->current_copy;
1004 $hold->update({ current_copy => undef });
1006 if (!scalar(@good_copies)) {
1007 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1008 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1009 $client->respond("\tPushing current_copy back onto the targeting list\n");
1010 push @good_copies, asset::copy->retrieve( $old_best );
1012 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1018 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1019 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1021 my $best = choose_nearest_copy($hold, $prox_list);
1024 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1025 $best = choose_nearest_copy($hold, $prox_list);
1029 # hold wasn't fulfilled, record the fact
1031 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1032 action::unfulfilled_hold_list->create(
1033 { hold => ''.$hold->id,
1034 current_copy => ''.$old_best->id,
1035 circ_lib => ''.$old_best->circ_lib,
1040 $hold->update( { current_copy => ''.$best->id } );
1041 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1044 $hold->update( { prev_check_time => 'now' } );
1045 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1047 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1048 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1050 #action::hold_request->dbi_commit;
1054 $log->error("Processing of hold failed: $e");
1055 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1056 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1057 #action::hold_request->dbi_rollback;
1061 $self->{user_filter}->disconnect;
1062 $self->{user_filter}->finish;
1063 delete $$self{user_filter};
1066 __PACKAGE__->register_method(
1067 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1070 method => 'hold_copy_targeter',
1074 sub copy_hold_capture {
1079 if (!defined($cps)) {
1081 $cps = [ asset::copy->search( id => $hold->target ) ];
1082 } catch Error with {
1084 die "Could not retrieve initial volume list:\n\n$e\n";
1088 my @copies = grep { $_->holdable } @$cps;
1090 for (my $i = 0; $i < @$cps; $i++) {
1091 next unless $$cps[$i];
1093 my $cn = $cache{cns}{$copies[$i]->call_number};
1094 my $rec = $cache{titles}{$cn->record};
1095 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1096 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1097 $copies[$i] = undef if (
1099 !$self->{user_filter}->request(
1100 'open-ils.circ.permit_hold',
1101 $hold->to_fieldmapper, do {
1102 my $cp_fm = $copies[$i]->to_fieldmapper;
1103 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1104 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1105 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1108 { title => $rec->to_fieldmapper,
1109 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1110 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1113 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1116 @copies = grep { $_ } @copies;
1118 my $count = @copies;
1120 return unless ($count);
1122 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1125 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1126 for my $c (@copies) {
1127 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1129 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1135 sub choose_nearest_copy {
1137 my $prox_list = shift;
1139 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1140 next unless (ref $$prox_list[$p]);
1142 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1143 next unless (@capturable);
1145 my $rand = int(rand(scalar(@capturable)));
1146 while (my ($c) = splice(@capturable,$rand)) {
1147 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1148 { title => $c->call_number->record->to_fieldmapper,
1149 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1150 patron => $hold->usr->to_fieldmapper,
1151 copy => $c->to_fieldmapper,
1152 requestor => $hold->requestor->to_fieldmapper,
1153 request_lib => $hold->request_lib->to_fieldmapper,
1156 last unless(@capturable);
1157 $rand = int(rand(scalar(@capturable)));
1165 sub create_prox_list {
1171 for my $cp (@$copies) {
1172 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1173 next unless (defined($prox));
1174 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1175 push @{$prox_list[$prox]}, $cp;
1180 sub volume_hold_capture {
1185 if (!defined($vols)) {
1187 $vols = [ asset::call_number->search( id => $hold->target ) ];
1188 $cache{cns}{$_->id} = $_ for (@$vols);
1189 } catch Error with {
1191 die "Could not retrieve initial volume list:\n\n$e\n";
1195 my @v_ids = map { $_->id } @$vols;
1199 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1201 } catch Error with {
1203 warn "Could not retrieve copy list:\n\n$e\n";
1206 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1209 sub title_hold_capture {
1214 if (!defined($titles)) {
1216 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1217 $cache{titles}{$_->id} = $_ for (@$titles);
1218 } catch Error with {
1220 die "Could not retrieve initial title list:\n\n$e\n";
1224 my @t_ids = map { $_->id } @$titles;
1227 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1229 } catch Error with {
1231 warn "Could not retrieve volume list:\n\n$e\n";
1234 $cache{cns}{$_->id} = $_ for (@$cn_list);
1236 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1239 sub metarecord_hold_capture {
1245 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1247 } catch Error with {
1249 die "Could not retrieve initial title list:\n\n$e\n";
1253 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1255 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1257 } catch Error with {
1259 die "Could not retrieve format-pruned title list:\n\n$e\n";
1263 $cache{titles}{$_->id} = $_ for (@$titles);
1264 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);