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;
186 my $age = shift() || '0 seconds';
192 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp, $pl, $age);
194 FROM action.hold_request h
195 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
196 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
197 WHERE hm.target_copy = ?
199 AND AGE(h.request_time) > ?
200 AND h.capture_time IS NULL
201 AND h.cancel_time IS NULL
204 h.selection_depth DESC,
209 $client->respond( $_ ) for ( @$ids );
212 __PACKAGE__->register_method(
213 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
216 method => 'nearest_hold',
219 sub next_resp_group_id {
223 # XXX This is not replication safe!!!
225 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
226 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
230 __PACKAGE__->register_method(
231 api_name => 'open-ils.storage.action.survey_response.next_group_id',
233 method => 'next_resp_group_id',
236 sub patron_circ_summary {
241 return undef unless ($id);
242 my $c_table = action::circulation->table;
243 my $b_table = money::billing->table;
245 $log->debug("Retrieving patron summary for id $id", DEBUG);
247 my $select = <<" SQL";
248 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
250 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
252 AND c.xact_finish IS NULL
254 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
255 OR c.stop_fines IS NULL
259 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
261 __PACKAGE__->register_method(
262 api_name => 'open-ils.storage.action.circulation.patron_summary',
264 method => 'patron_circ_summary',
267 #XXX Fix stored proc calls
268 sub find_local_surveys {
273 return undef unless ($ou);
274 my $s_table = action::survey->table;
276 my $select = <<" SQL";
279 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
280 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
283 my $sth = action::survey->db_Main->prepare_cached($select);
286 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
290 __PACKAGE__->register_method(
291 api_name => 'open-ils.storage.action.survey.all',
294 method => 'find_local_surveys',
297 #XXX Fix stored proc calls
298 sub find_opac_surveys {
303 return undef unless ($ou);
304 my $s_table = action::survey->table;
306 my $select = <<" SQL";
309 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
310 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
314 my $sth = action::survey->db_Main->prepare_cached($select);
317 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
321 __PACKAGE__->register_method(
322 api_name => 'open-ils.storage.action.survey.opac',
325 method => 'find_opac_surveys',
332 my $limit = shift || 10;
333 my $offset = shift || 0;
335 return undef unless ($ou);
336 my $h_table = action::hold_request->table;
337 my $a_table = asset::copy->table;
339 my $idlist = 1 if ($self->api_name =~/id_list/o);
341 my $select = <<" SQL";
344 JOIN $a_table a ON (h.current_copy = a.id)
346 AND h.capture_time IS NULL
347 AND h.cancel_time IS NULL
348 ORDER BY h.request_time ASC
353 my $sth = action::survey->db_Main->prepare_cached($select);
357 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
359 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
364 __PACKAGE__->register_method(
365 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
369 "Returns the hold ids for a specific library's pull list.",
370 [ [org_unit => "The library's org id", "number"],
371 [limit => 'An optional page size, defaults to 10', 'number'],
372 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
374 ['A list of holds for the stated library to pull for', 'array']
376 method => 'hold_pull_list',
378 __PACKAGE__->register_method(
379 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
383 "Returns the holds for a specific library's pull list.",
384 [ [org_unit => "The library's org id", "number"],
385 [limit => 'An optional page size, defaults to 10', 'number'],
386 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
388 ['A list of holds for the stated library to pull for', 'array']
390 method => 'hold_pull_list',
393 sub find_optional_surveys {
398 return undef unless ($ou);
399 my $s_table = action::survey->table;
401 my $select = <<" SQL";
404 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
405 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
406 AND s.required IS FALSE;
409 my $sth = action::survey->db_Main->prepare_cached($select);
412 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
416 __PACKAGE__->register_method(
417 api_name => 'open-ils.storage.action.survey.optional',
420 method => 'find_optional_surveys',
423 sub find_required_surveys {
428 return undef unless ($ou);
429 my $s_table = action::survey->table;
431 my $select = <<" SQL";
434 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
435 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
436 AND s.required IS TRUE;
439 my $sth = action::survey->db_Main->prepare_cached($select);
442 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
446 __PACKAGE__->register_method(
447 api_name => 'open-ils.storage.action.survey.required',
450 method => 'find_required_surveys',
453 sub find_usr_summary_surveys {
458 return undef unless ($ou);
459 my $s_table = action::survey->table;
461 my $select = <<" SQL";
464 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
465 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
466 AND s.usr_summary IS TRUE;
469 my $sth = action::survey->db_Main->prepare_cached($select);
472 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
476 __PACKAGE__->register_method(
477 api_name => 'open-ils.storage.action.survey.usr_summary',
480 method => 'find_usr_summary_surveys',
489 my $overbill = shift;
491 local $OpenILS::Application::Storage::WRITE = 1;
495 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
497 push @circs, overdue_circs($grace);
500 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
502 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
506 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
507 $log->debug("Cleaning up after previous transaction\n");
508 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
510 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
511 $log->info("Processing circ ".$c->id."...\n");
514 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
516 my $due = $due_dt->epoch;
518 my $fine_interval = interval_to_seconds( $c->fine_interval );
520 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
522 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
523 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
526 $due -= ($due % $fine_interval) + $tz_offset_s;
527 $now -= ($now % $fine_interval) + $tz_offset_s;
531 "ARG! Overdue circulation ".$c->id.
532 " for item ".$c->target_copy.
533 " (user ".$c->usr.").\n".
534 "\tItem was due on or before: ".localtime($due)."\n");
536 my @fines = money::billing->search_where(
538 billing_type => 'Overdue materials',
539 billing_ts => { '>' => $c->due_date } },
540 { order_by => 'billing_ts DESC'}
544 my $fine = $fines[$f_idx] if (@fines);
546 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
549 my $current_fine_total = 0;
550 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
554 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
555 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
557 $log->info( "Potential first billing for circ ".$c->id );
561 if (my $h = $hoo{$c->circ_lib}) {
563 $log->info( "Circ lib has an hours-of-operation entry" );
564 # find the day after the due date...
565 $due_dt = $due_dt->add( days => 1 );
567 # get the day of the week for that day...
568 my $dow = $due_dt->day_of_week_0;
569 my $dow_open = "dow_${dow}_open";
570 my $dow_close = "dow_${dow}_close";
573 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
574 # if the circ lib is closed, add a day to the grace period...
577 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
578 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
580 $due_dt = $due_dt->add( days => 1 );
581 $dow = $due_dt->day_of_week_0;
582 $dow_open = "dow_${dow}_open";
583 $dow_close = "dow_${dow}_close";
587 # and check for up to a week
588 last if ($count > 6);
595 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
596 if ($pending_fine_count < 1 + $grace) {
597 $client->respond( "\tNo fines to create. " );
598 if ($grace && $now < $due + $fine_interval * $grace) {
599 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
600 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
602 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
607 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
609 my $recuring_fine = int($c->recuring_fine * 100);
610 my $max_fine = int($c->max_fine * 100);
612 my ($latest_billing_ts, $latest_amount) = ('',0);
613 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
615 if ($current_fine_total >= $max_fine) {
616 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
618 "\tMaximum fine level of ".$c->max_fine.
619 " reached for this circulation.\n".
620 "\tNo more fines will be generated.\n" );
624 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
626 my $dow = $billing_ts->day_of_week_0();
627 my $dow_open = "dow_${dow}_open";
628 my $dow_close = "dow_${dow}_close";
630 if (my $h = $hoo{$c->circ_lib}) {
631 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
634 my $timestamptz = $billing_ts->strftime('%FT%T%z');
635 my @cl = actor::org_unit::closed_date->search_where(
636 { close_start => { '<=' => $timestamptz },
637 close_end => { '>=' => $timestamptz },
638 org_unit => $c->circ_lib }
642 $current_fine_total += $recuring_fine;
643 $latest_amount += $recuring_fine;
644 $latest_billing_ts = $timestamptz;
646 money::billing->create(
648 note => "System Generated Overdue Fine",
649 billing_type => "Overdue materials",
650 amount => sprintf('%0.2f', $recuring_fine/100),
651 billing_ts => $timestamptz,
657 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
658 if ($latest_billing_ts and $latest_amount);
660 $self->method_lookup('open-ils.storage.transaction.commit')->run;
663 'open-ils.penalty.patron_penalty.calculate',
664 { patron => $c->usr->to_fieldmapper,
672 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
673 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
674 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
675 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
679 __PACKAGE__->register_method(
680 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
683 method => 'generate_fines',
688 sub new_hold_copy_targeter {
691 my $check_expire = shift;
692 my $one_hold = shift;
694 local $OpenILS::Application::Storage::WRITE = 1;
700 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
701 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
702 } elsif ( $check_expire ) {
704 # what's the retarget time threashold?
706 $check_expire ||= '12h';
707 $check_expire = interval_to_seconds( $check_expire );
709 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
712 my $expire_threshold = sprintf(
713 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
714 $year, $mon, $mday, $hour, $min, $sec
717 # find all the holds holds needing retargeting
718 $holds = [ action::hold_request->search_where(
719 { capture_time => undef,
720 fulfillment_time => undef,
721 cancel_time => undef,
723 prev_check_time => { '<=' => $expire_threshold },
725 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
727 # find all the holds holds needing first time targeting
728 push @$holds, action::hold_request->search(
729 capture_time => undef,
730 fulfillment_time => undef,
731 prev_check_time => undef,
733 cancel_time => undef,
734 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
737 # find all the holds holds needing first time targeting ONLY
738 $holds = [ action::hold_request->search(
739 capture_time => undef,
740 fulfillment_time => undef,
741 prev_check_time => undef,
742 cancel_time => undef,
744 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
748 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
751 my @closed = actor::org_unit::closed_date->search_where(
752 { close_start => { '<=', 'now' },
753 close_end => { '>=', 'now' } }
759 for my $hold (@$holds) {
761 #start a transaction if needed
762 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
763 $log->debug("Cleaning up after previous transaction\n");
764 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
766 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
767 $log->info("Processing hold ".$hold->id."...\n");
769 #first, re-fetch the hold, to make sure it's not captured already
770 $hold = action::hold_request->retrieve( $hold->id );
771 die "OK\n" if (!$hold or $hold->capture_time);
773 # remove old auto-targeting maps
774 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
775 $_->delete for (@oldmaps);
780 # find filters for MR holds
781 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
783 # find all the potential copies
784 if ($hold->hold_type eq 'M') {
787 metabib::record_descriptor
789 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
790 ( $types ? (item_type => [split '', $types]) : () ),
791 ( $formats ? (item_form => [split '', $formats]) : () ),
792 ( $lang ? (item_lang => $lang) : () ),
796 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
797 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
799 for my $cn ( @{ $rtree->call_numbers } ) {
801 asset::copy->search_where(
802 { id => [map {$_->id} @{ $cn->copies }],
804 ) if ($cn && @{ $cn->copies });
807 } elsif ($hold->hold_type eq 'T') {
809 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
810 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
813 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
817 for my $cn ( @{ $rtree->call_numbers } ) {
819 asset::copy->search_where(
820 { id => [map {$_->id} @{ $cn->copies }],
822 ) if ($cn && @{ $cn->copies });
824 } elsif ($hold->hold_type eq 'V') {
826 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
827 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
830 asset::copy->search_where(
831 { id => [map {$_->id} @{ $vtree->copies }],
833 ) if ($vtree && @{ $vtree->copies });
835 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
836 my $_cp = asset::copy->retrieve($hold->target);
837 push @$all_copies, $_cp if $_cp;
841 @$all_copies = grep { isTrue($_->status->holdable) &&
842 isTrue($_->location->holdable) &&
843 isTrue($_->holdable) &&
847 # let 'em know we're still working
848 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
850 # if we have no copies ...
851 if (!ref $all_copies || !@$all_copies) {
852 $log->info("\tNo copies available for targeting at all!\n");
853 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
855 $hold->update( { prev_check_time => 'today', current_copy => undef } );
856 $self->method_lookup('open-ils.storage.transaction.commit')->run;
860 my $copy_count = @$all_copies;
862 # map the potentials, so that we can pick up checkins
863 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
864 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
866 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
869 for my $c (@$all_copies) {
871 next if ($c->id eq $hold->current_copy);
874 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
876 # target of another hold
877 next if (action::hold_request
879 { current_copy => $c->id,
880 fulfillment_time => undef,
881 cancel_time => undef,
886 # we passed all three, keep it
887 push @good_copies, $c if ($c);
888 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
891 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
893 my $old_best = $hold->current_copy;
894 $hold->update({ current_copy => undef }) if ($old_best);
896 if (!scalar(@good_copies)) {
897 $log->info("\tNo (non-current) copies eligible to fill the hold.");
900 grep { $old_best eq $_ } @$all_copies &&
901 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
903 # the old copy is still available
904 $log->debug("\tPushing current_copy back onto the targeting list");
905 push @good_copies, $old_best;
907 # oops, old copy is not available
908 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
909 $hold->update( { prev_check_time => 'today' } );
910 $self->method_lookup('open-ils.storage.transaction.commit')->run;
911 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
916 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
921 $_->circ_lib == $hold->pickup_lib
925 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
927 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
928 my $best = choose_nearest_copy($hold, $prox_list);
929 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
932 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
933 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
935 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
937 $best = choose_nearest_copy($hold, $prox_list);
940 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
942 # hold wasn't fulfilled, record the fact
944 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
945 action::unfulfilled_hold_list->create(
946 { hold => ''.$hold->id,
947 current_copy => ''.$old_best->id,
948 circ_lib => ''.$old_best->circ_lib,
953 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
954 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
959 { current_copy => $old_best->id,
960 fulfillment_time => undef,
961 cancel_time => undef,
965 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
966 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
968 $hold->update( { prev_check_time => 'now' } );
969 $log->info( "\tThere were no targetable copies for the hold" );
972 $self->method_lookup('open-ils.storage.transaction.commit')->run;
973 $log->info("\tProcessing of hold ".$hold->id." complete.");
977 old_target => ($old_best ? $old_best->id : undef),
978 eligible_copies => $copy_count,
979 target => ($best ? $best->id : undef) };
984 $log->error("Processing of hold failed: $e");
985 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
986 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
993 __PACKAGE__->register_method(
994 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
996 method => 'new_hold_copy_targeter',
1001 my %cache = (titles => {}, cns => {});
1002 sub hold_copy_targeter {
1005 my $check_expire = shift;
1006 my $one_hold = shift;
1008 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1009 $self->{user_filter}->connect;
1010 $self->{client} = $client;
1013 $check_expire ||= '12h';
1014 $check_expire = interval_to_seconds( $check_expire );
1016 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1019 my $expire_threshold = sprintf(
1020 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1021 $year, $mon, $mday, $hour, $min, $sec
1025 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1027 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1031 %cache = (titles => {}, cns => {});
1035 $holds = [ action::hold_request->search(id => $one_hold) ];
1037 $holds = [ action::hold_request->search_where(
1038 { capture_time => undef,
1039 prev_check_time => { '<=' => $expire_threshold },
1041 { order_by => 'request_time,prev_check_time' } ) ];
1042 push @$holds, action::hold_request->search_where(
1043 { capture_time => undef,
1044 prev_check_time => undef,
1046 { order_by => 'request_time' } );
1048 } catch Error with {
1050 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1053 for my $hold (@$holds) {
1055 #action::hold_request->db_Main->begin_work;
1056 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1057 $client->respond("Cleaning up after previous transaction\n");
1058 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1060 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1061 $client->respond("Processing hold ".$hold->id."...\n");
1065 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1066 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1068 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1069 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1071 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1072 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1074 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1076 unless (ref $copies || !@$copies) {
1077 $client->respond("\tNo copies available for targeting at all!\n");
1081 for my $c (@$copies) {
1082 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1083 push @good_copies, $c if ($c);
1086 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1088 my $old_best = $hold->current_copy;
1089 $hold->update({ current_copy => undef });
1091 if (!scalar(@good_copies)) {
1092 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1093 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1094 $client->respond("\tPushing current_copy back onto the targeting list\n");
1095 push @good_copies, asset::copy->retrieve( $old_best );
1097 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1103 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1104 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1106 my $best = choose_nearest_copy($hold, $prox_list);
1109 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1110 $best = choose_nearest_copy($hold, $prox_list);
1114 # hold wasn't fulfilled, record the fact
1116 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1117 action::unfulfilled_hold_list->create(
1118 { hold => ''.$hold->id,
1119 current_copy => ''.$old_best->id,
1120 circ_lib => ''.$old_best->circ_lib,
1125 $hold->update( { current_copy => ''.$best->id } );
1126 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1129 $hold->update( { prev_check_time => 'now' } );
1130 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1132 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1133 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1135 #action::hold_request->dbi_commit;
1139 $log->error("Processing of hold failed: $e");
1140 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1141 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1142 #action::hold_request->dbi_rollback;
1146 $self->{user_filter}->disconnect;
1147 $self->{user_filter}->finish;
1148 delete $$self{user_filter};
1151 __PACKAGE__->register_method(
1152 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1155 method => 'hold_copy_targeter',
1159 sub copy_hold_capture {
1164 if (!defined($cps)) {
1166 $cps = [ asset::copy->search( id => $hold->target ) ];
1167 } catch Error with {
1169 die "Could not retrieve initial volume list:\n\n$e\n";
1173 my @copies = grep { $_->holdable } @$cps;
1175 for (my $i = 0; $i < @$cps; $i++) {
1176 next unless $$cps[$i];
1178 my $cn = $cache{cns}{$copies[$i]->call_number};
1179 my $rec = $cache{titles}{$cn->record};
1180 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1181 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1182 $copies[$i] = undef if (
1184 !$self->{user_filter}->request(
1185 'open-ils.circ.permit_hold',
1186 $hold->to_fieldmapper, do {
1187 my $cp_fm = $copies[$i]->to_fieldmapper;
1188 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1189 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1190 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1193 { title => $rec->to_fieldmapper,
1194 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1195 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1198 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1201 @copies = grep { $_ } @copies;
1203 my $count = @copies;
1205 return unless ($count);
1207 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1210 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1211 for my $c (@copies) {
1212 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1214 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1220 sub choose_nearest_copy {
1222 my $prox_list = shift;
1224 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1225 next unless (ref $$prox_list[$p]);
1227 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1228 next unless (@capturable);
1230 my $rand = int(rand(scalar(@capturable)));
1231 while (my ($c) = splice(@capturable,$rand)) {
1232 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1233 { title => $c->call_number->record->to_fieldmapper,
1234 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1235 patron => $hold->usr->to_fieldmapper,
1236 copy => $c->to_fieldmapper,
1237 requestor => $hold->requestor->to_fieldmapper,
1238 request_lib => $hold->request_lib->to_fieldmapper,
1239 pickup_lib => $hold->pickup_lib->id,
1243 last unless(@capturable);
1244 $rand = int(rand(scalar(@capturable)));
1249 sub create_prox_list {
1255 for my $cp (@$copies) {
1256 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1257 next unless (defined($prox));
1258 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1259 push @{$prox_list[$prox]}, $cp;
1264 sub volume_hold_capture {
1269 if (!defined($vols)) {
1271 $vols = [ asset::call_number->search( id => $hold->target ) ];
1272 $cache{cns}{$_->id} = $_ for (@$vols);
1273 } catch Error with {
1275 die "Could not retrieve initial volume list:\n\n$e\n";
1279 my @v_ids = map { $_->id } @$vols;
1283 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1285 } catch Error with {
1287 warn "Could not retrieve copy list:\n\n$e\n";
1290 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1293 sub title_hold_capture {
1298 if (!defined($titles)) {
1300 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1301 $cache{titles}{$_->id} = $_ for (@$titles);
1302 } catch Error with {
1304 die "Could not retrieve initial title list:\n\n$e\n";
1308 my @t_ids = map { $_->id } @$titles;
1311 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1313 } catch Error with {
1315 warn "Could not retrieve volume list:\n\n$e\n";
1318 $cache{cns}{$_->id} = $_ for (@$cn_list);
1320 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1323 sub metarecord_hold_capture {
1329 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1331 } catch Error with {
1333 die "Could not retrieve initial title list:\n\n$e\n";
1337 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1339 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1341 } catch Error with {
1343 die "Could not retrieve format-pruned title list:\n\n$e\n";
1347 $cache{titles}{$_->id} = $_ for (@$titles);
1348 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);