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 $status_filter = '';
368 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
370 my $select = <<" SQL";
373 JOIN $a_table a ON (h.current_copy = a.id)
375 AND h.capture_time IS NULL
376 AND h.cancel_time IS NULL
378 ORDER BY h.request_time ASC
383 my $sth = action::survey->db_Main->prepare_cached($select);
387 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
389 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
394 __PACKAGE__->register_method(
395 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
399 "Returns the hold ids for a specific library's pull list.",
400 [ [org_unit => "The library's org id", "number"],
401 [limit => 'An optional page size, defaults to 10', 'number'],
402 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
404 ['A list of holds for the stated library to pull for', 'array']
406 method => 'hold_pull_list',
408 __PACKAGE__->register_method(
409 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
413 "Returns the holds for a specific library's pull list.",
414 [ [org_unit => "The library's org id", "number"],
415 [limit => 'An optional page size, defaults to 10', 'number'],
416 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
418 ['A list of holds for the stated library to pull for', 'array']
420 method => 'hold_pull_list',
422 __PACKAGE__->register_method(
423 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
427 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
428 [ [org_unit => "The library's org id", "number"],
429 [limit => 'An optional page size, defaults to 10', 'number'],
430 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
432 ['A list of holds for the stated library to pull for', 'array']
434 method => 'hold_pull_list',
436 __PACKAGE__->register_method(
437 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
441 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
442 [ [org_unit => "The library's org id", "number"],
443 [limit => 'An optional page size, defaults to 10', 'number'],
444 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
446 ['A list of holds for the stated library to pull for', 'array']
448 method => 'hold_pull_list',
451 sub find_optional_surveys {
456 return undef unless ($ou);
457 my $s_table = action::survey->table;
459 my $select = <<" SQL";
462 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
463 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
464 AND s.required IS FALSE;
467 my $sth = action::survey->db_Main->prepare_cached($select);
470 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
474 __PACKAGE__->register_method(
475 api_name => 'open-ils.storage.action.survey.optional',
478 method => 'find_optional_surveys',
481 sub find_required_surveys {
486 return undef unless ($ou);
487 my $s_table = action::survey->table;
489 my $select = <<" SQL";
492 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
493 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
494 AND s.required IS TRUE;
497 my $sth = action::survey->db_Main->prepare_cached($select);
500 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
504 __PACKAGE__->register_method(
505 api_name => 'open-ils.storage.action.survey.required',
508 method => 'find_required_surveys',
511 sub find_usr_summary_surveys {
516 return undef unless ($ou);
517 my $s_table = action::survey->table;
519 my $select = <<" SQL";
522 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
523 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
524 AND s.usr_summary IS TRUE;
527 my $sth = action::survey->db_Main->prepare_cached($select);
530 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
534 __PACKAGE__->register_method(
535 api_name => 'open-ils.storage.action.survey.usr_summary',
538 method => 'find_usr_summary_surveys',
547 my $overbill = shift;
549 local $OpenILS::Application::Storage::WRITE = 1;
553 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
555 push @circs, overdue_circs($grace);
558 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
560 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
564 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
565 $log->debug("Cleaning up after previous transaction\n");
566 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
568 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
569 $log->info("Processing circ ".$c->id."...\n");
572 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
574 my $due = $due_dt->epoch;
576 my $fine_interval = interval_to_seconds( $c->fine_interval );
578 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
580 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
581 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
584 $due -= ($due % $fine_interval) + $tz_offset_s;
585 $now -= ($now % $fine_interval) + $tz_offset_s;
589 "ARG! Overdue circulation ".$c->id.
590 " for item ".$c->target_copy.
591 " (user ".$c->usr.").\n".
592 "\tItem was due on or before: ".localtime($due)."\n");
594 my @fines = money::billing->search_where(
596 billing_type => 'Overdue materials',
597 billing_ts => { '>' => $c->due_date } },
598 { order_by => 'billing_ts DESC'}
602 my $fine = $fines[$f_idx] if (@fines);
604 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
607 my $current_fine_total = 0;
608 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
612 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
613 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
615 $log->info( "Potential first billing for circ ".$c->id );
619 if (my $h = $hoo{$c->circ_lib}) {
621 $log->info( "Circ lib has an hours-of-operation entry" );
622 # find the day after the due date...
623 $due_dt = $due_dt->add( days => 1 );
625 # get the day of the week for that day...
626 my $dow = $due_dt->day_of_week_0;
627 my $dow_open = "dow_${dow}_open";
628 my $dow_close = "dow_${dow}_close";
631 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
632 # if the circ lib is closed, add a day to the grace period...
635 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
636 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
638 $due_dt = $due_dt->add( days => 1 );
639 $dow = $due_dt->day_of_week_0;
640 $dow_open = "dow_${dow}_open";
641 $dow_close = "dow_${dow}_close";
645 # and check for up to a week
646 last if ($count > 6);
653 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
654 if ($pending_fine_count < 1 + $grace) {
655 $client->respond( "\tNo fines to create. " );
656 if ($grace && $now < $due + $fine_interval * $grace) {
657 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
658 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
660 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
665 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
667 my $recuring_fine = int($c->recuring_fine * 100);
668 my $max_fine = int($c->max_fine * 100);
670 my ($latest_billing_ts, $latest_amount) = ('',0);
671 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
673 if ($current_fine_total >= $max_fine) {
674 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
676 "\tMaximum fine level of ".$c->max_fine.
677 " reached for this circulation.\n".
678 "\tNo more fines will be generated.\n" );
682 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
684 my $dow = $billing_ts->day_of_week_0();
685 my $dow_open = "dow_${dow}_open";
686 my $dow_close = "dow_${dow}_close";
688 if (my $h = $hoo{$c->circ_lib}) {
689 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
692 my $timestamptz = $billing_ts->strftime('%FT%T%z');
693 my @cl = actor::org_unit::closed_date->search_where(
694 { close_start => { '<=' => $timestamptz },
695 close_end => { '>=' => $timestamptz },
696 org_unit => $c->circ_lib }
700 $current_fine_total += $recuring_fine;
701 $latest_amount += $recuring_fine;
702 $latest_billing_ts = $timestamptz;
704 money::billing->create(
706 note => "System Generated Overdue Fine",
707 billing_type => "Overdue materials",
708 amount => sprintf('%0.2f', $recuring_fine/100),
709 billing_ts => $timestamptz,
715 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
716 if ($latest_billing_ts and $latest_amount);
718 $self->method_lookup('open-ils.storage.transaction.commit')->run;
721 'open-ils.penalty.patron_penalty.calculate',
722 { patron => $c->usr->to_fieldmapper,
730 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
731 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
732 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
733 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
737 __PACKAGE__->register_method(
738 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
741 method => 'generate_fines',
746 sub new_hold_copy_targeter {
749 my $check_expire = shift;
750 my $one_hold = shift;
752 local $OpenILS::Application::Storage::WRITE = 1;
758 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
759 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
760 } elsif ( $check_expire ) {
762 # what's the retarget time threashold?
764 $check_expire ||= '12h';
765 $check_expire = interval_to_seconds( $check_expire );
767 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
770 my $expire_threshold = sprintf(
771 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
772 $year, $mon, $mday, $hour, $min, $sec
775 # find all the holds holds needing retargeting
776 $holds = [ action::hold_request->search_where(
777 { capture_time => undef,
778 fulfillment_time => undef,
779 cancel_time => undef,
781 prev_check_time => { '<=' => $expire_threshold },
783 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
785 # find all the holds holds needing first time targeting
786 push @$holds, action::hold_request->search(
787 capture_time => undef,
788 fulfillment_time => undef,
789 prev_check_time => undef,
791 cancel_time => undef,
792 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
795 # find all the holds holds needing first time targeting ONLY
796 $holds = [ action::hold_request->search(
797 capture_time => undef,
798 fulfillment_time => undef,
799 prev_check_time => undef,
800 cancel_time => undef,
802 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
806 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
809 my @closed = actor::org_unit::closed_date->search_where(
810 { close_start => { '<=', 'now' },
811 close_end => { '>=', 'now' } }
817 for my $hold (@$holds) {
819 #start a transaction if needed
820 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
821 $log->debug("Cleaning up after previous transaction\n");
822 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
824 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
825 $log->info("Processing hold ".$hold->id."...\n");
827 #first, re-fetch the hold, to make sure it's not captured already
828 $hold = action::hold_request->retrieve( $hold->id );
829 die "OK\n" if (!$hold or $hold->capture_time);
831 # remove old auto-targeting maps
832 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
833 $_->delete for (@oldmaps);
838 # find filters for MR holds
839 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
841 # find all the potential copies
842 if ($hold->hold_type eq 'M') {
845 metabib::record_descriptor
847 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
848 ( $types ? (item_type => [split '', $types]) : () ),
849 ( $formats ? (item_form => [split '', $formats]) : () ),
850 ( $lang ? (item_lang => $lang) : () ),
854 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
855 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
857 for my $cn ( @{ $rtree->call_numbers } ) {
859 asset::copy->search_where(
860 { id => [map {$_->id} @{ $cn->copies }],
862 ) if ($cn && @{ $cn->copies });
865 } elsif ($hold->hold_type eq 'T') {
867 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
868 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
871 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
875 for my $cn ( @{ $rtree->call_numbers } ) {
877 asset::copy->search_where(
878 { id => [map {$_->id} @{ $cn->copies }],
880 ) if ($cn && @{ $cn->copies });
882 } elsif ($hold->hold_type eq 'V') {
884 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
885 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
888 asset::copy->search_where(
889 { id => [map {$_->id} @{ $vtree->copies }],
891 ) if ($vtree && @{ $vtree->copies });
893 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
894 my $_cp = asset::copy->retrieve($hold->target);
895 push @$all_copies, $_cp if $_cp;
899 @$all_copies = grep { isTrue($_->status->holdable) &&
900 isTrue($_->location->holdable) &&
901 isTrue($_->holdable) &&
905 # let 'em know we're still working
906 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
908 # if we have no copies ...
909 if (!ref $all_copies || !@$all_copies) {
910 $log->info("\tNo copies available for targeting at all!\n");
911 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
913 $hold->update( { prev_check_time => 'today', current_copy => undef } );
914 $self->method_lookup('open-ils.storage.transaction.commit')->run;
918 my $copy_count = @$all_copies;
920 # map the potentials, so that we can pick up checkins
921 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
922 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
924 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
927 for my $c (@$all_copies) {
929 next if ($c->id eq $hold->current_copy);
932 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
934 # target of another hold
935 next if (action::hold_request
937 { current_copy => $c->id,
938 fulfillment_time => undef,
939 cancel_time => undef,
944 # we passed all three, keep it
945 push @good_copies, $c if ($c);
946 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
949 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
951 my $old_best = $hold->current_copy;
952 $hold->update({ current_copy => undef }) if ($old_best);
954 if (!scalar(@good_copies)) {
955 $log->info("\tNo (non-current) copies eligible to fill the hold.");
958 grep { $old_best eq $_ } @$all_copies &&
959 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
961 # the old copy is still available
962 $log->debug("\tPushing current_copy back onto the targeting list");
963 push @good_copies, $old_best;
965 # oops, old copy is not available
966 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
967 $hold->update( { prev_check_time => 'today' } );
968 $self->method_lookup('open-ils.storage.transaction.commit')->run;
969 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
974 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
979 $_->circ_lib == $hold->pickup_lib
983 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
985 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
986 my $best = choose_nearest_copy($hold, $prox_list);
987 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
990 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
991 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
993 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
995 $best = choose_nearest_copy($hold, $prox_list);
998 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1000 # hold wasn't fulfilled, record the fact
1002 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1003 action::unfulfilled_hold_list->create(
1004 { hold => ''.$hold->id,
1005 current_copy => ''.$old_best->id,
1006 circ_lib => ''.$old_best->circ_lib,
1011 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1012 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1015 action::hold_request
1017 { current_copy => $old_best->id,
1018 fulfillment_time => undef,
1019 cancel_time => undef,
1023 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1024 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1026 $hold->update( { prev_check_time => 'now' } );
1027 $log->info( "\tThere were no targetable copies for the hold" );
1030 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1031 $log->info("\tProcessing of hold ".$hold->id." complete.");
1034 { hold => $hold->id,
1035 old_target => ($old_best ? $old_best->id : undef),
1036 eligible_copies => $copy_count,
1037 target => ($best ? $best->id : undef) };
1042 $log->error("Processing of hold failed: $e");
1043 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1044 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1051 __PACKAGE__->register_method(
1052 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1054 method => 'new_hold_copy_targeter',
1059 my %cache = (titles => {}, cns => {});
1060 sub hold_copy_targeter {
1063 my $check_expire = shift;
1064 my $one_hold = shift;
1066 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1067 $self->{user_filter}->connect;
1068 $self->{client} = $client;
1071 $check_expire ||= '12h';
1072 $check_expire = interval_to_seconds( $check_expire );
1074 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1077 my $expire_threshold = sprintf(
1078 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1079 $year, $mon, $mday, $hour, $min, $sec
1083 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1085 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1089 %cache = (titles => {}, cns => {});
1093 $holds = [ action::hold_request->search(id => $one_hold) ];
1095 $holds = [ action::hold_request->search_where(
1096 { capture_time => undef,
1097 prev_check_time => { '<=' => $expire_threshold },
1099 { order_by => 'request_time,prev_check_time' } ) ];
1100 push @$holds, action::hold_request->search_where(
1101 { capture_time => undef,
1102 prev_check_time => undef,
1104 { order_by => 'request_time' } );
1106 } catch Error with {
1108 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1111 for my $hold (@$holds) {
1113 #action::hold_request->db_Main->begin_work;
1114 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1115 $client->respond("Cleaning up after previous transaction\n");
1116 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1118 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1119 $client->respond("Processing hold ".$hold->id."...\n");
1123 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1124 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1126 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1127 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1129 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1130 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1132 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1134 unless (ref $copies || !@$copies) {
1135 $client->respond("\tNo copies available for targeting at all!\n");
1139 for my $c (@$copies) {
1140 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1141 push @good_copies, $c if ($c);
1144 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1146 my $old_best = $hold->current_copy;
1147 $hold->update({ current_copy => undef });
1149 if (!scalar(@good_copies)) {
1150 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1151 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1152 $client->respond("\tPushing current_copy back onto the targeting list\n");
1153 push @good_copies, asset::copy->retrieve( $old_best );
1155 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1161 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1162 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1164 my $best = choose_nearest_copy($hold, $prox_list);
1167 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1168 $best = choose_nearest_copy($hold, $prox_list);
1172 # hold wasn't fulfilled, record the fact
1174 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1175 action::unfulfilled_hold_list->create(
1176 { hold => ''.$hold->id,
1177 current_copy => ''.$old_best->id,
1178 circ_lib => ''.$old_best->circ_lib,
1183 $hold->update( { current_copy => ''.$best->id } );
1184 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1187 $hold->update( { prev_check_time => 'now' } );
1188 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1190 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1191 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1193 #action::hold_request->dbi_commit;
1197 $log->error("Processing of hold failed: $e");
1198 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1199 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1200 #action::hold_request->dbi_rollback;
1204 $self->{user_filter}->disconnect;
1205 $self->{user_filter}->finish;
1206 delete $$self{user_filter};
1209 __PACKAGE__->register_method(
1210 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1213 method => 'hold_copy_targeter',
1217 sub copy_hold_capture {
1222 if (!defined($cps)) {
1224 $cps = [ asset::copy->search( id => $hold->target ) ];
1225 } catch Error with {
1227 die "Could not retrieve initial volume list:\n\n$e\n";
1231 my @copies = grep { $_->holdable } @$cps;
1233 for (my $i = 0; $i < @$cps; $i++) {
1234 next unless $$cps[$i];
1236 my $cn = $cache{cns}{$copies[$i]->call_number};
1237 my $rec = $cache{titles}{$cn->record};
1238 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1239 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1240 $copies[$i] = undef if (
1242 !$self->{user_filter}->request(
1243 'open-ils.circ.permit_hold',
1244 $hold->to_fieldmapper, do {
1245 my $cp_fm = $copies[$i]->to_fieldmapper;
1246 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1247 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1248 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1251 { title => $rec->to_fieldmapper,
1252 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1253 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1256 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1259 @copies = grep { $_ } @copies;
1261 my $count = @copies;
1263 return unless ($count);
1265 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1268 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1269 for my $c (@copies) {
1270 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1272 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1278 sub choose_nearest_copy {
1280 my $prox_list = shift;
1282 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1283 next unless (ref $$prox_list[$p]);
1285 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1286 next unless (@capturable);
1288 my $rand = int(rand(scalar(@capturable)));
1289 while (my ($c) = splice(@capturable,$rand)) {
1290 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1291 { title => $c->call_number->record->to_fieldmapper,
1292 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1293 patron => $hold->usr->to_fieldmapper,
1294 copy => $c->to_fieldmapper,
1295 requestor => $hold->requestor->to_fieldmapper,
1296 request_lib => $hold->request_lib->to_fieldmapper,
1297 pickup_lib => $hold->pickup_lib->id,
1301 last unless(@capturable);
1302 $rand = int(rand(scalar(@capturable)));
1307 sub create_prox_list {
1313 for my $cp (@$copies) {
1314 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1315 next unless (defined($prox));
1316 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1317 push @{$prox_list[$prox]}, $cp;
1322 sub volume_hold_capture {
1327 if (!defined($vols)) {
1329 $vols = [ asset::call_number->search( id => $hold->target ) ];
1330 $cache{cns}{$_->id} = $_ for (@$vols);
1331 } catch Error with {
1333 die "Could not retrieve initial volume list:\n\n$e\n";
1337 my @v_ids = map { $_->id } @$vols;
1341 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1343 } catch Error with {
1345 warn "Could not retrieve copy list:\n\n$e\n";
1348 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1351 sub title_hold_capture {
1356 if (!defined($titles)) {
1358 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1359 $cache{titles}{$_->id} = $_ for (@$titles);
1360 } catch Error with {
1362 die "Could not retrieve initial title list:\n\n$e\n";
1366 my @t_ids = map { $_->id } @$titles;
1369 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1371 } catch Error with {
1373 warn "Could not retrieve volume list:\n\n$e\n";
1376 $cache{cns}{$_->id} = $_ for (@$cn_list);
1378 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1381 sub metarecord_hold_capture {
1387 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1389 } catch Error with {
1391 die "Could not retrieve initial title list:\n\n$e\n";
1395 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1397 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1399 } catch Error with {
1401 die "Could not retrieve format-pruned title list:\n\n$e\n";
1405 $cache{titles}{$_->id} = $_ for (@$titles);
1406 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);