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(
531 { xact => $c->id, billing_type => 'Overdue materials' },
532 { order_by => 'billing_ts DESC'}
536 my $fine = $fines[$f_idx] if (@fines);
538 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
541 my $current_fine_total = 0;
542 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
546 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
547 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
549 $log->info( "Potential first billing for circ ".$c->id );
553 if (my $h = $hoo{$c->circ_lib}) {
555 $log->info( "Circ lib has an hours-of-operation entry" );
556 # find the day after the due date...
557 $due_dt = $due_dt->add( days => 1 );
559 # get the day of the week for that day...
560 my $dow = $due_dt->day_of_week_0;
561 my $dow_open = "dow_${dow}_open";
562 my $dow_close = "dow_${dow}_close";
565 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
566 # if the circ lib is closed, add a day to the grace period...
569 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
570 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
572 $due_dt = $due_dt->add( days => 1 );
573 $dow = $due_dt->day_of_week_0;
574 $dow_open = "dow_${dow}_open";
575 $dow_close = "dow_${dow}_close";
579 # and check for up to a week
580 last if ($count > 6);
587 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
588 if ($pending_fine_count < 1 + $grace) {
589 $client->respond( "\tNo fines to create. " );
590 if ($grace && $now < $due + $fine_interval * $grace) {
591 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
592 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
594 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
599 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
601 my $recuring_fine = int($c->recuring_fine * 100);
602 my $max_fine = int($c->max_fine * 100);
604 my ($latest_billing_ts, $latest_amount) = ('',0);
605 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
607 if ($current_fine_total >= $max_fine) {
608 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
610 "\tMaximum fine level of ".$c->max_fine.
611 " reached for this circulation.\n".
612 "\tNo more fines will be generated.\n" );
616 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
618 my $dow = $billing_ts->day_of_week_0();
619 my $dow_open = "dow_${dow}_open";
620 my $dow_close = "dow_${dow}_close";
622 if (my $h = $hoo{$c->circ_lib}) {
623 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
626 my $timestamptz = $billing_ts->strftime('%FT%T%z');
627 my @cl = actor::org_unit::closed_date->search_where(
628 { close_start => { '<=' => $timestamptz },
629 close_end => { '>=' => $timestamptz },
630 org_unit => $c->circ_lib }
634 $current_fine_total += $recuring_fine;
635 $latest_amount += $recuring_fine;
636 $latest_billing_ts = $timestamptz;
638 money::billing->create(
640 note => "System Generated Overdue Fine",
641 billing_type => "Overdue materials",
642 amount => sprintf('%0.2f', $recuring_fine/100),
643 billing_ts => $timestamptz,
649 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
650 if ($latest_billing_ts and $latest_amount);
652 $self->method_lookup('open-ils.storage.transaction.commit')->run;
655 'open-ils.penalty.patron_penalty.calculate',
656 { patron => $c->usr->to_fieldmapper,
664 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
665 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
666 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
667 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
671 __PACKAGE__->register_method(
672 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
675 method => 'generate_fines',
680 sub new_hold_copy_targeter {
683 my $check_expire = shift;
684 my $one_hold = shift;
686 local $OpenILS::Application::Storage::WRITE = 1;
692 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
693 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
694 } elsif ( $check_expire ) {
696 # what's the retarget time threashold?
698 $check_expire ||= '12h';
699 $check_expire = interval_to_seconds( $check_expire );
701 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
704 my $expire_threshold = sprintf(
705 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
706 $year, $mon, $mday, $hour, $min, $sec
709 # find all the holds holds needing retargeting
710 $holds = [ action::hold_request->search_where(
711 { capture_time => undef,
712 fulfillment_time => undef,
713 cancel_time => undef,
714 prev_check_time => { '<=' => $expire_threshold },
716 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
718 # find all the holds holds needing first time targeting
719 push @$holds, action::hold_request->search(
720 capture_time => undef,
721 fulfillment_time => undef,
722 prev_check_time => undef,
723 cancel_time => undef,
724 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
727 # find all the holds holds needing first time targeting ONLY
728 $holds = [ action::hold_request->search(
729 capture_time => undef,
730 fulfillment_time => undef,
731 prev_check_time => undef,
732 cancel_time => undef,
733 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
737 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
740 my @closed = actor::org_unit::closed_date->search_where(
741 { close_start => { '<=', 'now' },
742 close_end => { '>=', 'now' } }
748 for my $hold (@$holds) {
750 #start a transaction if needed
751 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
752 $log->debug("Cleaning up after previous transaction\n");
753 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
755 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
756 $log->info("Processing hold ".$hold->id."...\n");
758 #first, re-fetch the hold, to make sure it's not captured already
759 $hold = action::hold_request->retrieve( $hold->id );
760 die "OK\n" if (!$hold or $hold->capture_time);
762 # remove old auto-targeting maps
763 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
764 $_->delete for (@oldmaps);
769 # find filters for MR holds
770 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
772 # find all the potential copies
773 if ($hold->hold_type eq 'M') {
776 metabib::record_descriptor
778 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
779 ( $types ? (item_type => [split '', $types]) : () ),
780 ( $formats ? (item_form => [split '', $formats]) : () ),
781 ( $lang ? (item_lang => $lang) : () ),
785 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
786 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
788 for my $cn ( @{ $rtree->call_numbers } ) {
790 asset::copy->search_where(
791 { id => [map {$_->id} @{ $cn->copies }],
793 ) if ($cn && $cn->copies);
796 } elsif ($hold->hold_type eq 'T') {
798 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
799 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
802 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
806 for my $cn ( @{ $rtree->call_numbers } ) {
808 asset::copy->search_where(
809 { id => [map {$_->id} @{ $cn->copies }],
811 ) if ($cn && $cn->copies);
813 } elsif ($hold->hold_type eq 'V') {
815 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
816 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
819 asset::copy->search_where(
820 { id => [map {$_->id} @{ $vtree->copies }],
822 ) if ($vtree && $vtree->copies);
824 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
825 $all_copies = [asset::copy->retrieve($hold->target)];
829 @$all_copies = grep { isTrue($_->status->holdable) &&
830 isTrue($_->location->holdable) &&
831 isTrue($_->holdable) &&
835 # let 'em know we're still working
836 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
838 # if we have no copies ...
839 if (!ref $all_copies || !@$all_copies) {
840 $log->info("\tNo copies available for targeting at all!\n");
841 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
843 $hold->update( { prev_check_time => 'today', current_copy => undef } );
844 $self->method_lookup('open-ils.storage.transaction.commit')->run;
848 my $copy_count = @$all_copies;
850 # map the potentials, so that we can pick up checkins
851 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
852 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
854 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
857 for my $c (@$all_copies) {
859 next if ($c->id eq $hold->current_copy);
862 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
864 # target of another hold
865 next if (action::hold_request
867 { current_copy => $c->id,
868 fulfillment_time => undef,
869 cancel_time => undef,
874 # we passed all three, keep it
875 push @good_copies, $c if ($c);
876 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
879 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
881 my $old_best = $hold->current_copy;
882 $hold->update({ current_copy => undef }) if ($old_best);
884 if (!scalar(@good_copies)) {
885 $log->info("\tNo (non-current) copies eligible to fill the hold.");
888 grep { $old_best eq $_ } @$all_copies &&
889 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
891 # the old copy is still available
892 $log->debug("\tPushing current_copy back onto the targeting list");
893 push @good_copies, $old_best;
895 # oops, old copy is not available
896 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
897 $hold->update( { prev_check_time => 'today' } );
898 $self->method_lookup('open-ils.storage.transaction.commit')->run;
899 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
904 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
909 $_->circ_lib == $hold->pickup_lib
913 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
915 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
916 my $best = choose_nearest_copy($hold, $prox_list);
917 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
920 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
921 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
923 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
925 $best = choose_nearest_copy($hold, $prox_list);
928 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
930 # hold wasn't fulfilled, record the fact
932 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
933 action::unfulfilled_hold_list->create(
934 { hold => ''.$hold->id,
935 current_copy => ''.$old_best->id,
936 circ_lib => ''.$old_best->circ_lib,
941 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
942 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
947 { current_copy => $old_best->id,
948 fulfillment_time => undef,
949 cancel_time => undef,
953 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
954 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
956 $hold->update( { prev_check_time => 'now' } );
957 $log->info( "\tThere were no targetable copies for the hold" );
960 $self->method_lookup('open-ils.storage.transaction.commit')->run;
961 $log->info("\tProcessing of hold ".$hold->id." complete.");
965 old_target => ($old_best ? $old_best->id : undef),
966 eligible_copies => $copy_count,
967 target => ($best ? $best->id : undef) };
972 $log->error("Processing of hold failed: $e");
973 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
974 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
981 __PACKAGE__->register_method(
982 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
984 method => 'new_hold_copy_targeter',
989 my %cache = (titles => {}, cns => {});
990 sub hold_copy_targeter {
993 my $check_expire = shift;
994 my $one_hold = shift;
996 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
997 $self->{user_filter}->connect;
998 $self->{client} = $client;
1001 $check_expire ||= '12h';
1002 $check_expire = interval_to_seconds( $check_expire );
1004 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1007 my $expire_threshold = sprintf(
1008 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1009 $year, $mon, $mday, $hour, $min, $sec
1013 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1015 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1019 %cache = (titles => {}, cns => {});
1023 $holds = [ action::hold_request->search(id => $one_hold) ];
1025 $holds = [ action::hold_request->search_where(
1026 { capture_time => undef,
1027 prev_check_time => { '<=' => $expire_threshold },
1029 { order_by => 'request_time,prev_check_time' } ) ];
1030 push @$holds, action::hold_request->search_where(
1031 { capture_time => undef,
1032 prev_check_time => undef,
1034 { order_by => 'request_time' } );
1036 } catch Error with {
1038 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1041 for my $hold (@$holds) {
1043 #action::hold_request->db_Main->begin_work;
1044 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1045 $client->respond("Cleaning up after previous transaction\n");
1046 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1048 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1049 $client->respond("Processing hold ".$hold->id."...\n");
1053 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1054 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1056 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1057 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1059 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1060 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1062 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1064 unless (ref $copies || !@$copies) {
1065 $client->respond("\tNo copies available for targeting at all!\n");
1069 for my $c (@$copies) {
1070 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1071 push @good_copies, $c if ($c);
1074 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1076 my $old_best = $hold->current_copy;
1077 $hold->update({ current_copy => undef });
1079 if (!scalar(@good_copies)) {
1080 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1081 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1082 $client->respond("\tPushing current_copy back onto the targeting list\n");
1083 push @good_copies, asset::copy->retrieve( $old_best );
1085 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1091 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1092 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1094 my $best = choose_nearest_copy($hold, $prox_list);
1097 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1098 $best = choose_nearest_copy($hold, $prox_list);
1102 # hold wasn't fulfilled, record the fact
1104 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1105 action::unfulfilled_hold_list->create(
1106 { hold => ''.$hold->id,
1107 current_copy => ''.$old_best->id,
1108 circ_lib => ''.$old_best->circ_lib,
1113 $hold->update( { current_copy => ''.$best->id } );
1114 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1117 $hold->update( { prev_check_time => 'now' } );
1118 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1120 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1121 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1123 #action::hold_request->dbi_commit;
1127 $log->error("Processing of hold failed: $e");
1128 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1129 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1130 #action::hold_request->dbi_rollback;
1134 $self->{user_filter}->disconnect;
1135 $self->{user_filter}->finish;
1136 delete $$self{user_filter};
1139 __PACKAGE__->register_method(
1140 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1143 method => 'hold_copy_targeter',
1147 sub copy_hold_capture {
1152 if (!defined($cps)) {
1154 $cps = [ asset::copy->search( id => $hold->target ) ];
1155 } catch Error with {
1157 die "Could not retrieve initial volume list:\n\n$e\n";
1161 my @copies = grep { $_->holdable } @$cps;
1163 for (my $i = 0; $i < @$cps; $i++) {
1164 next unless $$cps[$i];
1166 my $cn = $cache{cns}{$copies[$i]->call_number};
1167 my $rec = $cache{titles}{$cn->record};
1168 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1169 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1170 $copies[$i] = undef if (
1172 !$self->{user_filter}->request(
1173 'open-ils.circ.permit_hold',
1174 $hold->to_fieldmapper, do {
1175 my $cp_fm = $copies[$i]->to_fieldmapper;
1176 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1177 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1178 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1181 { title => $rec->to_fieldmapper,
1182 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1183 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1186 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1189 @copies = grep { $_ } @copies;
1191 my $count = @copies;
1193 return unless ($count);
1195 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1198 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1199 for my $c (@copies) {
1200 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1202 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1208 sub choose_nearest_copy {
1210 my $prox_list = shift;
1212 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1213 next unless (ref $$prox_list[$p]);
1215 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1216 next unless (@capturable);
1218 my $rand = int(rand(scalar(@capturable)));
1219 while (my ($c) = splice(@capturable,$rand)) {
1220 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1221 { title => $c->call_number->record->to_fieldmapper,
1222 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1223 patron => $hold->usr->to_fieldmapper,
1224 copy => $c->to_fieldmapper,
1225 requestor => $hold->requestor->to_fieldmapper,
1226 request_lib => $hold->request_lib->to_fieldmapper,
1230 last unless(@capturable);
1231 $rand = int(rand(scalar(@capturable)));
1236 sub create_prox_list {
1242 for my $cp (@$copies) {
1243 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1244 next unless (defined($prox));
1245 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1246 push @{$prox_list[$prox]}, $cp;
1251 sub volume_hold_capture {
1256 if (!defined($vols)) {
1258 $vols = [ asset::call_number->search( id => $hold->target ) ];
1259 $cache{cns}{$_->id} = $_ for (@$vols);
1260 } catch Error with {
1262 die "Could not retrieve initial volume list:\n\n$e\n";
1266 my @v_ids = map { $_->id } @$vols;
1270 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1272 } catch Error with {
1274 warn "Could not retrieve copy list:\n\n$e\n";
1277 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1280 sub title_hold_capture {
1285 if (!defined($titles)) {
1287 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1288 $cache{titles}{$_->id} = $_ for (@$titles);
1289 } catch Error with {
1291 die "Could not retrieve initial title list:\n\n$e\n";
1295 my @t_ids = map { $_->id } @$titles;
1298 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1300 } catch Error with {
1302 warn "Could not retrieve volume list:\n\n$e\n";
1305 $cache{cns}{$_->id} = $_ for (@$cn_list);
1307 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1310 sub metarecord_hold_capture {
1316 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1318 } catch Error with {
1320 die "Could not retrieve initial title list:\n\n$e\n";
1324 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1326 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1328 } catch Error with {
1330 die "Could not retrieve format-pruned title list:\n\n$e\n";
1334 $cache{titles}{$_->id} = $_ for (@$titles);
1335 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);