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';
212 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
214 FROM action.hold_request h
215 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
216 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
217 WHERE hm.target_copy = ?
218 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
219 AND h.capture_time IS NULL
220 AND h.cancel_time IS NULL
221 AND h.frozen IS FALSE
224 h.selection_depth DESC,
229 $client->respond( $_ ) for ( @$ids );
232 __PACKAGE__->register_method(
233 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
236 method => 'nearest_hold',
239 sub next_resp_group_id {
243 # XXX This is not replication safe!!!
245 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
246 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
250 __PACKAGE__->register_method(
251 api_name => 'open-ils.storage.action.survey_response.next_group_id',
253 method => 'next_resp_group_id',
256 sub patron_circ_summary {
261 return undef unless ($id);
262 my $c_table = action::circulation->table;
263 my $b_table = money::billing->table;
265 $log->debug("Retrieving patron summary for id $id", DEBUG);
267 my $select = <<" SQL";
268 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
270 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
272 AND c.xact_finish IS NULL
274 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
275 OR c.stop_fines IS NULL
279 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
281 __PACKAGE__->register_method(
282 api_name => 'open-ils.storage.action.circulation.patron_summary',
284 method => 'patron_circ_summary',
287 #XXX Fix stored proc calls
288 sub find_local_surveys {
293 return undef unless ($ou);
294 my $s_table = action::survey->table;
296 my $select = <<" SQL";
299 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
300 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
303 my $sth = action::survey->db_Main->prepare_cached($select);
306 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
310 __PACKAGE__->register_method(
311 api_name => 'open-ils.storage.action.survey.all',
314 method => 'find_local_surveys',
317 #XXX Fix stored proc calls
318 sub find_opac_surveys {
323 return undef unless ($ou);
324 my $s_table = action::survey->table;
326 my $select = <<" SQL";
329 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
330 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
334 my $sth = action::survey->db_Main->prepare_cached($select);
337 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
341 __PACKAGE__->register_method(
342 api_name => 'open-ils.storage.action.survey.opac',
345 method => 'find_opac_surveys',
352 my $limit = shift || 10;
353 my $offset = shift || 0;
355 return undef unless ($ou);
356 my $h_table = action::hold_request->table;
357 my $a_table = asset::copy->table;
359 my $idlist = 1 if ($self->api_name =~/id_list/o);
361 my $status_filter = '';
362 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
364 my $select = <<" SQL";
367 JOIN $a_table a ON (h.current_copy = a.id)
369 AND h.capture_time IS NULL
370 AND h.cancel_time IS NULL
372 ORDER BY h.request_time ASC
377 my $sth = action::survey->db_Main->prepare_cached($select);
381 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
383 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
388 __PACKAGE__->register_method(
389 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
393 "Returns the hold ids for a specific library's pull list.",
394 [ [org_unit => "The library's org id", "number"],
395 [limit => 'An optional page size, defaults to 10', 'number'],
396 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
398 ['A list of holds for the stated library to pull for', 'array']
400 method => 'hold_pull_list',
402 __PACKAGE__->register_method(
403 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
407 "Returns the holds for a specific library's pull list.",
408 [ [org_unit => "The library's org id", "number"],
409 [limit => 'An optional page size, defaults to 10', 'number'],
410 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
412 ['A list of holds for the stated library to pull for', 'array']
414 method => 'hold_pull_list',
416 __PACKAGE__->register_method(
417 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
421 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
422 [ [org_unit => "The library's org id", "number"],
423 [limit => 'An optional page size, defaults to 10', 'number'],
424 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
426 ['A list of holds for the stated library to pull for', 'array']
428 method => 'hold_pull_list',
430 __PACKAGE__->register_method(
431 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
435 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
436 [ [org_unit => "The library's org id", "number"],
437 [limit => 'An optional page size, defaults to 10', 'number'],
438 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
440 ['A list of holds for the stated library to pull for', 'array']
442 method => 'hold_pull_list',
445 sub find_optional_surveys {
450 return undef unless ($ou);
451 my $s_table = action::survey->table;
453 my $select = <<" SQL";
456 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
457 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
458 AND s.required IS FALSE;
461 my $sth = action::survey->db_Main->prepare_cached($select);
464 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
468 __PACKAGE__->register_method(
469 api_name => 'open-ils.storage.action.survey.optional',
472 method => 'find_optional_surveys',
475 sub find_required_surveys {
480 return undef unless ($ou);
481 my $s_table = action::survey->table;
483 my $select = <<" SQL";
486 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
487 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
488 AND s.required IS TRUE;
491 my $sth = action::survey->db_Main->prepare_cached($select);
494 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
498 __PACKAGE__->register_method(
499 api_name => 'open-ils.storage.action.survey.required',
502 method => 'find_required_surveys',
505 sub find_usr_summary_surveys {
510 return undef unless ($ou);
511 my $s_table = action::survey->table;
513 my $select = <<" SQL";
516 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
517 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
518 AND s.usr_summary IS TRUE;
521 my $sth = action::survey->db_Main->prepare_cached($select);
524 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
528 __PACKAGE__->register_method(
529 api_name => 'open-ils.storage.action.survey.usr_summary',
532 method => 'find_usr_summary_surveys',
541 my $overbill = shift;
543 local $OpenILS::Application::Storage::WRITE = 1;
547 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
549 push @circs, overdue_circs($grace);
552 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
554 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
558 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
559 $log->debug("Cleaning up after previous transaction\n");
560 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
562 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
563 $log->info("Processing circ ".$c->id."...\n");
566 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
568 my $due = $due_dt->epoch;
570 my $fine_interval = interval_to_seconds( $c->fine_interval );
572 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
574 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
575 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
578 $due -= ($due % $fine_interval) + $tz_offset_s;
579 $now -= ($now % $fine_interval) + $tz_offset_s;
583 "ARG! Overdue circulation ".$c->id.
584 " for item ".$c->target_copy.
585 " (user ".$c->usr.").\n".
586 "\tItem was due on or before: ".localtime($due)."\n");
588 my @fines = money::billing->search_where(
590 billing_type => 'Overdue materials',
591 billing_ts => { '>' => $c->due_date } },
592 { order_by => 'billing_ts DESC'}
596 my $fine = $fines[$f_idx] if (@fines);
598 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
601 my $current_fine_total = 0;
602 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
606 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
607 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
609 $log->info( "Potential first billing for circ ".$c->id );
613 if (my $h = $hoo{$c->circ_lib}) {
615 $log->info( "Circ lib has an hours-of-operation entry" );
616 # find the day after the due date...
617 $due_dt = $due_dt->add( days => 1 );
619 # get the day of the week for that day...
620 my $dow = $due_dt->day_of_week_0;
621 my $dow_open = "dow_${dow}_open";
622 my $dow_close = "dow_${dow}_close";
625 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
626 # if the circ lib is closed, add a day to the grace period...
629 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
630 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
632 $due_dt = $due_dt->add( days => 1 );
633 $dow = $due_dt->day_of_week_0;
634 $dow_open = "dow_${dow}_open";
635 $dow_close = "dow_${dow}_close";
639 # and check for up to a week
640 last if ($count > 6);
647 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
648 if ($pending_fine_count < 1 + $grace) {
649 $client->respond( "\tNo fines to create. " );
650 if ($grace && $now < $due + $fine_interval * $grace) {
651 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
652 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
654 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
659 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
661 my $recuring_fine = int($c->recuring_fine * 100);
662 my $max_fine = int($c->max_fine * 100);
664 my ($latest_billing_ts, $latest_amount) = ('',0);
665 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
667 if ($current_fine_total >= $max_fine) {
668 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
670 "\tMaximum fine level of ".$c->max_fine.
671 " reached for this circulation.\n".
672 "\tNo more fines will be generated.\n" );
676 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
678 my $dow = $billing_ts->day_of_week_0();
679 my $dow_open = "dow_${dow}_open";
680 my $dow_close = "dow_${dow}_close";
682 if (my $h = $hoo{$c->circ_lib}) {
683 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
686 my $timestamptz = $billing_ts->strftime('%FT%T%z');
687 my @cl = actor::org_unit::closed_date->search_where(
688 { close_start => { '<=' => $timestamptz },
689 close_end => { '>=' => $timestamptz },
690 org_unit => $c->circ_lib }
694 $current_fine_total += $recuring_fine;
695 $latest_amount += $recuring_fine;
696 $latest_billing_ts = $timestamptz;
698 money::billing->create(
700 note => "System Generated Overdue Fine",
701 billing_type => "Overdue materials",
702 amount => sprintf('%0.2f', $recuring_fine/100),
703 billing_ts => $timestamptz,
709 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
710 if ($latest_billing_ts and $latest_amount);
712 $self->method_lookup('open-ils.storage.transaction.commit')->run;
715 'open-ils.penalty.patron_penalty.calculate',
716 { patron => $c->usr->to_fieldmapper,
724 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
725 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
726 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
727 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
731 __PACKAGE__->register_method(
732 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
735 method => 'generate_fines',
740 sub new_hold_copy_targeter {
743 my $check_expire = shift;
744 my $one_hold = shift;
746 local $OpenILS::Application::Storage::WRITE = 1;
752 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
753 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
754 } elsif ( $check_expire ) {
756 # what's the retarget time threashold?
758 $check_expire ||= '12h';
759 $check_expire = interval_to_seconds( $check_expire );
761 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
764 my $expire_threshold = sprintf(
765 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
766 $year, $mon, $mday, $hour, $min, $sec
769 # find all the holds holds needing retargeting
770 $holds = [ action::hold_request->search_where(
771 { capture_time => undef,
772 fulfillment_time => undef,
773 cancel_time => undef,
775 prev_check_time => { '<=' => $expire_threshold },
777 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
779 # find all the holds holds needing first time targeting
780 push @$holds, action::hold_request->search(
781 capture_time => undef,
782 fulfillment_time => undef,
783 prev_check_time => undef,
785 cancel_time => undef,
786 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
789 # find all the holds holds needing first time targeting ONLY
790 $holds = [ action::hold_request->search(
791 capture_time => undef,
792 fulfillment_time => undef,
793 prev_check_time => undef,
794 cancel_time => undef,
796 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
800 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
803 my @closed = actor::org_unit::closed_date->search_where(
804 { close_start => { '<=', 'now' },
805 close_end => { '>=', 'now' } }
811 for my $hold (@$holds) {
813 #start a transaction if needed
814 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
815 $log->debug("Cleaning up after previous transaction\n");
816 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
818 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
819 $log->info("Processing hold ".$hold->id."...\n");
821 #first, re-fetch the hold, to make sure it's not captured already
822 $hold->remove_from_object_index();
823 $hold = action::hold_request->retrieve( $hold->id );
824 die "OK\n" if (!$hold or $hold->capture_time);
826 # remove old auto-targeting maps
827 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
828 $_->delete for (@oldmaps);
833 # find filters for MR holds
834 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
836 # find all the potential copies
837 if ($hold->hold_type eq 'M') {
840 metabib::record_descriptor
844 isTrue($_->deleted) ? () : ($_->id)
845 } metabib::metarecord->retrieve($hold->target)->source_records
847 ( $types ? (item_type => [split '', $types]) : () ),
848 ( $formats ? (item_form => [split '', $formats]) : () ),
849 ( $lang ? (item_lang => $lang) : () ),
853 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
854 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
856 for my $cn ( @{ $rtree->call_numbers } ) {
858 asset::copy->search_where(
859 { id => [map {$_->id} @{ $cn->copies }],
861 ) if ($cn && @{ $cn->copies });
864 } elsif ($hold->hold_type eq 'T') {
866 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
867 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
870 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
874 for my $cn ( @{ $rtree->call_numbers } ) {
876 asset::copy->search_where(
877 { id => [map {$_->id} @{ $cn->copies }],
879 ) if ($cn && @{ $cn->copies });
881 } elsif ($hold->hold_type eq 'V') {
883 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
884 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
887 asset::copy->search_where(
888 { id => [map {$_->id} @{ $vtree->copies }],
890 ) if ($vtree && @{ $vtree->copies });
892 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
893 my $_cp = asset::copy->retrieve($hold->target);
894 push @$all_copies, $_cp if $_cp;
898 @$all_copies = grep { isTrue($_->status->holdable) &&
899 isTrue($_->location->holdable) &&
900 isTrue($_->holdable) &&
904 # let 'em know we're still working
905 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
907 # if we have no copies ...
908 if (!ref $all_copies || !@$all_copies) {
909 $log->info("\tNo copies available for targeting at all!\n");
910 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
912 $hold->update( { prev_check_time => 'today', current_copy => undef } );
913 $self->method_lookup('open-ils.storage.transaction.commit')->run;
917 my $copy_count = @$all_copies;
919 # map the potentials, so that we can pick up checkins
920 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
921 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
923 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
926 for my $c (@$all_copies) {
928 next if ($c->id eq $hold->current_copy);
931 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
933 # target of another hold
934 next if (action::hold_request
936 { current_copy => $c->id,
937 fulfillment_time => undef,
938 cancel_time => undef,
943 # we passed all three, keep it
944 push @good_copies, $c if ($c);
945 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
948 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
950 my $old_best = $hold->current_copy;
951 $hold->update({ current_copy => undef }) if ($old_best);
953 if (!scalar(@good_copies)) {
954 $log->info("\tNo (non-current) copies eligible to fill the hold.");
955 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
956 # the old copy is still available
957 $log->debug("\tPushing current_copy back onto the targeting list");
958 push @good_copies, $old_best;
960 # oops, old copy is not available
961 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
962 $hold->update( { prev_check_time => 'today' } );
963 $self->method_lookup('open-ils.storage.transaction.commit')->run;
964 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
969 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
974 $_->circ_lib == $hold->pickup_lib
978 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
980 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
981 my $best = choose_nearest_copy($hold, $prox_list);
982 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
985 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
986 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
988 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
990 $best = choose_nearest_copy($hold, $prox_list);
993 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
995 # hold wasn't fulfilled, record the fact
997 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
998 action::unfulfilled_hold_list->create(
999 { hold => ''.$hold->id,
1000 current_copy => ''.$old_best->id,
1001 circ_lib => ''.$old_best->circ_lib,
1006 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1007 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1010 action::hold_request
1012 { current_copy => $old_best->id,
1013 fulfillment_time => undef,
1014 cancel_time => undef,
1018 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1019 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1021 $hold->update( { prev_check_time => 'now' } );
1022 $log->info( "\tThere were no targetable copies for the hold" );
1025 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1026 $log->info("\tProcessing of hold ".$hold->id." complete.");
1029 { hold => $hold->id,
1030 old_target => ($old_best ? $old_best->id : undef),
1031 eligible_copies => $copy_count,
1032 target => ($best ? $best->id : undef) };
1037 $log->error("Processing of hold failed: $e");
1038 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1039 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1046 __PACKAGE__->register_method(
1047 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1049 method => 'new_hold_copy_targeter',
1054 my %cache = (titles => {}, cns => {});
1055 sub hold_copy_targeter {
1058 my $check_expire = shift;
1059 my $one_hold = shift;
1061 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1062 $self->{user_filter}->connect;
1063 $self->{client} = $client;
1066 $check_expire ||= '12h';
1067 $check_expire = interval_to_seconds( $check_expire );
1069 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1072 my $expire_threshold = sprintf(
1073 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1074 $year, $mon, $mday, $hour, $min, $sec
1078 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1080 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1084 %cache = (titles => {}, cns => {});
1088 $holds = [ action::hold_request->search(id => $one_hold) ];
1090 $holds = [ action::hold_request->search_where(
1091 { capture_time => undef,
1092 prev_check_time => { '<=' => $expire_threshold },
1094 { order_by => 'request_time,prev_check_time' } ) ];
1095 push @$holds, action::hold_request->search_where(
1096 { capture_time => undef,
1097 prev_check_time => undef,
1099 { order_by => 'request_time' } );
1101 } catch Error with {
1103 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1106 for my $hold (@$holds) {
1108 #action::hold_request->db_Main->begin_work;
1109 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1110 $client->respond("Cleaning up after previous transaction\n");
1111 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1113 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1114 $client->respond("Processing hold ".$hold->id."...\n");
1118 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1119 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1121 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1122 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1124 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1125 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1127 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1129 unless (ref $copies || !@$copies) {
1130 $client->respond("\tNo copies available for targeting at all!\n");
1134 for my $c (@$copies) {
1135 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1136 push @good_copies, $c if ($c);
1139 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1141 my $old_best = $hold->current_copy;
1142 $hold->update({ current_copy => undef });
1144 if (!scalar(@good_copies)) {
1145 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1146 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1147 $client->respond("\tPushing current_copy back onto the targeting list\n");
1148 push @good_copies, asset::copy->retrieve( $old_best );
1150 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1156 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1157 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1159 my $best = choose_nearest_copy($hold, $prox_list);
1162 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1163 $best = choose_nearest_copy($hold, $prox_list);
1167 # hold wasn't fulfilled, record the fact
1169 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1170 action::unfulfilled_hold_list->create(
1171 { hold => ''.$hold->id,
1172 current_copy => ''.$old_best->id,
1173 circ_lib => ''.$old_best->circ_lib,
1178 $hold->update( { current_copy => ''.$best->id } );
1179 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1182 $hold->update( { prev_check_time => 'now' } );
1183 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1185 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1186 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1188 #action::hold_request->dbi_commit;
1192 $log->error("Processing of hold failed: $e");
1193 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1194 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1195 #action::hold_request->dbi_rollback;
1199 $self->{user_filter}->disconnect;
1200 $self->{user_filter}->finish;
1201 delete $$self{user_filter};
1204 __PACKAGE__->register_method(
1205 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1208 method => 'hold_copy_targeter',
1212 sub copy_hold_capture {
1217 if (!defined($cps)) {
1219 $cps = [ asset::copy->search( id => $hold->target ) ];
1220 } catch Error with {
1222 die "Could not retrieve initial volume list:\n\n$e\n";
1226 my @copies = grep { $_->holdable } @$cps;
1228 for (my $i = 0; $i < @$cps; $i++) {
1229 next unless $$cps[$i];
1231 my $cn = $cache{cns}{$copies[$i]->call_number};
1232 my $rec = $cache{titles}{$cn->record};
1233 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1234 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1235 $copies[$i] = undef if (
1237 !$self->{user_filter}->request(
1238 'open-ils.circ.permit_hold',
1239 $hold->to_fieldmapper, do {
1240 my $cp_fm = $copies[$i]->to_fieldmapper;
1241 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1242 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1243 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1246 { title => $rec->to_fieldmapper,
1247 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1248 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1251 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1254 @copies = grep { $_ } @copies;
1256 my $count = @copies;
1258 return unless ($count);
1260 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1263 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1264 for my $c (@copies) {
1265 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1267 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1273 sub choose_nearest_copy {
1275 my $prox_list = shift;
1277 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1278 next unless (ref $$prox_list[$p]);
1280 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1281 next unless (@capturable);
1283 my $rand = int(rand(scalar(@capturable)));
1284 while (my ($c) = splice(@capturable,$rand)) {
1285 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1286 { title => $c->call_number->record->to_fieldmapper,
1287 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1288 patron => $hold->usr->to_fieldmapper,
1289 copy => $c->to_fieldmapper,
1290 requestor => $hold->requestor->to_fieldmapper,
1291 request_lib => $hold->request_lib->to_fieldmapper,
1292 pickup_lib => $hold->pickup_lib->id,
1296 last unless(@capturable);
1297 $rand = int(rand(scalar(@capturable)));
1302 sub create_prox_list {
1308 for my $cp (@$copies) {
1309 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1310 next unless (defined($prox));
1311 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1312 push @{$prox_list[$prox]}, $cp;
1317 sub volume_hold_capture {
1322 if (!defined($vols)) {
1324 $vols = [ asset::call_number->search( id => $hold->target ) ];
1325 $cache{cns}{$_->id} = $_ for (@$vols);
1326 } catch Error with {
1328 die "Could not retrieve initial volume list:\n\n$e\n";
1332 my @v_ids = map { $_->id } @$vols;
1336 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1338 } catch Error with {
1340 warn "Could not retrieve copy list:\n\n$e\n";
1343 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1346 sub title_hold_capture {
1351 if (!defined($titles)) {
1353 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1354 $cache{titles}{$_->id} = $_ for (@$titles);
1355 } catch Error with {
1357 die "Could not retrieve initial title list:\n\n$e\n";
1361 my @t_ids = map { $_->id } @$titles;
1364 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1366 } catch Error with {
1368 warn "Could not retrieve volume list:\n\n$e\n";
1371 $cache{cns}{$_->id} = $_ for (@$cn_list);
1373 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1376 sub metarecord_hold_capture {
1382 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1384 } catch Error with {
1386 die "Could not retrieve initial title list:\n\n$e\n";
1390 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1392 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1394 } catch Error with {
1396 die "Could not retrieve format-pruned title list:\n\n$e\n";
1400 $cache{titles}{$_->id} = $_ for (@$titles);
1401 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);