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
223 h.selection_depth DESC,
228 $client->respond( $_ ) for ( @$ids );
231 __PACKAGE__->register_method(
232 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
235 method => 'nearest_hold',
238 sub next_resp_group_id {
242 # XXX This is not replication safe!!!
244 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
245 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
249 __PACKAGE__->register_method(
250 api_name => 'open-ils.storage.action.survey_response.next_group_id',
252 method => 'next_resp_group_id',
255 sub patron_circ_summary {
260 return undef unless ($id);
261 my $c_table = action::circulation->table;
262 my $b_table = money::billing->table;
264 $log->debug("Retrieving patron summary for id $id", DEBUG);
266 my $select = <<" SQL";
267 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
269 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
271 AND c.xact_finish IS NULL
273 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
274 OR c.stop_fines IS NULL
278 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
280 __PACKAGE__->register_method(
281 api_name => 'open-ils.storage.action.circulation.patron_summary',
283 method => 'patron_circ_summary',
286 #XXX Fix stored proc calls
287 sub find_local_surveys {
292 return undef unless ($ou);
293 my $s_table = action::survey->table;
295 my $select = <<" SQL";
298 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
299 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
302 my $sth = action::survey->db_Main->prepare_cached($select);
305 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
309 __PACKAGE__->register_method(
310 api_name => 'open-ils.storage.action.survey.all',
313 method => 'find_local_surveys',
316 #XXX Fix stored proc calls
317 sub find_opac_surveys {
322 return undef unless ($ou);
323 my $s_table = action::survey->table;
325 my $select = <<" SQL";
328 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
329 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
333 my $sth = action::survey->db_Main->prepare_cached($select);
336 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
340 __PACKAGE__->register_method(
341 api_name => 'open-ils.storage.action.survey.opac',
344 method => 'find_opac_surveys',
351 my $limit = shift || 10;
352 my $offset = shift || 0;
354 return undef unless ($ou);
355 my $h_table = action::hold_request->table;
356 my $a_table = asset::copy->table;
358 my $idlist = 1 if ($self->api_name =~/id_list/o);
360 my $status_filter = '';
361 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
363 my $select = <<" SQL";
366 JOIN $a_table a ON (h.current_copy = a.id)
368 AND h.capture_time IS NULL
369 AND h.cancel_time IS NULL
371 ORDER BY h.request_time ASC
376 my $sth = action::survey->db_Main->prepare_cached($select);
380 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
382 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
387 __PACKAGE__->register_method(
388 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
392 "Returns the hold ids for a specific library's pull list.",
393 [ [org_unit => "The library's org id", "number"],
394 [limit => 'An optional page size, defaults to 10', 'number'],
395 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
397 ['A list of holds for the stated library to pull for', 'array']
399 method => 'hold_pull_list',
401 __PACKAGE__->register_method(
402 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
406 "Returns the holds for a specific library's pull list.",
407 [ [org_unit => "The library's org id", "number"],
408 [limit => 'An optional page size, defaults to 10', 'number'],
409 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
411 ['A list of holds for the stated library to pull for', 'array']
413 method => 'hold_pull_list',
415 __PACKAGE__->register_method(
416 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
420 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
421 [ [org_unit => "The library's org id", "number"],
422 [limit => 'An optional page size, defaults to 10', 'number'],
423 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
425 ['A list of holds for the stated library to pull for', 'array']
427 method => 'hold_pull_list',
429 __PACKAGE__->register_method(
430 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
434 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
435 [ [org_unit => "The library's org id", "number"],
436 [limit => 'An optional page size, defaults to 10', 'number'],
437 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
439 ['A list of holds for the stated library to pull for', 'array']
441 method => 'hold_pull_list',
444 sub find_optional_surveys {
449 return undef unless ($ou);
450 my $s_table = action::survey->table;
452 my $select = <<" SQL";
455 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
456 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
457 AND s.required IS FALSE;
460 my $sth = action::survey->db_Main->prepare_cached($select);
463 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
467 __PACKAGE__->register_method(
468 api_name => 'open-ils.storage.action.survey.optional',
471 method => 'find_optional_surveys',
474 sub find_required_surveys {
479 return undef unless ($ou);
480 my $s_table = action::survey->table;
482 my $select = <<" SQL";
485 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
486 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
487 AND s.required IS TRUE;
490 my $sth = action::survey->db_Main->prepare_cached($select);
493 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
497 __PACKAGE__->register_method(
498 api_name => 'open-ils.storage.action.survey.required',
501 method => 'find_required_surveys',
504 sub find_usr_summary_surveys {
509 return undef unless ($ou);
510 my $s_table = action::survey->table;
512 my $select = <<" SQL";
515 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
516 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
517 AND s.usr_summary IS TRUE;
520 my $sth = action::survey->db_Main->prepare_cached($select);
523 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
527 __PACKAGE__->register_method(
528 api_name => 'open-ils.storage.action.survey.usr_summary',
531 method => 'find_usr_summary_surveys',
540 my $overbill = shift;
542 local $OpenILS::Application::Storage::WRITE = 1;
546 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
548 push @circs, overdue_circs($grace);
551 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
553 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
557 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
558 $log->debug("Cleaning up after previous transaction\n");
559 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
561 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
562 $log->info("Processing circ ".$c->id."...\n");
565 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
567 my $due = $due_dt->epoch;
569 my $fine_interval = interval_to_seconds( $c->fine_interval );
571 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
573 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
574 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
577 $due -= ($due % $fine_interval) + $tz_offset_s;
578 $now -= ($now % $fine_interval) + $tz_offset_s;
582 "ARG! Overdue circulation ".$c->id.
583 " for item ".$c->target_copy.
584 " (user ".$c->usr.").\n".
585 "\tItem was due on or before: ".localtime($due)."\n");
587 my @fines = money::billing->search_where(
589 billing_type => 'Overdue materials',
590 billing_ts => { '>' => $c->due_date } },
591 { order_by => 'billing_ts DESC'}
595 my $fine = $fines[$f_idx] if (@fines);
597 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
600 my $current_fine_total = 0;
601 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
605 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
606 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
608 $log->info( "Potential first billing for circ ".$c->id );
612 if (my $h = $hoo{$c->circ_lib}) {
614 $log->info( "Circ lib has an hours-of-operation entry" );
615 # find the day after the due date...
616 $due_dt = $due_dt->add( days => 1 );
618 # get the day of the week for that day...
619 my $dow = $due_dt->day_of_week_0;
620 my $dow_open = "dow_${dow}_open";
621 my $dow_close = "dow_${dow}_close";
624 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
625 # if the circ lib is closed, add a day to the grace period...
628 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
629 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
631 $due_dt = $due_dt->add( days => 1 );
632 $dow = $due_dt->day_of_week_0;
633 $dow_open = "dow_${dow}_open";
634 $dow_close = "dow_${dow}_close";
638 # and check for up to a week
639 last if ($count > 6);
646 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
647 if ($pending_fine_count < 1 + $grace) {
648 $client->respond( "\tNo fines to create. " );
649 if ($grace && $now < $due + $fine_interval * $grace) {
650 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
651 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
653 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
658 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
660 my $recuring_fine = int($c->recuring_fine * 100);
661 my $max_fine = int($c->max_fine * 100);
663 my ($latest_billing_ts, $latest_amount) = ('',0);
664 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
666 if ($current_fine_total >= $max_fine) {
667 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
669 "\tMaximum fine level of ".$c->max_fine.
670 " reached for this circulation.\n".
671 "\tNo more fines will be generated.\n" );
675 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
677 my $dow = $billing_ts->day_of_week_0();
678 my $dow_open = "dow_${dow}_open";
679 my $dow_close = "dow_${dow}_close";
681 if (my $h = $hoo{$c->circ_lib}) {
682 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
685 my $timestamptz = $billing_ts->strftime('%FT%T%z');
686 my @cl = actor::org_unit::closed_date->search_where(
687 { close_start => { '<=' => $timestamptz },
688 close_end => { '>=' => $timestamptz },
689 org_unit => $c->circ_lib }
693 $current_fine_total += $recuring_fine;
694 $latest_amount += $recuring_fine;
695 $latest_billing_ts = $timestamptz;
697 money::billing->create(
699 note => "System Generated Overdue Fine",
700 billing_type => "Overdue materials",
701 amount => sprintf('%0.2f', $recuring_fine/100),
702 billing_ts => $timestamptz,
708 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
709 if ($latest_billing_ts and $latest_amount);
711 $self->method_lookup('open-ils.storage.transaction.commit')->run;
714 'open-ils.penalty.patron_penalty.calculate',
715 { patron => $c->usr->to_fieldmapper,
723 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
724 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
725 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
726 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
730 __PACKAGE__->register_method(
731 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
734 method => 'generate_fines',
739 sub new_hold_copy_targeter {
742 my $check_expire = shift;
743 my $one_hold = shift;
745 local $OpenILS::Application::Storage::WRITE = 1;
751 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
752 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
753 } elsif ( $check_expire ) {
755 # what's the retarget time threashold?
757 $check_expire ||= '12h';
758 $check_expire = interval_to_seconds( $check_expire );
760 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
763 my $expire_threshold = sprintf(
764 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
765 $year, $mon, $mday, $hour, $min, $sec
768 # find all the holds holds needing retargeting
769 $holds = [ action::hold_request->search_where(
770 { capture_time => undef,
771 fulfillment_time => undef,
772 cancel_time => undef,
774 prev_check_time => { '<=' => $expire_threshold },
776 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
778 # find all the holds holds needing first time targeting
779 push @$holds, action::hold_request->search(
780 capture_time => undef,
781 fulfillment_time => undef,
782 prev_check_time => undef,
784 cancel_time => undef,
785 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
788 # find all the holds holds needing first time targeting ONLY
789 $holds = [ action::hold_request->search(
790 capture_time => undef,
791 fulfillment_time => undef,
792 prev_check_time => undef,
793 cancel_time => undef,
795 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
799 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
802 my @closed = actor::org_unit::closed_date->search_where(
803 { close_start => { '<=', 'now' },
804 close_end => { '>=', 'now' } }
810 for my $hold (@$holds) {
812 #start a transaction if needed
813 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
814 $log->debug("Cleaning up after previous transaction\n");
815 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
817 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
818 $log->info("Processing hold ".$hold->id."...\n");
820 #first, re-fetch the hold, to make sure it's not captured already
821 $hold->remove_from_object_index();
822 $hold = action::hold_request->retrieve( $hold->id );
823 die "OK\n" if (!$hold or $hold->capture_time);
825 # remove old auto-targeting maps
826 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
827 $_->delete for (@oldmaps);
832 # find filters for MR holds
833 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
835 # find all the potential copies
836 if ($hold->hold_type eq 'M') {
839 metabib::record_descriptor
843 isTrue($_->deleted) ? () : ($_->id)
844 } metabib::metarecord->retrieve($hold->target)->source_records
846 ( $types ? (item_type => [split '', $types]) : () ),
847 ( $formats ? (item_form => [split '', $formats]) : () ),
848 ( $lang ? (item_lang => $lang) : () ),
852 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
853 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
855 for my $cn ( @{ $rtree->call_numbers } ) {
857 asset::copy->search_where(
858 { id => [map {$_->id} @{ $cn->copies }],
860 ) if ($cn && @{ $cn->copies });
863 } elsif ($hold->hold_type eq 'T') {
865 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
866 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
869 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
873 for my $cn ( @{ $rtree->call_numbers } ) {
875 asset::copy->search_where(
876 { id => [map {$_->id} @{ $cn->copies }],
878 ) if ($cn && @{ $cn->copies });
880 } elsif ($hold->hold_type eq 'V') {
882 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
883 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
886 asset::copy->search_where(
887 { id => [map {$_->id} @{ $vtree->copies }],
889 ) if ($vtree && @{ $vtree->copies });
891 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
892 my $_cp = asset::copy->retrieve($hold->target);
893 push @$all_copies, $_cp if $_cp;
897 @$all_copies = grep { isTrue($_->status->holdable) &&
898 isTrue($_->location->holdable) &&
899 isTrue($_->holdable) &&
903 # let 'em know we're still working
904 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
906 # if we have no copies ...
907 if (!ref $all_copies || !@$all_copies) {
908 $log->info("\tNo copies available for targeting at all!\n");
909 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
911 $hold->update( { prev_check_time => 'today', current_copy => undef } );
912 $self->method_lookup('open-ils.storage.transaction.commit')->run;
916 my $copy_count = @$all_copies;
918 # map the potentials, so that we can pick up checkins
919 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
920 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
922 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
925 for my $c (@$all_copies) {
927 next if ($c->id eq $hold->current_copy);
930 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
932 # target of another hold
933 next if (action::hold_request
935 { current_copy => $c->id,
936 fulfillment_time => undef,
937 cancel_time => undef,
942 # we passed all three, keep it
943 push @good_copies, $c if ($c);
944 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
947 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
949 my $old_best = $hold->current_copy;
950 $hold->update({ current_copy => undef }) if ($old_best);
952 if (!scalar(@good_copies)) {
953 $log->info("\tNo (non-current) copies eligible to fill the hold.");
956 grep { $old_best eq $_ } @$all_copies &&
957 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
959 # the old copy is still available
960 $log->debug("\tPushing current_copy back onto the targeting list");
961 push @good_copies, $old_best;
963 # oops, old copy is not available
964 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
965 $hold->update( { prev_check_time => 'today' } );
966 $self->method_lookup('open-ils.storage.transaction.commit')->run;
967 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
972 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
977 $_->circ_lib == $hold->pickup_lib
981 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
983 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
984 my $best = choose_nearest_copy($hold, $prox_list);
985 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
988 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
989 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
991 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
993 $best = choose_nearest_copy($hold, $prox_list);
996 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
998 # hold wasn't fulfilled, record the fact
1000 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1001 action::unfulfilled_hold_list->create(
1002 { hold => ''.$hold->id,
1003 current_copy => ''.$old_best->id,
1004 circ_lib => ''.$old_best->circ_lib,
1009 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1010 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1013 action::hold_request
1015 { current_copy => $old_best->id,
1016 fulfillment_time => undef,
1017 cancel_time => undef,
1021 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1022 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1024 $hold->update( { prev_check_time => 'now' } );
1025 $log->info( "\tThere were no targetable copies for the hold" );
1028 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1029 $log->info("\tProcessing of hold ".$hold->id." complete.");
1032 { hold => $hold->id,
1033 old_target => ($old_best ? $old_best->id : undef),
1034 eligible_copies => $copy_count,
1035 target => ($best ? $best->id : undef) };
1040 $log->error("Processing of hold failed: $e");
1041 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1042 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1049 __PACKAGE__->register_method(
1050 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1052 method => 'new_hold_copy_targeter',
1057 my %cache = (titles => {}, cns => {});
1058 sub hold_copy_targeter {
1061 my $check_expire = shift;
1062 my $one_hold = shift;
1064 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1065 $self->{user_filter}->connect;
1066 $self->{client} = $client;
1069 $check_expire ||= '12h';
1070 $check_expire = interval_to_seconds( $check_expire );
1072 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1075 my $expire_threshold = sprintf(
1076 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1077 $year, $mon, $mday, $hour, $min, $sec
1081 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1083 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1087 %cache = (titles => {}, cns => {});
1091 $holds = [ action::hold_request->search(id => $one_hold) ];
1093 $holds = [ action::hold_request->search_where(
1094 { capture_time => undef,
1095 prev_check_time => { '<=' => $expire_threshold },
1097 { order_by => 'request_time,prev_check_time' } ) ];
1098 push @$holds, action::hold_request->search_where(
1099 { capture_time => undef,
1100 prev_check_time => undef,
1102 { order_by => 'request_time' } );
1104 } catch Error with {
1106 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1109 for my $hold (@$holds) {
1111 #action::hold_request->db_Main->begin_work;
1112 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1113 $client->respond("Cleaning up after previous transaction\n");
1114 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1116 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1117 $client->respond("Processing hold ".$hold->id."...\n");
1121 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1122 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1124 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1125 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1127 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1128 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1130 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1132 unless (ref $copies || !@$copies) {
1133 $client->respond("\tNo copies available for targeting at all!\n");
1137 for my $c (@$copies) {
1138 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1139 push @good_copies, $c if ($c);
1142 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1144 my $old_best = $hold->current_copy;
1145 $hold->update({ current_copy => undef });
1147 if (!scalar(@good_copies)) {
1148 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1149 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1150 $client->respond("\tPushing current_copy back onto the targeting list\n");
1151 push @good_copies, asset::copy->retrieve( $old_best );
1153 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1159 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1160 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1162 my $best = choose_nearest_copy($hold, $prox_list);
1165 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1166 $best = choose_nearest_copy($hold, $prox_list);
1170 # hold wasn't fulfilled, record the fact
1172 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1173 action::unfulfilled_hold_list->create(
1174 { hold => ''.$hold->id,
1175 current_copy => ''.$old_best->id,
1176 circ_lib => ''.$old_best->circ_lib,
1181 $hold->update( { current_copy => ''.$best->id } );
1182 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1185 $hold->update( { prev_check_time => 'now' } );
1186 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1188 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1189 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1191 #action::hold_request->dbi_commit;
1195 $log->error("Processing of hold failed: $e");
1196 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1197 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1198 #action::hold_request->dbi_rollback;
1202 $self->{user_filter}->disconnect;
1203 $self->{user_filter}->finish;
1204 delete $$self{user_filter};
1207 __PACKAGE__->register_method(
1208 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1211 method => 'hold_copy_targeter',
1215 sub copy_hold_capture {
1220 if (!defined($cps)) {
1222 $cps = [ asset::copy->search( id => $hold->target ) ];
1223 } catch Error with {
1225 die "Could not retrieve initial volume list:\n\n$e\n";
1229 my @copies = grep { $_->holdable } @$cps;
1231 for (my $i = 0; $i < @$cps; $i++) {
1232 next unless $$cps[$i];
1234 my $cn = $cache{cns}{$copies[$i]->call_number};
1235 my $rec = $cache{titles}{$cn->record};
1236 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1237 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1238 $copies[$i] = undef if (
1240 !$self->{user_filter}->request(
1241 'open-ils.circ.permit_hold',
1242 $hold->to_fieldmapper, do {
1243 my $cp_fm = $copies[$i]->to_fieldmapper;
1244 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1245 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1246 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1249 { title => $rec->to_fieldmapper,
1250 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1251 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1254 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1257 @copies = grep { $_ } @copies;
1259 my $count = @copies;
1261 return unless ($count);
1263 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1266 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1267 for my $c (@copies) {
1268 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1270 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1276 sub choose_nearest_copy {
1278 my $prox_list = shift;
1280 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1281 next unless (ref $$prox_list[$p]);
1283 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1284 next unless (@capturable);
1286 my $rand = int(rand(scalar(@capturable)));
1287 while (my ($c) = splice(@capturable,$rand)) {
1288 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1289 { title => $c->call_number->record->to_fieldmapper,
1290 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1291 patron => $hold->usr->to_fieldmapper,
1292 copy => $c->to_fieldmapper,
1293 requestor => $hold->requestor->to_fieldmapper,
1294 request_lib => $hold->request_lib->to_fieldmapper,
1295 pickup_lib => $hold->pickup_lib->id,
1299 last unless(@capturable);
1300 $rand = int(rand(scalar(@capturable)));
1305 sub create_prox_list {
1311 for my $cp (@$copies) {
1312 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1313 next unless (defined($prox));
1314 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1315 push @{$prox_list[$prox]}, $cp;
1320 sub volume_hold_capture {
1325 if (!defined($vols)) {
1327 $vols = [ asset::call_number->search( id => $hold->target ) ];
1328 $cache{cns}{$_->id} = $_ for (@$vols);
1329 } catch Error with {
1331 die "Could not retrieve initial volume list:\n\n$e\n";
1335 my @v_ids = map { $_->id } @$vols;
1339 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1341 } catch Error with {
1343 warn "Could not retrieve copy list:\n\n$e\n";
1346 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1349 sub title_hold_capture {
1354 if (!defined($titles)) {
1356 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1357 $cache{titles}{$_->id} = $_ for (@$titles);
1358 } catch Error with {
1360 die "Could not retrieve initial title list:\n\n$e\n";
1364 my @t_ids = map { $_->id } @$titles;
1367 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1369 } catch Error with {
1371 warn "Could not retrieve volume list:\n\n$e\n";
1374 $cache{cns}{$_->id} = $_ for (@$cn_list);
1376 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1379 sub metarecord_hold_capture {
1385 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1387 } catch Error with {
1389 die "Could not retrieve initial title list:\n\n$e\n";
1393 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1395 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1397 } catch Error with {
1399 die "Could not retrieve format-pruned title list:\n\n$e\n";
1403 $cache{titles}{$_->id} = $_ for (@$titles);
1404 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);