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;
131 SELECT cp.id, MAX(circ.checkin_time)
133 JOIN $circ circ ON (circ.target_copy = cp.id)
134 WHERE circ.checkin_time IS NOT NULL
137 HAVING MAX(circ.checkin_time) < NOW() - CAST(? AS INTERVAL)
143 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
145 AND cp.create_date < NOW() - CAST(? AS INTERVAL)
149 my $sth = action::circulation->db_Main->prepare_cached($sql);
150 $sth->execute($window, $window);
155 __PACKAGE__->register_method(
156 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
160 method => 'complete_reshelving',
166 my $grace = shift || '';
168 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
173 __PACKAGE__->register_method(
174 api_name => 'open-ils.storage.action.circulation.overdue',
177 method => 'grab_overdue',
185 my $limit = int(shift()) || 10;
187 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp, $pl);
189 FROM action.hold_request h
190 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
191 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
192 WHERE hm.target_copy = ?
194 AND h.capture_time IS NULL
195 AND h.cancel_time IS NULL
198 h.selection_depth DESC,
203 $client->respond( $_ ) for ( @$ids );
206 __PACKAGE__->register_method(
207 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
210 method => 'nearest_hold',
213 sub next_resp_group_id {
217 # XXX This is not replication safe!!!
219 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
220 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
224 __PACKAGE__->register_method(
225 api_name => 'open-ils.storage.action.survey_response.next_group_id',
227 method => 'next_resp_group_id',
230 sub patron_circ_summary {
235 return undef unless ($id);
236 my $c_table = action::circulation->table;
237 my $b_table = money::billing->table;
239 $log->debug("Retrieving patron summary for id $id", DEBUG);
241 my $select = <<" SQL";
242 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
244 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
246 AND c.xact_finish IS NULL
248 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
249 OR c.stop_fines IS NULL
253 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
255 __PACKAGE__->register_method(
256 api_name => 'open-ils.storage.action.circulation.patron_summary',
258 method => 'patron_circ_summary',
261 #XXX Fix stored proc calls
262 sub find_local_surveys {
267 return undef unless ($ou);
268 my $s_table = action::survey->table;
270 my $select = <<" SQL";
273 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
274 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
277 my $sth = action::survey->db_Main->prepare_cached($select);
280 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
284 __PACKAGE__->register_method(
285 api_name => 'open-ils.storage.action.survey.all',
288 method => 'find_local_surveys',
291 #XXX Fix stored proc calls
292 sub find_opac_surveys {
297 return undef unless ($ou);
298 my $s_table = action::survey->table;
300 my $select = <<" SQL";
303 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
304 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
308 my $sth = action::survey->db_Main->prepare_cached($select);
311 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
315 __PACKAGE__->register_method(
316 api_name => 'open-ils.storage.action.survey.opac',
319 method => 'find_opac_surveys',
326 my $limit = shift || 10;
327 my $offset = shift || 0;
329 return undef unless ($ou);
330 my $h_table = action::hold_request->table;
331 my $a_table = asset::copy->table;
333 my $idlist = 1 if ($self->api_name =~/id_list/o);
335 my $select = <<" SQL";
338 JOIN $a_table a ON (h.current_copy = a.id)
340 AND h.capture_time IS NULL
341 AND h.cancel_time IS NULL
342 ORDER BY h.request_time ASC
347 my $sth = action::survey->db_Main->prepare_cached($select);
351 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
353 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
358 __PACKAGE__->register_method(
359 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
363 "Returns the hold ids 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',
372 __PACKAGE__->register_method(
373 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
377 "Returns the holds for a specific library's pull list.",
378 [ [org_unit => "The library's org id", "number"],
379 [limit => 'An optional page size, defaults to 10', 'number'],
380 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
382 ['A list of holds for the stated library to pull for', 'array']
384 method => 'hold_pull_list',
387 sub find_optional_surveys {
392 return undef unless ($ou);
393 my $s_table = action::survey->table;
395 my $select = <<" SQL";
398 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
399 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
400 AND s.required IS FALSE;
403 my $sth = action::survey->db_Main->prepare_cached($select);
406 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
410 __PACKAGE__->register_method(
411 api_name => 'open-ils.storage.action.survey.optional',
414 method => 'find_optional_surveys',
417 sub find_required_surveys {
422 return undef unless ($ou);
423 my $s_table = action::survey->table;
425 my $select = <<" SQL";
428 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
429 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
430 AND s.required IS TRUE;
433 my $sth = action::survey->db_Main->prepare_cached($select);
436 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
440 __PACKAGE__->register_method(
441 api_name => 'open-ils.storage.action.survey.required',
444 method => 'find_required_surveys',
447 sub find_usr_summary_surveys {
452 return undef unless ($ou);
453 my $s_table = action::survey->table;
455 my $select = <<" SQL";
458 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
459 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
460 AND s.usr_summary IS TRUE;
463 my $sth = action::survey->db_Main->prepare_cached($select);
466 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
470 __PACKAGE__->register_method(
471 api_name => 'open-ils.storage.action.survey.usr_summary',
474 method => 'find_usr_summary_surveys',
483 my $overbill = shift;
485 local $OpenILS::Application::Storage::WRITE = 1;
489 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
491 push @circs, overdue_circs($grace);
494 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
496 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
500 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
501 $log->debug("Cleaning up after previous transaction\n");
502 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
504 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
505 $log->info("Processing circ ".$c->id."...\n");
508 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
510 my $due = $due_dt->epoch;
512 my $fine_interval = interval_to_seconds( $c->fine_interval );
514 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
516 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
517 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
520 $due -= ($due % $fine_interval) + $tz_offset_s;
521 $now -= ($now % $fine_interval) + $tz_offset_s;
525 "ARG! Overdue circulation ".$c->id.
526 " for item ".$c->target_copy.
527 " (user ".$c->usr.").\n".
528 "\tItem was due on or before: ".localtime($due)."\n");
530 my @fines = money::billing->search_where(
532 billing_type => 'Overdue materials',
533 billing_ts => { '>' => $c->due_date } },
534 { order_by => 'billing_ts DESC'}
538 my $fine = $fines[$f_idx] if (@fines);
540 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
543 my $current_fine_total = 0;
544 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
548 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
549 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
551 $log->info( "Potential first billing for circ ".$c->id );
555 if (my $h = $hoo{$c->circ_lib}) {
557 $log->info( "Circ lib has an hours-of-operation entry" );
558 # find the day after the due date...
559 $due_dt = $due_dt->add( days => 1 );
561 # get the day of the week for that day...
562 my $dow = $due_dt->day_of_week_0;
563 my $dow_open = "dow_${dow}_open";
564 my $dow_close = "dow_${dow}_close";
567 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
568 # if the circ lib is closed, add a day to the grace period...
571 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
572 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
574 $due_dt = $due_dt->add( days => 1 );
575 $dow = $due_dt->day_of_week_0;
576 $dow_open = "dow_${dow}_open";
577 $dow_close = "dow_${dow}_close";
581 # and check for up to a week
582 last if ($count > 6);
589 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
590 if ($pending_fine_count < 1 + $grace) {
591 $client->respond( "\tNo fines to create. " );
592 if ($grace && $now < $due + $fine_interval * $grace) {
593 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
594 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
596 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
601 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
603 my $recuring_fine = int($c->recuring_fine * 100);
604 my $max_fine = int($c->max_fine * 100);
606 my ($latest_billing_ts, $latest_amount) = ('',0);
607 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
609 if ($current_fine_total >= $max_fine) {
610 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
612 "\tMaximum fine level of ".$c->max_fine.
613 " reached for this circulation.\n".
614 "\tNo more fines will be generated.\n" );
618 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
620 my $dow = $billing_ts->day_of_week_0();
621 my $dow_open = "dow_${dow}_open";
622 my $dow_close = "dow_${dow}_close";
624 if (my $h = $hoo{$c->circ_lib}) {
625 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
628 my $timestamptz = $billing_ts->strftime('%FT%T%z');
629 my @cl = actor::org_unit::closed_date->search_where(
630 { close_start => { '<=' => $timestamptz },
631 close_end => { '>=' => $timestamptz },
632 org_unit => $c->circ_lib }
636 $current_fine_total += $recuring_fine;
637 $latest_amount += $recuring_fine;
638 $latest_billing_ts = $timestamptz;
640 money::billing->create(
642 note => "System Generated Overdue Fine",
643 billing_type => "Overdue materials",
644 amount => sprintf('%0.2f', $recuring_fine/100),
645 billing_ts => $timestamptz,
651 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
652 if ($latest_billing_ts and $latest_amount);
654 $self->method_lookup('open-ils.storage.transaction.commit')->run;
657 'open-ils.penalty.patron_penalty.calculate',
658 { patron => $c->usr->to_fieldmapper,
666 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
667 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
668 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
669 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
673 __PACKAGE__->register_method(
674 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
677 method => 'generate_fines',
682 sub new_hold_copy_targeter {
685 my $check_expire = shift;
686 my $one_hold = shift;
688 local $OpenILS::Application::Storage::WRITE = 1;
694 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
695 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
696 } elsif ( $check_expire ) {
698 # what's the retarget time threashold?
700 $check_expire ||= '12h';
701 $check_expire = interval_to_seconds( $check_expire );
703 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
706 my $expire_threshold = sprintf(
707 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
708 $year, $mon, $mday, $hour, $min, $sec
711 # find all the holds holds needing retargeting
712 $holds = [ action::hold_request->search_where(
713 { capture_time => undef,
714 fulfillment_time => undef,
715 cancel_time => undef,
717 prev_check_time => { '<=' => $expire_threshold },
719 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
721 # find all the holds holds needing first time targeting
722 push @$holds, action::hold_request->search(
723 capture_time => undef,
724 fulfillment_time => undef,
725 prev_check_time => undef,
727 cancel_time => undef,
728 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
731 # find all the holds holds needing first time targeting ONLY
732 $holds = [ action::hold_request->search(
733 capture_time => undef,
734 fulfillment_time => undef,
735 prev_check_time => undef,
736 cancel_time => undef,
738 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
742 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
745 my @closed = actor::org_unit::closed_date->search_where(
746 { close_start => { '<=', 'now' },
747 close_end => { '>=', 'now' } }
753 for my $hold (@$holds) {
755 #start a transaction if needed
756 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
757 $log->debug("Cleaning up after previous transaction\n");
758 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
760 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
761 $log->info("Processing hold ".$hold->id."...\n");
763 #first, re-fetch the hold, to make sure it's not captured already
764 $hold = action::hold_request->retrieve( $hold->id );
765 die "OK\n" if (!$hold or $hold->capture_time);
767 # remove old auto-targeting maps
768 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
769 $_->delete for (@oldmaps);
774 # find filters for MR holds
775 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
777 # find all the potential copies
778 if ($hold->hold_type eq 'M') {
781 metabib::record_descriptor
783 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
784 ( $types ? (item_type => [split '', $types]) : () ),
785 ( $formats ? (item_form => [split '', $formats]) : () ),
786 ( $lang ? (item_lang => $lang) : () ),
790 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
791 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
793 for my $cn ( @{ $rtree->call_numbers } ) {
795 asset::copy->search_where(
796 { id => [map {$_->id} @{ $cn->copies }],
798 ) if ($cn && @{ $cn->copies });
801 } elsif ($hold->hold_type eq 'T') {
803 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
804 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
807 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
811 for my $cn ( @{ $rtree->call_numbers } ) {
813 asset::copy->search_where(
814 { id => [map {$_->id} @{ $cn->copies }],
816 ) if ($cn && @{ $cn->copies });
818 } elsif ($hold->hold_type eq 'V') {
820 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
821 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
824 asset::copy->search_where(
825 { id => [map {$_->id} @{ $vtree->copies }],
827 ) if ($vtree && @{ $vtree->copies });
829 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
830 my $_cp = asset::copy->retrieve($hold->target);
831 push @$all_copies, $_cp if $_cp;
835 @$all_copies = grep { isTrue($_->status->holdable) &&
836 isTrue($_->location->holdable) &&
837 isTrue($_->holdable) &&
841 # let 'em know we're still working
842 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
844 # if we have no copies ...
845 if (!ref $all_copies || !@$all_copies) {
846 $log->info("\tNo copies available for targeting at all!\n");
847 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
849 $hold->update( { prev_check_time => 'today', current_copy => undef } );
850 $self->method_lookup('open-ils.storage.transaction.commit')->run;
854 my $copy_count = @$all_copies;
856 # map the potentials, so that we can pick up checkins
857 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
858 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
860 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
863 for my $c (@$all_copies) {
865 next if ($c->id eq $hold->current_copy);
868 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
870 # target of another hold
871 next if (action::hold_request
873 { current_copy => $c->id,
874 fulfillment_time => undef,
875 cancel_time => undef,
880 # we passed all three, keep it
881 push @good_copies, $c if ($c);
882 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
885 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
887 my $old_best = $hold->current_copy;
888 $hold->update({ current_copy => undef }) if ($old_best);
890 if (!scalar(@good_copies)) {
891 $log->info("\tNo (non-current) copies eligible to fill the hold.");
894 grep { $old_best eq $_ } @$all_copies &&
895 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
897 # the old copy is still available
898 $log->debug("\tPushing current_copy back onto the targeting list");
899 push @good_copies, $old_best;
901 # oops, old copy is not available
902 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
903 $hold->update( { prev_check_time => 'today' } );
904 $self->method_lookup('open-ils.storage.transaction.commit')->run;
905 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
910 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
915 $_->circ_lib == $hold->pickup_lib
919 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
921 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
922 my $best = choose_nearest_copy($hold, $prox_list);
923 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
926 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
927 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
929 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
931 $best = choose_nearest_copy($hold, $prox_list);
934 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
936 # hold wasn't fulfilled, record the fact
938 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
939 action::unfulfilled_hold_list->create(
940 { hold => ''.$hold->id,
941 current_copy => ''.$old_best->id,
942 circ_lib => ''.$old_best->circ_lib,
947 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
948 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
953 { current_copy => $old_best->id,
954 fulfillment_time => undef,
955 cancel_time => undef,
959 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
960 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
962 $hold->update( { prev_check_time => 'now' } );
963 $log->info( "\tThere were no targetable copies for the hold" );
966 $self->method_lookup('open-ils.storage.transaction.commit')->run;
967 $log->info("\tProcessing of hold ".$hold->id." complete.");
971 old_target => ($old_best ? $old_best->id : undef),
972 eligible_copies => $copy_count,
973 target => ($best ? $best->id : undef) };
978 $log->error("Processing of hold failed: $e");
979 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
980 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
987 __PACKAGE__->register_method(
988 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
990 method => 'new_hold_copy_targeter',
995 my %cache = (titles => {}, cns => {});
996 sub hold_copy_targeter {
999 my $check_expire = shift;
1000 my $one_hold = shift;
1002 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1003 $self->{user_filter}->connect;
1004 $self->{client} = $client;
1007 $check_expire ||= '12h';
1008 $check_expire = interval_to_seconds( $check_expire );
1010 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1013 my $expire_threshold = sprintf(
1014 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1015 $year, $mon, $mday, $hour, $min, $sec
1019 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1021 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1025 %cache = (titles => {}, cns => {});
1029 $holds = [ action::hold_request->search(id => $one_hold) ];
1031 $holds = [ action::hold_request->search_where(
1032 { capture_time => undef,
1033 prev_check_time => { '<=' => $expire_threshold },
1035 { order_by => 'request_time,prev_check_time' } ) ];
1036 push @$holds, action::hold_request->search_where(
1037 { capture_time => undef,
1038 prev_check_time => undef,
1040 { order_by => 'request_time' } );
1042 } catch Error with {
1044 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1047 for my $hold (@$holds) {
1049 #action::hold_request->db_Main->begin_work;
1050 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1051 $client->respond("Cleaning up after previous transaction\n");
1052 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1054 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1055 $client->respond("Processing hold ".$hold->id."...\n");
1059 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1060 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1062 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1063 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1065 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1066 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1068 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1070 unless (ref $copies || !@$copies) {
1071 $client->respond("\tNo copies available for targeting at all!\n");
1075 for my $c (@$copies) {
1076 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1077 push @good_copies, $c if ($c);
1080 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1082 my $old_best = $hold->current_copy;
1083 $hold->update({ current_copy => undef });
1085 if (!scalar(@good_copies)) {
1086 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1087 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1088 $client->respond("\tPushing current_copy back onto the targeting list\n");
1089 push @good_copies, asset::copy->retrieve( $old_best );
1091 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1097 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1098 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1100 my $best = choose_nearest_copy($hold, $prox_list);
1103 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1104 $best = choose_nearest_copy($hold, $prox_list);
1108 # hold wasn't fulfilled, record the fact
1110 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1111 action::unfulfilled_hold_list->create(
1112 { hold => ''.$hold->id,
1113 current_copy => ''.$old_best->id,
1114 circ_lib => ''.$old_best->circ_lib,
1119 $hold->update( { current_copy => ''.$best->id } );
1120 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1123 $hold->update( { prev_check_time => 'now' } );
1124 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1126 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1127 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1129 #action::hold_request->dbi_commit;
1133 $log->error("Processing of hold failed: $e");
1134 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1135 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1136 #action::hold_request->dbi_rollback;
1140 $self->{user_filter}->disconnect;
1141 $self->{user_filter}->finish;
1142 delete $$self{user_filter};
1145 __PACKAGE__->register_method(
1146 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1149 method => 'hold_copy_targeter',
1153 sub copy_hold_capture {
1158 if (!defined($cps)) {
1160 $cps = [ asset::copy->search( id => $hold->target ) ];
1161 } catch Error with {
1163 die "Could not retrieve initial volume list:\n\n$e\n";
1167 my @copies = grep { $_->holdable } @$cps;
1169 for (my $i = 0; $i < @$cps; $i++) {
1170 next unless $$cps[$i];
1172 my $cn = $cache{cns}{$copies[$i]->call_number};
1173 my $rec = $cache{titles}{$cn->record};
1174 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1175 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1176 $copies[$i] = undef if (
1178 !$self->{user_filter}->request(
1179 'open-ils.circ.permit_hold',
1180 $hold->to_fieldmapper, do {
1181 my $cp_fm = $copies[$i]->to_fieldmapper;
1182 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1183 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1184 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1187 { title => $rec->to_fieldmapper,
1188 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1189 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1192 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1195 @copies = grep { $_ } @copies;
1197 my $count = @copies;
1199 return unless ($count);
1201 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1204 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1205 for my $c (@copies) {
1206 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1208 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1214 sub choose_nearest_copy {
1216 my $prox_list = shift;
1218 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1219 next unless (ref $$prox_list[$p]);
1221 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1222 next unless (@capturable);
1224 my $rand = int(rand(scalar(@capturable)));
1225 while (my ($c) = splice(@capturable,$rand)) {
1226 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1227 { title => $c->call_number->record->to_fieldmapper,
1228 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1229 patron => $hold->usr->to_fieldmapper,
1230 copy => $c->to_fieldmapper,
1231 requestor => $hold->requestor->to_fieldmapper,
1232 request_lib => $hold->request_lib->to_fieldmapper,
1233 pickup_lib => $hold->pickup_lib->id,
1237 last unless(@capturable);
1238 $rand = int(rand(scalar(@capturable)));
1243 sub create_prox_list {
1249 for my $cp (@$copies) {
1250 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1251 next unless (defined($prox));
1252 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1253 push @{$prox_list[$prox]}, $cp;
1258 sub volume_hold_capture {
1263 if (!defined($vols)) {
1265 $vols = [ asset::call_number->search( id => $hold->target ) ];
1266 $cache{cns}{$_->id} = $_ for (@$vols);
1267 } catch Error with {
1269 die "Could not retrieve initial volume list:\n\n$e\n";
1273 my @v_ids = map { $_->id } @$vols;
1277 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1279 } catch Error with {
1281 warn "Could not retrieve copy list:\n\n$e\n";
1284 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1287 sub title_hold_capture {
1292 if (!defined($titles)) {
1294 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1295 $cache{titles}{$_->id} = $_ for (@$titles);
1296 } catch Error with {
1298 die "Could not retrieve initial title list:\n\n$e\n";
1302 my @t_ids = map { $_->id } @$titles;
1305 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1307 } catch Error with {
1309 warn "Could not retrieve volume list:\n\n$e\n";
1312 $cache{cns}{$_->id} = $_ for (@$cn_list);
1314 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1317 sub metarecord_hold_capture {
1323 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1325 } catch Error with {
1327 die "Could not retrieve initial title list:\n\n$e\n";
1331 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1333 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1335 } catch Error with {
1337 die "Could not retrieve format-pruned title list:\n\n$e\n";
1341 $cache{titles}{$_->id} = $_ for (@$titles);
1342 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);