1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage::Publisher/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::PermitHold;
10 use DateTime::Format::ISO8601;
14 return 1 if ($v == 1);
15 return 1 if ($v =~ /^t/io);
16 return 1 if ($v =~ /^y/io);
20 my $parser = DateTime::Format::ISO8601->new;
21 my $log = 'OpenSRF::Utils::Logger';
23 sub open_noncat_circs {
28 my $a = action::non_cataloged_circulation->table;
29 my $c = config::non_cataloged_type->table;
34 JOIN $c c ON (a.item_type = c.id)
35 WHERE a.circ_time + c.circ_duration > current_timestamp
39 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
41 __PACKAGE__->register_method(
42 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
45 method => 'open_noncat_circs',
49 sub ou_hold_requests {
54 my $h_table = action::hold_request->table;
55 my $c_table = asset::copy->table;
56 my $o_table = actor::org_unit->table;
61 JOIN $c_table cp ON (cp.id = h.current_copy)
62 JOIN $o_table ou ON (ou.id = cp.circ_lib)
64 AND h.capture_time IS NULL
65 AND h.cancel_time IS NULL
66 ORDER BY h.request_time
69 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
72 $client->respond($_) for (
75 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
79 } @{ $sth->fetchall_arrayref }
83 __PACKAGE__->register_method(
84 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
88 method => 'ou_hold_requests',
95 my $c_t = action::circulation->table;
97 $grace = " - ($grace * (fine_interval))" if ($grace);
102 WHERE stop_fines IS NULL
103 AND due_date < ( CURRENT_TIMESTAMP $grace)
106 my $sth = action::circulation->db_Main->prepare_cached($sql);
109 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
113 sub complete_reshelving {
118 local $OpenILS::Application::Storage::WRITE = 1;
120 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
121 unless (interval_to_seconds( $window ));
123 my $circ = action::circulation->table;
124 my $cp = asset::copy->table;
131 SELECT cp.id, MAX(circ.checkin_time)
133 JOIN $circ circ ON (circ.target_copy = cp.id)
134 WHERE circ.checkin_time IS NOT NULL
137 HAVING MAX(circ.checkin_time) < NOW() - CAST(? AS INTERVAL)
143 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
145 AND cp.create_date < NOW() - CAST(? AS INTERVAL)
149 my $sth = action::circulation->db_Main->prepare_cached($sql);
150 $sth->execute($window, $window);
155 __PACKAGE__->register_method(
156 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
160 method => 'complete_reshelving',
166 my $grace = shift || '';
168 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
173 __PACKAGE__->register_method(
174 api_name => 'open-ils.storage.action.circulation.overdue',
177 method => 'grab_overdue',
185 my $limit = int(shift()) || 10;
186 my $age = shift() || '0';
187 my $prox = shift() || 0;
189 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp, $pl, $age, $prox);
191 FROM action.hold_request h
192 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
193 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
194 WHERE hm.target_copy = ?
196 AND (h.request_time + ? < NOW() OR p.prox <= ?)
197 AND h.capture_time IS NULL
198 AND h.cancel_time IS NULL
201 h.selection_depth DESC,
206 $client->respond( $_ ) for ( @$ids );
209 __PACKAGE__->register_method(
210 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
213 method => 'nearest_hold',
216 sub next_resp_group_id {
220 # XXX This is not replication safe!!!
222 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
223 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
227 __PACKAGE__->register_method(
228 api_name => 'open-ils.storage.action.survey_response.next_group_id',
230 method => 'next_resp_group_id',
233 sub patron_circ_summary {
238 return undef unless ($id);
239 my $c_table = action::circulation->table;
240 my $b_table = money::billing->table;
242 $log->debug("Retrieving patron summary for id $id", DEBUG);
244 my $select = <<" SQL";
245 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
247 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
249 AND c.xact_finish IS NULL
251 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
252 OR c.stop_fines IS NULL
256 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
258 __PACKAGE__->register_method(
259 api_name => 'open-ils.storage.action.circulation.patron_summary',
261 method => 'patron_circ_summary',
264 #XXX Fix stored proc calls
265 sub find_local_surveys {
270 return undef unless ($ou);
271 my $s_table = action::survey->table;
273 my $select = <<" SQL";
276 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
277 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
280 my $sth = action::survey->db_Main->prepare_cached($select);
283 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
287 __PACKAGE__->register_method(
288 api_name => 'open-ils.storage.action.survey.all',
291 method => 'find_local_surveys',
294 #XXX Fix stored proc calls
295 sub find_opac_surveys {
300 return undef unless ($ou);
301 my $s_table = action::survey->table;
303 my $select = <<" SQL";
306 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
307 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
311 my $sth = action::survey->db_Main->prepare_cached($select);
314 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
318 __PACKAGE__->register_method(
319 api_name => 'open-ils.storage.action.survey.opac',
322 method => 'find_opac_surveys',
329 my $limit = shift || 10;
330 my $offset = shift || 0;
332 return undef unless ($ou);
333 my $h_table = action::hold_request->table;
334 my $a_table = asset::copy->table;
336 my $idlist = 1 if ($self->api_name =~/id_list/o);
338 my $select = <<" SQL";
341 JOIN $a_table a ON (h.current_copy = a.id)
343 AND h.capture_time IS NULL
344 AND h.cancel_time IS NULL
345 ORDER BY h.request_time ASC
350 my $sth = action::survey->db_Main->prepare_cached($select);
354 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
356 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
361 __PACKAGE__->register_method(
362 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
366 "Returns the hold ids for a specific library's pull list.",
367 [ [org_unit => "The library's org id", "number"],
368 [limit => 'An optional page size, defaults to 10', 'number'],
369 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
371 ['A list of holds for the stated library to pull for', 'array']
373 method => 'hold_pull_list',
375 __PACKAGE__->register_method(
376 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
380 "Returns the holds for a specific library's pull list.",
381 [ [org_unit => "The library's org id", "number"],
382 [limit => 'An optional page size, defaults to 10', 'number'],
383 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
385 ['A list of holds for the stated library to pull for', 'array']
387 method => 'hold_pull_list',
390 sub find_optional_surveys {
395 return undef unless ($ou);
396 my $s_table = action::survey->table;
398 my $select = <<" SQL";
401 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
402 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
403 AND s.required IS FALSE;
406 my $sth = action::survey->db_Main->prepare_cached($select);
409 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
413 __PACKAGE__->register_method(
414 api_name => 'open-ils.storage.action.survey.optional',
417 method => 'find_optional_surveys',
420 sub find_required_surveys {
425 return undef unless ($ou);
426 my $s_table = action::survey->table;
428 my $select = <<" SQL";
431 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
432 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
433 AND s.required IS TRUE;
436 my $sth = action::survey->db_Main->prepare_cached($select);
439 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
443 __PACKAGE__->register_method(
444 api_name => 'open-ils.storage.action.survey.required',
447 method => 'find_required_surveys',
450 sub find_usr_summary_surveys {
455 return undef unless ($ou);
456 my $s_table = action::survey->table;
458 my $select = <<" SQL";
461 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
462 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
463 AND s.usr_summary IS TRUE;
466 my $sth = action::survey->db_Main->prepare_cached($select);
469 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
473 __PACKAGE__->register_method(
474 api_name => 'open-ils.storage.action.survey.usr_summary',
477 method => 'find_usr_summary_surveys',
486 my $overbill = shift;
488 local $OpenILS::Application::Storage::WRITE = 1;
492 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
494 push @circs, overdue_circs($grace);
497 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
499 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
503 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
504 $log->debug("Cleaning up after previous transaction\n");
505 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
507 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
508 $log->info("Processing circ ".$c->id."...\n");
511 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
513 my $due = $due_dt->epoch;
515 my $fine_interval = interval_to_seconds( $c->fine_interval );
517 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
519 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
520 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
523 $due -= ($due % $fine_interval) + $tz_offset_s;
524 $now -= ($now % $fine_interval) + $tz_offset_s;
528 "ARG! Overdue circulation ".$c->id.
529 " for item ".$c->target_copy.
530 " (user ".$c->usr.").\n".
531 "\tItem was due on or before: ".localtime($due)."\n");
533 my @fines = money::billing->search_where(
535 billing_type => 'Overdue materials',
536 billing_ts => { '>' => $c->due_date } },
537 { order_by => 'billing_ts DESC'}
541 my $fine = $fines[$f_idx] if (@fines);
543 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
546 my $current_fine_total = 0;
547 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
551 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
552 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
554 $log->info( "Potential first billing for circ ".$c->id );
558 if (my $h = $hoo{$c->circ_lib}) {
560 $log->info( "Circ lib has an hours-of-operation entry" );
561 # find the day after the due date...
562 $due_dt = $due_dt->add( days => 1 );
564 # get the day of the week for that day...
565 my $dow = $due_dt->day_of_week_0;
566 my $dow_open = "dow_${dow}_open";
567 my $dow_close = "dow_${dow}_close";
570 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
571 # if the circ lib is closed, add a day to the grace period...
574 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
575 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
577 $due_dt = $due_dt->add( days => 1 );
578 $dow = $due_dt->day_of_week_0;
579 $dow_open = "dow_${dow}_open";
580 $dow_close = "dow_${dow}_close";
584 # and check for up to a week
585 last if ($count > 6);
592 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
593 if ($pending_fine_count < 1 + $grace) {
594 $client->respond( "\tNo fines to create. " );
595 if ($grace && $now < $due + $fine_interval * $grace) {
596 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
597 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
599 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
604 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
606 my $recuring_fine = int($c->recuring_fine * 100);
607 my $max_fine = int($c->max_fine * 100);
609 my ($latest_billing_ts, $latest_amount) = ('',0);
610 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
612 if ($current_fine_total >= $max_fine) {
613 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
615 "\tMaximum fine level of ".$c->max_fine.
616 " reached for this circulation.\n".
617 "\tNo more fines will be generated.\n" );
621 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
623 my $dow = $billing_ts->day_of_week_0();
624 my $dow_open = "dow_${dow}_open";
625 my $dow_close = "dow_${dow}_close";
627 if (my $h = $hoo{$c->circ_lib}) {
628 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
631 my $timestamptz = $billing_ts->strftime('%FT%T%z');
632 my @cl = actor::org_unit::closed_date->search_where(
633 { close_start => { '<=' => $timestamptz },
634 close_end => { '>=' => $timestamptz },
635 org_unit => $c->circ_lib }
639 $current_fine_total += $recuring_fine;
640 $latest_amount += $recuring_fine;
641 $latest_billing_ts = $timestamptz;
643 money::billing->create(
645 note => "System Generated Overdue Fine",
646 billing_type => "Overdue materials",
647 amount => sprintf('%0.2f', $recuring_fine/100),
648 billing_ts => $timestamptz,
654 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
655 if ($latest_billing_ts and $latest_amount);
657 $self->method_lookup('open-ils.storage.transaction.commit')->run;
660 'open-ils.penalty.patron_penalty.calculate',
661 { patron => $c->usr->to_fieldmapper,
669 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
670 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
671 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
672 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
676 __PACKAGE__->register_method(
677 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
680 method => 'generate_fines',
685 sub new_hold_copy_targeter {
688 my $check_expire = shift;
689 my $one_hold = shift;
691 local $OpenILS::Application::Storage::WRITE = 1;
697 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
698 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
699 } elsif ( $check_expire ) {
701 # what's the retarget time threashold?
703 $check_expire ||= '12h';
704 $check_expire = interval_to_seconds( $check_expire );
706 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
709 my $expire_threshold = sprintf(
710 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
711 $year, $mon, $mday, $hour, $min, $sec
714 # find all the holds holds needing retargeting
715 $holds = [ action::hold_request->search_where(
716 { capture_time => undef,
717 fulfillment_time => undef,
718 cancel_time => undef,
720 prev_check_time => { '<=' => $expire_threshold },
722 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
724 # find all the holds holds needing first time targeting
725 push @$holds, action::hold_request->search(
726 capture_time => undef,
727 fulfillment_time => undef,
728 prev_check_time => undef,
730 cancel_time => undef,
731 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
734 # find all the holds holds needing first time targeting ONLY
735 $holds = [ action::hold_request->search(
736 capture_time => undef,
737 fulfillment_time => undef,
738 prev_check_time => undef,
739 cancel_time => undef,
741 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
745 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
748 my @closed = actor::org_unit::closed_date->search_where(
749 { close_start => { '<=', 'now' },
750 close_end => { '>=', 'now' } }
756 for my $hold (@$holds) {
758 #start a transaction if needed
759 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
760 $log->debug("Cleaning up after previous transaction\n");
761 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
763 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
764 $log->info("Processing hold ".$hold->id."...\n");
766 #first, re-fetch the hold, to make sure it's not captured already
767 $hold = action::hold_request->retrieve( $hold->id );
768 die "OK\n" if (!$hold or $hold->capture_time);
770 # remove old auto-targeting maps
771 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
772 $_->delete for (@oldmaps);
777 # find filters for MR holds
778 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
780 # find all the potential copies
781 if ($hold->hold_type eq 'M') {
784 metabib::record_descriptor
786 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
787 ( $types ? (item_type => [split '', $types]) : () ),
788 ( $formats ? (item_form => [split '', $formats]) : () ),
789 ( $lang ? (item_lang => $lang) : () ),
793 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
794 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
796 for my $cn ( @{ $rtree->call_numbers } ) {
798 asset::copy->search_where(
799 { id => [map {$_->id} @{ $cn->copies }],
801 ) if ($cn && @{ $cn->copies });
804 } elsif ($hold->hold_type eq 'T') {
806 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
807 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
810 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
814 for my $cn ( @{ $rtree->call_numbers } ) {
816 asset::copy->search_where(
817 { id => [map {$_->id} @{ $cn->copies }],
819 ) if ($cn && @{ $cn->copies });
821 } elsif ($hold->hold_type eq 'V') {
823 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
824 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
827 asset::copy->search_where(
828 { id => [map {$_->id} @{ $vtree->copies }],
830 ) if ($vtree && @{ $vtree->copies });
832 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
833 my $_cp = asset::copy->retrieve($hold->target);
834 push @$all_copies, $_cp if $_cp;
838 @$all_copies = grep { isTrue($_->status->holdable) &&
839 isTrue($_->location->holdable) &&
840 isTrue($_->holdable) &&
844 # let 'em know we're still working
845 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
847 # if we have no copies ...
848 if (!ref $all_copies || !@$all_copies) {
849 $log->info("\tNo copies available for targeting at all!\n");
850 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
852 $hold->update( { prev_check_time => 'today', current_copy => undef } );
853 $self->method_lookup('open-ils.storage.transaction.commit')->run;
857 my $copy_count = @$all_copies;
859 # map the potentials, so that we can pick up checkins
860 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
861 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
863 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
866 for my $c (@$all_copies) {
868 next if ($c->id eq $hold->current_copy);
871 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
873 # target of another hold
874 next if (action::hold_request
876 { current_copy => $c->id,
877 fulfillment_time => undef,
878 cancel_time => undef,
883 # we passed all three, keep it
884 push @good_copies, $c if ($c);
885 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
888 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
890 my $old_best = $hold->current_copy;
891 $hold->update({ current_copy => undef }) if ($old_best);
893 if (!scalar(@good_copies)) {
894 $log->info("\tNo (non-current) copies eligible to fill the hold.");
897 grep { $old_best eq $_ } @$all_copies &&
898 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
900 # the old copy is still available
901 $log->debug("\tPushing current_copy back onto the targeting list");
902 push @good_copies, $old_best;
904 # oops, old copy is not available
905 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
906 $hold->update( { prev_check_time => 'today' } );
907 $self->method_lookup('open-ils.storage.transaction.commit')->run;
908 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
913 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
918 $_->circ_lib == $hold->pickup_lib
922 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
924 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
925 my $best = choose_nearest_copy($hold, $prox_list);
926 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
929 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
930 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
932 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
934 $best = choose_nearest_copy($hold, $prox_list);
937 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
939 # hold wasn't fulfilled, record the fact
941 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
942 action::unfulfilled_hold_list->create(
943 { hold => ''.$hold->id,
944 current_copy => ''.$old_best->id,
945 circ_lib => ''.$old_best->circ_lib,
950 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
951 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
956 { current_copy => $old_best->id,
957 fulfillment_time => undef,
958 cancel_time => undef,
962 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
963 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
965 $hold->update( { prev_check_time => 'now' } );
966 $log->info( "\tThere were no targetable copies for the hold" );
969 $self->method_lookup('open-ils.storage.transaction.commit')->run;
970 $log->info("\tProcessing of hold ".$hold->id." complete.");
974 old_target => ($old_best ? $old_best->id : undef),
975 eligible_copies => $copy_count,
976 target => ($best ? $best->id : undef) };
981 $log->error("Processing of hold failed: $e");
982 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
983 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
990 __PACKAGE__->register_method(
991 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
993 method => 'new_hold_copy_targeter',
998 my %cache = (titles => {}, cns => {});
999 sub hold_copy_targeter {
1002 my $check_expire = shift;
1003 my $one_hold = shift;
1005 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1006 $self->{user_filter}->connect;
1007 $self->{client} = $client;
1010 $check_expire ||= '12h';
1011 $check_expire = interval_to_seconds( $check_expire );
1013 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1016 my $expire_threshold = sprintf(
1017 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1018 $year, $mon, $mday, $hour, $min, $sec
1022 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1024 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1028 %cache = (titles => {}, cns => {});
1032 $holds = [ action::hold_request->search(id => $one_hold) ];
1034 $holds = [ action::hold_request->search_where(
1035 { capture_time => undef,
1036 prev_check_time => { '<=' => $expire_threshold },
1038 { order_by => 'request_time,prev_check_time' } ) ];
1039 push @$holds, action::hold_request->search_where(
1040 { capture_time => undef,
1041 prev_check_time => undef,
1043 { order_by => 'request_time' } );
1045 } catch Error with {
1047 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1050 for my $hold (@$holds) {
1052 #action::hold_request->db_Main->begin_work;
1053 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1054 $client->respond("Cleaning up after previous transaction\n");
1055 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1057 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1058 $client->respond("Processing hold ".$hold->id."...\n");
1062 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1063 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1065 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1066 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1068 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1069 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1071 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1073 unless (ref $copies || !@$copies) {
1074 $client->respond("\tNo copies available for targeting at all!\n");
1078 for my $c (@$copies) {
1079 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1080 push @good_copies, $c if ($c);
1083 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1085 my $old_best = $hold->current_copy;
1086 $hold->update({ current_copy => undef });
1088 if (!scalar(@good_copies)) {
1089 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1090 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1091 $client->respond("\tPushing current_copy back onto the targeting list\n");
1092 push @good_copies, asset::copy->retrieve( $old_best );
1094 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1100 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1101 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1103 my $best = choose_nearest_copy($hold, $prox_list);
1106 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1107 $best = choose_nearest_copy($hold, $prox_list);
1111 # hold wasn't fulfilled, record the fact
1113 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1114 action::unfulfilled_hold_list->create(
1115 { hold => ''.$hold->id,
1116 current_copy => ''.$old_best->id,
1117 circ_lib => ''.$old_best->circ_lib,
1122 $hold->update( { current_copy => ''.$best->id } );
1123 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1126 $hold->update( { prev_check_time => 'now' } );
1127 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1129 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1130 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1132 #action::hold_request->dbi_commit;
1136 $log->error("Processing of hold failed: $e");
1137 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1138 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1139 #action::hold_request->dbi_rollback;
1143 $self->{user_filter}->disconnect;
1144 $self->{user_filter}->finish;
1145 delete $$self{user_filter};
1148 __PACKAGE__->register_method(
1149 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1152 method => 'hold_copy_targeter',
1156 sub copy_hold_capture {
1161 if (!defined($cps)) {
1163 $cps = [ asset::copy->search( id => $hold->target ) ];
1164 } catch Error with {
1166 die "Could not retrieve initial volume list:\n\n$e\n";
1170 my @copies = grep { $_->holdable } @$cps;
1172 for (my $i = 0; $i < @$cps; $i++) {
1173 next unless $$cps[$i];
1175 my $cn = $cache{cns}{$copies[$i]->call_number};
1176 my $rec = $cache{titles}{$cn->record};
1177 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1178 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1179 $copies[$i] = undef if (
1181 !$self->{user_filter}->request(
1182 'open-ils.circ.permit_hold',
1183 $hold->to_fieldmapper, do {
1184 my $cp_fm = $copies[$i]->to_fieldmapper;
1185 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1186 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1187 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1190 { title => $rec->to_fieldmapper,
1191 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1192 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1195 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1198 @copies = grep { $_ } @copies;
1200 my $count = @copies;
1202 return unless ($count);
1204 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1207 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1208 for my $c (@copies) {
1209 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1211 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1217 sub choose_nearest_copy {
1219 my $prox_list = shift;
1221 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1222 next unless (ref $$prox_list[$p]);
1224 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1225 next unless (@capturable);
1227 my $rand = int(rand(scalar(@capturable)));
1228 while (my ($c) = splice(@capturable,$rand)) {
1229 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1230 { title => $c->call_number->record->to_fieldmapper,
1231 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1232 patron => $hold->usr->to_fieldmapper,
1233 copy => $c->to_fieldmapper,
1234 requestor => $hold->requestor->to_fieldmapper,
1235 request_lib => $hold->request_lib->to_fieldmapper,
1236 pickup_lib => $hold->pickup_lib->id,
1240 last unless(@capturable);
1241 $rand = int(rand(scalar(@capturable)));
1246 sub create_prox_list {
1252 for my $cp (@$copies) {
1253 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1254 next unless (defined($prox));
1255 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1256 push @{$prox_list[$prox]}, $cp;
1261 sub volume_hold_capture {
1266 if (!defined($vols)) {
1268 $vols = [ asset::call_number->search( id => $hold->target ) ];
1269 $cache{cns}{$_->id} = $_ for (@$vols);
1270 } catch Error with {
1272 die "Could not retrieve initial volume list:\n\n$e\n";
1276 my @v_ids = map { $_->id } @$vols;
1280 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1282 } catch Error with {
1284 warn "Could not retrieve copy list:\n\n$e\n";
1287 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1290 sub title_hold_capture {
1295 if (!defined($titles)) {
1297 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1298 $cache{titles}{$_->id} = $_ for (@$titles);
1299 } catch Error with {
1301 die "Could not retrieve initial title list:\n\n$e\n";
1305 my @t_ids = map { $_->id } @$titles;
1308 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1310 } catch Error with {
1312 warn "Could not retrieve volume list:\n\n$e\n";
1315 $cache{cns}{$_->id} = $_ for (@$cn_list);
1317 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1320 sub metarecord_hold_capture {
1326 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1328 } catch Error with {
1330 die "Could not retrieve initial title list:\n\n$e\n";
1334 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1336 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1338 } catch Error with {
1340 die "Could not retrieve format-pruned title list:\n\n$e\n";
1344 $cache{titles}{$_->id} = $_ for (@$titles);
1345 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);