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',
163 sub auto_thaw_frozen_holds {
167 local $OpenILS::Application::Storage::WRITE = 1;
169 my $holds = action::hold_request->table;
171 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
173 my $sth = action::hold_request->db_Main->prepare_cached($sql);
179 __PACKAGE__->register_method(
180 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
184 method => 'auto_thaw_frozen_holds',
190 my $grace = shift || '';
192 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
197 __PACKAGE__->register_method(
198 api_name => 'open-ils.storage.action.circulation.overdue',
201 method => 'grab_overdue',
209 my $limit = int(shift()) || 10;
210 my $age = shift() || '0 seconds';
215 "actor.org_unit_descendants($pl, $depth)" :
216 "actor.org_unit_descendants($pl)" ;
218 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $pl, $cp, $age);
220 FROM action.hold_request h
221 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
222 JOIN $descendents d ON (d.id = h.pickup_lib)
223 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = d.id)
224 WHERE hm.target_copy = ?
225 AND AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL)
226 AND h.capture_time IS NULL
227 AND h.cancel_time IS NULL
230 h.selection_depth DESC,
235 $client->respond( $_ ) for ( @$ids );
238 __PACKAGE__->register_method(
239 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
242 method => 'nearest_hold',
245 sub next_resp_group_id {
249 # XXX This is not replication safe!!!
251 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
252 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
256 __PACKAGE__->register_method(
257 api_name => 'open-ils.storage.action.survey_response.next_group_id',
259 method => 'next_resp_group_id',
262 sub patron_circ_summary {
267 return undef unless ($id);
268 my $c_table = action::circulation->table;
269 my $b_table = money::billing->table;
271 $log->debug("Retrieving patron summary for id $id", DEBUG);
273 my $select = <<" SQL";
274 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
276 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
278 AND c.xact_finish IS NULL
280 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
281 OR c.stop_fines IS NULL
285 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
287 __PACKAGE__->register_method(
288 api_name => 'open-ils.storage.action.circulation.patron_summary',
290 method => 'patron_circ_summary',
293 #XXX Fix stored proc calls
294 sub find_local_surveys {
299 return undef unless ($ou);
300 my $s_table = action::survey->table;
302 my $select = <<" SQL";
305 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
306 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
309 my $sth = action::survey->db_Main->prepare_cached($select);
312 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
316 __PACKAGE__->register_method(
317 api_name => 'open-ils.storage.action.survey.all',
320 method => 'find_local_surveys',
323 #XXX Fix stored proc calls
324 sub find_opac_surveys {
329 return undef unless ($ou);
330 my $s_table = action::survey->table;
332 my $select = <<" SQL";
335 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
336 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
340 my $sth = action::survey->db_Main->prepare_cached($select);
343 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
347 __PACKAGE__->register_method(
348 api_name => 'open-ils.storage.action.survey.opac',
351 method => 'find_opac_surveys',
358 my $limit = shift || 10;
359 my $offset = shift || 0;
361 return undef unless ($ou);
362 my $h_table = action::hold_request->table;
363 my $a_table = asset::copy->table;
365 my $idlist = 1 if ($self->api_name =~/id_list/o);
367 my $select = <<" SQL";
370 JOIN $a_table a ON (h.current_copy = a.id)
372 AND h.capture_time IS NULL
373 AND h.cancel_time IS NULL
374 ORDER BY h.request_time ASC
379 my $sth = action::survey->db_Main->prepare_cached($select);
383 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
385 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
390 __PACKAGE__->register_method(
391 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
395 "Returns the hold ids for a specific library's pull list.",
396 [ [org_unit => "The library's org id", "number"],
397 [limit => 'An optional page size, defaults to 10', 'number'],
398 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
400 ['A list of holds for the stated library to pull for', 'array']
402 method => 'hold_pull_list',
404 __PACKAGE__->register_method(
405 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
409 "Returns the holds for a specific library's pull list.",
410 [ [org_unit => "The library's org id", "number"],
411 [limit => 'An optional page size, defaults to 10', 'number'],
412 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
414 ['A list of holds for the stated library to pull for', 'array']
416 method => 'hold_pull_list',
419 sub find_optional_surveys {
424 return undef unless ($ou);
425 my $s_table = action::survey->table;
427 my $select = <<" SQL";
430 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
431 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
432 AND s.required IS FALSE;
435 my $sth = action::survey->db_Main->prepare_cached($select);
438 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
442 __PACKAGE__->register_method(
443 api_name => 'open-ils.storage.action.survey.optional',
446 method => 'find_optional_surveys',
449 sub find_required_surveys {
454 return undef unless ($ou);
455 my $s_table = action::survey->table;
457 my $select = <<" SQL";
460 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
461 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
462 AND s.required IS TRUE;
465 my $sth = action::survey->db_Main->prepare_cached($select);
468 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
472 __PACKAGE__->register_method(
473 api_name => 'open-ils.storage.action.survey.required',
476 method => 'find_required_surveys',
479 sub find_usr_summary_surveys {
484 return undef unless ($ou);
485 my $s_table = action::survey->table;
487 my $select = <<" SQL";
490 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
491 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
492 AND s.usr_summary IS TRUE;
495 my $sth = action::survey->db_Main->prepare_cached($select);
498 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
502 __PACKAGE__->register_method(
503 api_name => 'open-ils.storage.action.survey.usr_summary',
506 method => 'find_usr_summary_surveys',
515 my $overbill = shift;
517 local $OpenILS::Application::Storage::WRITE = 1;
521 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
523 push @circs, overdue_circs($grace);
526 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
528 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
532 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
533 $log->debug("Cleaning up after previous transaction\n");
534 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
536 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
537 $log->info("Processing circ ".$c->id."...\n");
540 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
542 my $due = $due_dt->epoch;
544 my $fine_interval = interval_to_seconds( $c->fine_interval );
546 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
548 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
549 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
552 $due -= ($due % $fine_interval) + $tz_offset_s;
553 $now -= ($now % $fine_interval) + $tz_offset_s;
557 "ARG! Overdue circulation ".$c->id.
558 " for item ".$c->target_copy.
559 " (user ".$c->usr.").\n".
560 "\tItem was due on or before: ".localtime($due)."\n");
562 my @fines = money::billing->search_where(
564 billing_type => 'Overdue materials',
565 billing_ts => { '>' => $c->due_date } },
566 { order_by => 'billing_ts DESC'}
570 my $fine = $fines[$f_idx] if (@fines);
572 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
575 my $current_fine_total = 0;
576 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
580 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
581 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
583 $log->info( "Potential first billing for circ ".$c->id );
587 if (my $h = $hoo{$c->circ_lib}) {
589 $log->info( "Circ lib has an hours-of-operation entry" );
590 # find the day after the due date...
591 $due_dt = $due_dt->add( days => 1 );
593 # get the day of the week for that day...
594 my $dow = $due_dt->day_of_week_0;
595 my $dow_open = "dow_${dow}_open";
596 my $dow_close = "dow_${dow}_close";
599 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
600 # if the circ lib is closed, add a day to the grace period...
603 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
604 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
606 $due_dt = $due_dt->add( days => 1 );
607 $dow = $due_dt->day_of_week_0;
608 $dow_open = "dow_${dow}_open";
609 $dow_close = "dow_${dow}_close";
613 # and check for up to a week
614 last if ($count > 6);
621 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
622 if ($pending_fine_count < 1 + $grace) {
623 $client->respond( "\tNo fines to create. " );
624 if ($grace && $now < $due + $fine_interval * $grace) {
625 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
626 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
628 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
633 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
635 my $recuring_fine = int($c->recuring_fine * 100);
636 my $max_fine = int($c->max_fine * 100);
638 my ($latest_billing_ts, $latest_amount) = ('',0);
639 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
641 if ($current_fine_total >= $max_fine) {
642 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
644 "\tMaximum fine level of ".$c->max_fine.
645 " reached for this circulation.\n".
646 "\tNo more fines will be generated.\n" );
650 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
652 my $dow = $billing_ts->day_of_week_0();
653 my $dow_open = "dow_${dow}_open";
654 my $dow_close = "dow_${dow}_close";
656 if (my $h = $hoo{$c->circ_lib}) {
657 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
660 my $timestamptz = $billing_ts->strftime('%FT%T%z');
661 my @cl = actor::org_unit::closed_date->search_where(
662 { close_start => { '<=' => $timestamptz },
663 close_end => { '>=' => $timestamptz },
664 org_unit => $c->circ_lib }
668 $current_fine_total += $recuring_fine;
669 $latest_amount += $recuring_fine;
670 $latest_billing_ts = $timestamptz;
672 money::billing->create(
674 note => "System Generated Overdue Fine",
675 billing_type => "Overdue materials",
676 amount => sprintf('%0.2f', $recuring_fine/100),
677 billing_ts => $timestamptz,
683 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
684 if ($latest_billing_ts and $latest_amount);
686 $self->method_lookup('open-ils.storage.transaction.commit')->run;
689 'open-ils.penalty.patron_penalty.calculate',
690 { patron => $c->usr->to_fieldmapper,
698 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
699 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
700 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
701 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
705 __PACKAGE__->register_method(
706 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
709 method => 'generate_fines',
714 sub new_hold_copy_targeter {
717 my $check_expire = shift;
718 my $one_hold = shift;
720 local $OpenILS::Application::Storage::WRITE = 1;
726 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
727 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
728 } elsif ( $check_expire ) {
730 # what's the retarget time threashold?
732 $check_expire ||= '12h';
733 $check_expire = interval_to_seconds( $check_expire );
735 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
738 my $expire_threshold = sprintf(
739 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
740 $year, $mon, $mday, $hour, $min, $sec
743 # find all the holds holds needing retargeting
744 $holds = [ action::hold_request->search_where(
745 { capture_time => undef,
746 fulfillment_time => undef,
747 cancel_time => undef,
749 prev_check_time => { '<=' => $expire_threshold },
751 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
753 # find all the holds holds needing first time targeting
754 push @$holds, action::hold_request->search(
755 capture_time => undef,
756 fulfillment_time => undef,
757 prev_check_time => undef,
759 cancel_time => undef,
760 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
763 # find all the holds holds needing first time targeting ONLY
764 $holds = [ action::hold_request->search(
765 capture_time => undef,
766 fulfillment_time => undef,
767 prev_check_time => undef,
768 cancel_time => undef,
770 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
774 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
777 my @closed = actor::org_unit::closed_date->search_where(
778 { close_start => { '<=', 'now' },
779 close_end => { '>=', 'now' } }
785 for my $hold (@$holds) {
787 #start a transaction if needed
788 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
789 $log->debug("Cleaning up after previous transaction\n");
790 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
792 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
793 $log->info("Processing hold ".$hold->id."...\n");
795 #first, re-fetch the hold, to make sure it's not captured already
796 $hold = action::hold_request->retrieve( $hold->id );
797 die "OK\n" if (!$hold or $hold->capture_time);
799 # remove old auto-targeting maps
800 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
801 $_->delete for (@oldmaps);
806 # find filters for MR holds
807 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
809 # find all the potential copies
810 if ($hold->hold_type eq 'M') {
813 metabib::record_descriptor
815 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
816 ( $types ? (item_type => [split '', $types]) : () ),
817 ( $formats ? (item_form => [split '', $formats]) : () ),
818 ( $lang ? (item_lang => $lang) : () ),
822 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
823 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
825 for my $cn ( @{ $rtree->call_numbers } ) {
827 asset::copy->search_where(
828 { id => [map {$_->id} @{ $cn->copies }],
830 ) if ($cn && @{ $cn->copies });
833 } elsif ($hold->hold_type eq 'T') {
835 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
836 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
839 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
843 for my $cn ( @{ $rtree->call_numbers } ) {
845 asset::copy->search_where(
846 { id => [map {$_->id} @{ $cn->copies }],
848 ) if ($cn && @{ $cn->copies });
850 } elsif ($hold->hold_type eq 'V') {
852 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
853 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
856 asset::copy->search_where(
857 { id => [map {$_->id} @{ $vtree->copies }],
859 ) if ($vtree && @{ $vtree->copies });
861 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
862 my $_cp = asset::copy->retrieve($hold->target);
863 push @$all_copies, $_cp if $_cp;
867 @$all_copies = grep { isTrue($_->status->holdable) &&
868 isTrue($_->location->holdable) &&
869 isTrue($_->holdable) &&
873 # let 'em know we're still working
874 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
876 # if we have no copies ...
877 if (!ref $all_copies || !@$all_copies) {
878 $log->info("\tNo copies available for targeting at all!\n");
879 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
881 $hold->update( { prev_check_time => 'today', current_copy => undef } );
882 $self->method_lookup('open-ils.storage.transaction.commit')->run;
886 my $copy_count = @$all_copies;
888 # map the potentials, so that we can pick up checkins
889 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
890 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
892 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
895 for my $c (@$all_copies) {
897 next if ($c->id eq $hold->current_copy);
900 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
902 # target of another hold
903 next if (action::hold_request
905 { current_copy => $c->id,
906 fulfillment_time => undef,
907 cancel_time => undef,
912 # we passed all three, keep it
913 push @good_copies, $c if ($c);
914 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
917 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
919 my $old_best = $hold->current_copy;
920 $hold->update({ current_copy => undef }) if ($old_best);
922 if (!scalar(@good_copies)) {
923 $log->info("\tNo (non-current) copies eligible to fill the hold.");
926 grep { $old_best eq $_ } @$all_copies &&
927 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
929 # the old copy is still available
930 $log->debug("\tPushing current_copy back onto the targeting list");
931 push @good_copies, $old_best;
933 # oops, old copy is not available
934 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
935 $hold->update( { prev_check_time => 'today' } );
936 $self->method_lookup('open-ils.storage.transaction.commit')->run;
937 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
942 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
947 $_->circ_lib == $hold->pickup_lib
951 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
953 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
954 my $best = choose_nearest_copy($hold, $prox_list);
955 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
958 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
959 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
961 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
963 $best = choose_nearest_copy($hold, $prox_list);
966 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
968 # hold wasn't fulfilled, record the fact
970 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
971 action::unfulfilled_hold_list->create(
972 { hold => ''.$hold->id,
973 current_copy => ''.$old_best->id,
974 circ_lib => ''.$old_best->circ_lib,
979 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
980 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
985 { current_copy => $old_best->id,
986 fulfillment_time => undef,
987 cancel_time => undef,
991 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
992 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
994 $hold->update( { prev_check_time => 'now' } );
995 $log->info( "\tThere were no targetable copies for the hold" );
998 $self->method_lookup('open-ils.storage.transaction.commit')->run;
999 $log->info("\tProcessing of hold ".$hold->id." complete.");
1002 { hold => $hold->id,
1003 old_target => ($old_best ? $old_best->id : undef),
1004 eligible_copies => $copy_count,
1005 target => ($best ? $best->id : undef) };
1010 $log->error("Processing of hold failed: $e");
1011 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1012 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1019 __PACKAGE__->register_method(
1020 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1022 method => 'new_hold_copy_targeter',
1027 my %cache = (titles => {}, cns => {});
1028 sub hold_copy_targeter {
1031 my $check_expire = shift;
1032 my $one_hold = shift;
1034 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1035 $self->{user_filter}->connect;
1036 $self->{client} = $client;
1039 $check_expire ||= '12h';
1040 $check_expire = interval_to_seconds( $check_expire );
1042 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1045 my $expire_threshold = sprintf(
1046 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1047 $year, $mon, $mday, $hour, $min, $sec
1051 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1053 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1057 %cache = (titles => {}, cns => {});
1061 $holds = [ action::hold_request->search(id => $one_hold) ];
1063 $holds = [ action::hold_request->search_where(
1064 { capture_time => undef,
1065 prev_check_time => { '<=' => $expire_threshold },
1067 { order_by => 'request_time,prev_check_time' } ) ];
1068 push @$holds, action::hold_request->search_where(
1069 { capture_time => undef,
1070 prev_check_time => undef,
1072 { order_by => 'request_time' } );
1074 } catch Error with {
1076 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1079 for my $hold (@$holds) {
1081 #action::hold_request->db_Main->begin_work;
1082 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1083 $client->respond("Cleaning up after previous transaction\n");
1084 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1086 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1087 $client->respond("Processing hold ".$hold->id."...\n");
1091 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1092 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1094 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1095 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1097 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1098 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1100 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1102 unless (ref $copies || !@$copies) {
1103 $client->respond("\tNo copies available for targeting at all!\n");
1107 for my $c (@$copies) {
1108 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1109 push @good_copies, $c if ($c);
1112 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1114 my $old_best = $hold->current_copy;
1115 $hold->update({ current_copy => undef });
1117 if (!scalar(@good_copies)) {
1118 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1119 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1120 $client->respond("\tPushing current_copy back onto the targeting list\n");
1121 push @good_copies, asset::copy->retrieve( $old_best );
1123 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1129 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1130 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1132 my $best = choose_nearest_copy($hold, $prox_list);
1135 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1136 $best = choose_nearest_copy($hold, $prox_list);
1140 # hold wasn't fulfilled, record the fact
1142 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1143 action::unfulfilled_hold_list->create(
1144 { hold => ''.$hold->id,
1145 current_copy => ''.$old_best->id,
1146 circ_lib => ''.$old_best->circ_lib,
1151 $hold->update( { current_copy => ''.$best->id } );
1152 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1155 $hold->update( { prev_check_time => 'now' } );
1156 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1158 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1159 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1161 #action::hold_request->dbi_commit;
1165 $log->error("Processing of hold failed: $e");
1166 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1167 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1168 #action::hold_request->dbi_rollback;
1172 $self->{user_filter}->disconnect;
1173 $self->{user_filter}->finish;
1174 delete $$self{user_filter};
1177 __PACKAGE__->register_method(
1178 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1181 method => 'hold_copy_targeter',
1185 sub copy_hold_capture {
1190 if (!defined($cps)) {
1192 $cps = [ asset::copy->search( id => $hold->target ) ];
1193 } catch Error with {
1195 die "Could not retrieve initial volume list:\n\n$e\n";
1199 my @copies = grep { $_->holdable } @$cps;
1201 for (my $i = 0; $i < @$cps; $i++) {
1202 next unless $$cps[$i];
1204 my $cn = $cache{cns}{$copies[$i]->call_number};
1205 my $rec = $cache{titles}{$cn->record};
1206 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1207 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1208 $copies[$i] = undef if (
1210 !$self->{user_filter}->request(
1211 'open-ils.circ.permit_hold',
1212 $hold->to_fieldmapper, do {
1213 my $cp_fm = $copies[$i]->to_fieldmapper;
1214 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1215 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1216 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1219 { title => $rec->to_fieldmapper,
1220 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1221 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1224 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1227 @copies = grep { $_ } @copies;
1229 my $count = @copies;
1231 return unless ($count);
1233 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1236 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1237 for my $c (@copies) {
1238 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1240 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1246 sub choose_nearest_copy {
1248 my $prox_list = shift;
1250 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1251 next unless (ref $$prox_list[$p]);
1253 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1254 next unless (@capturable);
1256 my $rand = int(rand(scalar(@capturable)));
1257 while (my ($c) = splice(@capturable,$rand)) {
1258 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1259 { title => $c->call_number->record->to_fieldmapper,
1260 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1261 patron => $hold->usr->to_fieldmapper,
1262 copy => $c->to_fieldmapper,
1263 requestor => $hold->requestor->to_fieldmapper,
1264 request_lib => $hold->request_lib->to_fieldmapper,
1265 pickup_lib => $hold->pickup_lib->id,
1269 last unless(@capturable);
1270 $rand = int(rand(scalar(@capturable)));
1275 sub create_prox_list {
1281 for my $cp (@$copies) {
1282 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1283 next unless (defined($prox));
1284 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1285 push @{$prox_list[$prox]}, $cp;
1290 sub volume_hold_capture {
1295 if (!defined($vols)) {
1297 $vols = [ asset::call_number->search( id => $hold->target ) ];
1298 $cache{cns}{$_->id} = $_ for (@$vols);
1299 } catch Error with {
1301 die "Could not retrieve initial volume list:\n\n$e\n";
1305 my @v_ids = map { $_->id } @$vols;
1309 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1311 } catch Error with {
1313 warn "Could not retrieve copy list:\n\n$e\n";
1316 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1319 sub title_hold_capture {
1324 if (!defined($titles)) {
1326 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1327 $cache{titles}{$_->id} = $_ for (@$titles);
1328 } catch Error with {
1330 die "Could not retrieve initial title list:\n\n$e\n";
1334 my @t_ids = map { $_->id } @$titles;
1337 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1339 } catch Error with {
1341 warn "Could not retrieve volume list:\n\n$e\n";
1344 $cache{cns}{$_->id} = $_ for (@$cn_list);
1346 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1349 sub metarecord_hold_capture {
1355 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1357 } catch Error with {
1359 die "Could not retrieve initial title list:\n\n$e\n";
1363 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1365 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1367 } catch Error with {
1369 die "Could not retrieve format-pruned title list:\n\n$e\n";
1373 $cache{titles}{$_->id} = $_ for (@$titles);
1374 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);