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;
11 use OpenILS::Utils::Penalty;
15 return 1 if ($v == 1);
16 return 1 if ($v =~ /^t/io);
17 return 1 if ($v =~ /^y/io);
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
24 sub open_noncat_circs {
29 my $a = action::non_cataloged_circulation->table;
30 my $c = config::non_cataloged_type->table;
35 JOIN $c c ON (a.item_type = c.id)
36 WHERE a.circ_time + c.circ_duration > current_timestamp
40 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
42 __PACKAGE__->register_method(
43 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
46 method => 'open_noncat_circs',
50 sub ou_hold_requests {
55 my $h_table = action::hold_request->table;
56 my $c_table = asset::copy->table;
57 my $o_table = actor::org_unit->table;
62 JOIN $c_table cp ON (cp.id = h.current_copy)
63 JOIN $o_table ou ON (ou.id = cp.circ_lib)
65 AND h.capture_time IS NULL
66 AND h.cancel_time IS NULL
67 AND (h.expire_time IS NULL OR h.expire_time > NOW())
68 ORDER BY h.request_time
71 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
74 $client->respond($_) for (
77 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
81 } @{ $sth->fetchall_arrayref }
85 __PACKAGE__->register_method(
86 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
90 method => 'ou_hold_requests',
96 my $upper_interval = shift || '1 millennium';
98 my $c_t = action::circulation->table;
100 if ($grace && $grace =~ /^\d+$/o) {
101 $grace = " - ($grace * (fine_interval))";
109 WHERE stop_fines IS NULL
110 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 AND fine_interval < ?::INTERVAL
114 my $sth = action::circulation->db_Main->prepare_cached($sql);
115 $sth->execute($upper_interval);
117 my @circs = map { action::circulation->construct($_) } $sth->fetchall_hash;
119 $c_t = booking::reservation->table;
123 WHERE return_time IS NULL
124 AND end_time < ( CURRENT_TIMESTAMP $grace)
125 AND fine_interval IS NOT NULL
126 AND cancel_time IS NULL
129 $sth = action::circulation->db_Main->prepare_cached($sql);
132 push @circs, map { booking::reservation->construct($_) } $sth->fetchall_hash;
137 sub complete_reshelving {
142 local $OpenILS::Application::Storage::WRITE = 1;
144 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
145 unless (interval_to_seconds( $window ));
147 my $setting = actor::org_unit_setting->table;
148 my $circ = action::circulation->table;
149 my $cp = asset::copy->table;
156 FROM (SELECT cp.id, MAX(circ.checkin_time)
158 JOIN $circ circ ON (circ.target_copy = cp.id)
159 LEFT JOIN $setting setting
160 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
161 WHERE circ.checkin_time IS NOT NULL
164 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL)
169 LEFT JOIN $setting setting
170 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
171 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
172 WHERE cp.status = 7 AND circ.id IS NULL
173 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
177 my $sth = action::circulation->db_Main->prepare_cached($sql);
178 $sth->execute($window, $window);
183 __PACKAGE__->register_method(
184 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
187 method => 'complete_reshelving',
190 sub mark_longoverdue {
195 local $OpenILS::Application::Storage::WRITE = 1;
197 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
198 unless (interval_to_seconds( $window ));
200 my $setting = actor::org_unit_setting->table;
201 my $circ = action::circulation->table;
205 SET stop_fines = 'LONGOVERDUE',
206 stop_fines_time = now()
210 LEFT JOIN $setting setting
211 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
212 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
213 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
217 my $sth = action::circulation->db_Main->prepare_cached($sql);
218 $sth->execute($window);
223 __PACKAGE__->register_method(
224 api_name => 'open-ils.storage.action.circulation.long_overdue',
227 method => 'mark_longoverdue',
230 sub auto_thaw_frozen_holds {
234 local $OpenILS::Application::Storage::WRITE = 1;
236 my $holds = action::hold_request->table;
238 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
240 my $sth = action::hold_request->db_Main->prepare_cached($sql);
246 __PACKAGE__->register_method(
247 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
251 method => 'auto_thaw_frozen_holds',
257 my $grace = shift || '';
259 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
264 __PACKAGE__->register_method(
265 api_name => 'open-ils.storage.action.circulation.overdue',
268 method => 'grab_overdue',
276 my $limit = int(shift()) || 10;
277 my $age = shift() || '0 seconds';
279 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
281 FROM action.hold_request h
282 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
283 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
284 WHERE hm.target_copy = ?
285 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
286 AND h.capture_time IS NULL
287 AND h.cancel_time IS NULL
288 AND (h.expire_time IS NULL OR h.expire_time > NOW())
289 AND h.frozen IS FALSE
292 CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
293 h.selection_depth DESC,
298 $client->respond( $_ ) for ( @$ids );
301 __PACKAGE__->register_method(
302 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
305 method => 'nearest_hold',
308 sub next_resp_group_id {
312 # XXX This is not replication safe!!!
314 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
315 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
319 __PACKAGE__->register_method(
320 api_name => 'open-ils.storage.action.survey_response.next_group_id',
322 method => 'next_resp_group_id',
325 sub patron_circ_summary {
330 return undef unless ($id);
331 my $c_table = action::circulation->table;
332 my $b_table = money::billing->table;
334 $log->debug("Retrieving patron summary for id $id", DEBUG);
336 my $select = <<" SQL";
337 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
339 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
341 AND c.xact_finish IS NULL
343 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
344 OR c.stop_fines IS NULL
348 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
350 __PACKAGE__->register_method(
351 api_name => 'open-ils.storage.action.circulation.patron_summary',
353 method => 'patron_circ_summary',
356 #XXX Fix stored proc calls
357 sub find_local_surveys {
362 return undef unless ($ou);
363 my $s_table = action::survey->table;
365 my $select = <<" SQL";
368 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
369 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
372 my $sth = action::survey->db_Main->prepare_cached($select);
375 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
379 __PACKAGE__->register_method(
380 api_name => 'open-ils.storage.action.survey.all',
383 method => 'find_local_surveys',
386 #XXX Fix stored proc calls
387 sub find_opac_surveys {
392 return undef unless ($ou);
393 my $s_table = action::survey->table;
395 my $select = <<" SQL";
398 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
399 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
403 my $sth = action::survey->db_Main->prepare_cached($select);
406 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
410 __PACKAGE__->register_method(
411 api_name => 'open-ils.storage.action.survey.opac',
414 method => 'find_opac_surveys',
421 my $limit = shift || 10;
422 my $offset = shift || 0;
424 return undef unless ($ou);
425 my $h_table = action::hold_request->table;
426 my $a_table = asset::copy->table;
427 my $ord_table = asset::copy_location_order->table;
429 my $idlist = 1 if ($self->api_name =~/id_list/o);
430 my $count = 1 if ($self->api_name =~/count$/o);
432 my $status_filter = '';
433 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
435 my $select = <<" SQL";
438 JOIN $a_table a ON (h.current_copy = a.id)
439 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
441 AND h.capture_time IS NULL
442 AND h.cancel_time IS NULL
443 AND (h.expire_time IS NULL OR h.expire_time > NOW())
445 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
454 JOIN $a_table a ON (h.current_copy = a.id)
456 AND h.capture_time IS NULL
457 AND h.cancel_time IS NULL
458 AND (h.expire_time IS NULL OR h.expire_time > NOW())
463 my $sth = action::survey->db_Main->prepare_cached($select);
467 $client->respond( $sth->fetchall_arrayref()->[0][0] );
469 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
471 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
476 __PACKAGE__->register_method(
477 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
481 "Returns a count of holds for a specific library's pull list.",
482 [ [org_unit => "The library's org id", "number"] ],
483 ['A count of holds for the stated library to pull ', 'number']
485 method => 'hold_pull_list',
487 __PACKAGE__->register_method(
488 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
492 "Returns a status filtered count of holds for a specific library's pull list.",
493 [ [org_unit => "The library's org id", "number"] ],
494 ['A status filtered count of holds for the stated library to pull ', 'number']
496 method => 'hold_pull_list',
498 __PACKAGE__->register_method(
499 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
503 "Returns the hold ids for a specific library's pull list.",
504 [ [org_unit => "The library's org id", "number"],
505 [limit => 'An optional page size, defaults to 10', 'number'],
506 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
508 ['A list of holds for the stated library to pull for', 'array']
510 method => 'hold_pull_list',
512 __PACKAGE__->register_method(
513 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
517 "Returns the holds for a specific library's pull list.",
518 [ [org_unit => "The library's org id", "number"],
519 [limit => 'An optional page size, defaults to 10', 'number'],
520 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
522 ['A list of holds for the stated library to pull for', 'array']
524 method => 'hold_pull_list',
526 __PACKAGE__->register_method(
527 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
531 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
532 [ [org_unit => "The library's org id", "number"],
533 [limit => 'An optional page size, defaults to 10', 'number'],
534 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
536 ['A list of holds for the stated library to pull for', 'array']
538 method => 'hold_pull_list',
540 __PACKAGE__->register_method(
541 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
545 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
546 [ [org_unit => "The library's org id", "number"],
547 [limit => 'An optional page size, defaults to 10', 'number'],
548 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
550 ['A list of holds for the stated library to pull for', 'array']
552 method => 'hold_pull_list',
555 sub find_optional_surveys {
560 return undef unless ($ou);
561 my $s_table = action::survey->table;
563 my $select = <<" SQL";
566 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
567 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
568 AND s.required IS FALSE;
571 my $sth = action::survey->db_Main->prepare_cached($select);
574 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
578 __PACKAGE__->register_method(
579 api_name => 'open-ils.storage.action.survey.optional',
582 method => 'find_optional_surveys',
585 sub find_required_surveys {
590 return undef unless ($ou);
591 my $s_table = action::survey->table;
593 my $select = <<" SQL";
596 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
597 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
598 AND s.required IS TRUE;
601 my $sth = action::survey->db_Main->prepare_cached($select);
604 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
608 __PACKAGE__->register_method(
609 api_name => 'open-ils.storage.action.survey.required',
612 method => 'find_required_surveys',
615 sub find_usr_summary_surveys {
620 return undef unless ($ou);
621 my $s_table = action::survey->table;
623 my $select = <<" SQL";
626 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
627 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
628 AND s.usr_summary IS TRUE;
631 my $sth = action::survey->db_Main->prepare_cached($select);
634 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
638 __PACKAGE__->register_method(
639 api_name => 'open-ils.storage.action.survey.usr_summary',
642 method => 'find_usr_summary_surveys',
651 my $overbill = shift;
653 local $OpenILS::Application::Storage::WRITE = 1;
658 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
659 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
661 push @circs, overdue_circs($grace);
664 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
666 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
670 $ctype =~ s/^.*([^:]+)$/$1/o;
672 my $due_date_method = 'due_date';
673 my $target_copy_method = 'target_copy';
674 my $circ_lib_method = 'circ_lib';
675 my $recurring_fine_method = 'recurring_fine';
676 my $is_reservation = 0;
677 if ($ctype eq 'reservation') {
679 $due_date_method = 'end_time';
680 $target_copy_method = 'current_resource';
681 $circ_lib_method = 'pickup_lib';
682 $recurring_fine_method = 'fine_amount';
683 next unless ($c->fine_interval);
687 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
688 $log->debug("Cleaning up after previous transaction\n");
689 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
691 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
692 $log->info("Processing circ ".$c->id."...\n");
695 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
697 my $due = $due_dt->epoch;
700 my $fine_interval = $c->fine_interval;
701 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
702 $fine_interval = interval_to_seconds( $fine_interval );
704 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
706 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
707 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
710 $due -= ($due % $fine_interval) + $tz_offset_s;
711 $now -= ($now % $fine_interval) + $tz_offset_s;
715 "ARG! Overdue $ctype ".$c->id.
716 " for item ".$c->$target_copy_method.
717 " (user ".$c->usr.").\n".
718 "\tItem was due on or before: ".localtime($due)."\n");
720 my @fines = money::billing->search_where(
723 billing_ts => { '>' => $c->$due_date_method } },
724 { order_by => 'billing_ts DESC'}
728 my $fine = $fines[$f_idx] if (@fines);
730 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
733 my $current_fine_total = 0;
734 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
738 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
739 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
741 $log->info( "Potential first billing for circ ".$c->id );
745 if (my $h = $hoo{$c->$circ_lib_method}) {
747 $log->info( "Circ lib has an hours-of-operation entry" );
748 # find the day after the due date...
749 $due_dt = $due_dt->add( days => 1 );
751 # get the day of the week for that day...
752 my $dow = $due_dt->day_of_week_0;
753 my $dow_open = "dow_${dow}_open";
754 my $dow_close = "dow_${dow}_close";
757 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
758 # if the circ lib is closed, add a day to the grace period...
761 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
762 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
764 $due_dt = $due_dt->add( days => 1 );
765 $dow = $due_dt->day_of_week_0;
766 $dow_open = "dow_${dow}_open";
767 $dow_close = "dow_${dow}_close";
771 # and check for up to a week
772 last if ($count > 6);
778 next if ($last_fine > $now);
779 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
781 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
782 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
784 if ( $last_fine == $due # we have no fines yet
785 && $grace # and we have a grace period
786 && $pending_fine_count <= $grace # and we seem to be inside that period
787 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
789 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
790 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
794 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
795 next unless ($pending_fine_count);
797 my $recuring_fine = int($c->$recurring_fine_method * 100);
798 my $max_fine = int($c->max_fine * 100);
800 my ($latest_billing_ts, $latest_amount) = ('',0);
801 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
803 if ($current_fine_total >= $max_fine) {
804 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
806 "\tMaximum fine level of ".$c->max_fine.
807 " reached for this $ctype.\n".
808 "\tNo more fines will be generated.\n" );
812 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
814 my $dow = $billing_ts->day_of_week_0();
815 my $dow_open = "dow_${dow}_open";
816 my $dow_close = "dow_${dow}_close";
818 if (my $h = $hoo{$c->$circ_lib_method}) {
819 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
822 my $timestamptz = $billing_ts->strftime('%FT%T%z');
823 my @cl = actor::org_unit::closed_date->search_where(
824 { close_start => { '<=' => $timestamptz },
825 close_end => { '>=' => $timestamptz },
826 org_unit => $c->$circ_lib_method }
830 $current_fine_total += $recurring_fine;
831 $latest_amount += $recurring_fine;
832 $latest_billing_ts = $timestamptz;
834 money::billing->create(
836 note => "System Generated Overdue Fine",
837 billing_type => "Overdue materials",
839 amount => sprintf('%0.2f', $recurring_fine/100),
840 billing_ts => $timestamptz,
846 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
847 if ($latest_billing_ts and $latest_amount);
849 $self->method_lookup('open-ils.storage.transaction.commit')->run;
853 # Caluclate penalties inline
854 OpenILS::Utils::Penalty->calculate_penalties(
855 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
859 # Calculate penalties with an aysnc call to the penalty server. This approach
860 # may lead to duplicate penalties since multiple penalty processes for a
861 # given user may be running at the same time. Leave this here for reference
862 # in case we later find that asyc calls are needed in some environments.
864 'open-ils.penalty.patron_penalty.calculate',
865 { patronid => ''.$c->usr,
866 context_org => ''.$c->$circ_lib_method,
875 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
876 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
877 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
878 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
882 __PACKAGE__->register_method(
883 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
886 method => 'generate_fines',
891 sub new_hold_copy_targeter {
894 my $check_expire = shift;
895 my $one_hold = shift;
897 local $OpenILS::Application::Storage::WRITE = 1;
899 $self->{target_weight} = {};
905 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
906 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
907 } elsif ( $check_expire ) {
909 # what's the retarget time threashold?
911 $check_expire ||= '12h';
912 $check_expire = interval_to_seconds( $check_expire );
914 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
917 my $expire_threshold = sprintf(
918 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
919 $year, $mon, $mday, $hour, $min, $sec
922 # find all the holds holds needing retargeting
923 $holds = [ action::hold_request->search_where(
924 { capture_time => undef,
925 fulfillment_time => undef,
926 cancel_time => undef,
928 prev_check_time => { '<=' => $expire_threshold },
930 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
932 # find all the holds holds needing first time targeting
933 push @$holds, action::hold_request->search(
934 capture_time => undef,
935 fulfillment_time => undef,
936 prev_check_time => undef,
938 cancel_time => undef,
939 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
942 # find all the holds holds needing first time targeting ONLY
943 $holds = [ action::hold_request->search(
944 capture_time => undef,
945 fulfillment_time => undef,
946 prev_check_time => undef,
947 cancel_time => undef,
949 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
953 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
956 my @closed = actor::org_unit::closed_date->search_where(
957 { close_start => { '<=', 'now' },
958 close_end => { '>=', 'now' } }
963 # $check_expire, if it exists, was already converted to seconds
964 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
968 my $next_check_time = sprintf(
969 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
970 $year, $mon, $mday, $hour, $min, $sec
974 my @closed_at_next = actor::org_unit::closed_date->search_where(
975 { close_start => { '<=', $next_check_time },
976 close_end => { '>=', $next_check_time } }
980 for my $c_at_n (@closed_at_next) {
981 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
982 push @new_closed, $c_at_n;
985 @closed = @new_closed;
989 my $actor = OpenSRF::AppSession->create('open-ils.actor');
991 for my $hold (@$holds) {
993 #start a transaction if needed
994 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
995 $log->debug("Cleaning up after previous transaction\n");
996 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
998 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
999 $log->info("Processing hold ".$hold->id."...\n");
1001 #first, re-fetch the hold, to make sure it's not captured already
1002 $hold->remove_from_object_index();
1003 $hold = action::hold_request->retrieve( $hold->id );
1005 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1007 # remove old auto-targeting maps
1008 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1009 $_->delete for (@oldmaps);
1011 if ($hold->expire_time) {
1012 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1013 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1015 # cancel cause = un-targeted expiration
1016 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1017 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1019 # tell A/T the hold was cancelled
1020 my $fm_hold = $hold->to_fieldmapper;
1021 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1022 $ses->request('open-ils.trigger.event.autocreate',
1023 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1029 my $all_copies = [];
1031 # find filters for MR holds
1032 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1034 # find all the potential copies
1035 if ($hold->hold_type eq 'M') {
1038 metabib::record_descriptor
1042 isTrue($_->deleted) ? () : ($_->id)
1043 } metabib::metarecord->retrieve($hold->target)->source_records
1045 ( $types ? (item_type => [split '', $types]) : () ),
1046 ( $formats ? (item_form => [split '', $formats]) : () ),
1047 ( $lang ? (item_lang => $lang) : () ),
1051 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1052 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1054 for my $cn ( @{ $rtree->call_numbers } ) {
1056 asset::copy->search_where(
1057 { id => [map {$_->id} @{ $cn->copies }],
1059 ) if ($cn && @{ $cn->copies });
1062 } elsif ($hold->hold_type eq 'T') {
1064 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1065 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1068 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1072 for my $cn ( @{ $rtree->call_numbers } ) {
1074 asset::copy->search_where(
1075 { id => [map {$_->id} @{ $cn->copies }],
1077 ) if ($cn && @{ $cn->copies });
1079 } elsif ($hold->hold_type eq 'V') {
1081 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1082 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1085 asset::copy->search_where(
1086 { id => [map {$_->id} @{ $vtree->copies }],
1088 ) if ($vtree && @{ $vtree->copies });
1090 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1091 my $_cp = asset::copy->retrieve($hold->target);
1092 push @$all_copies, $_cp if $_cp;
1096 @$all_copies = grep { isTrue($_->status->holdable) &&
1097 isTrue($_->location->holdable) &&
1098 isTrue($_->holdable) &&
1099 !isTrue($_->deleted) &&
1100 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1103 # let 'em know we're still working
1104 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1106 # if we have no copies ...
1107 if (!ref $all_copies || !@$all_copies) {
1108 $log->info("\tNo copies available for targeting at all!\n");
1109 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1111 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1112 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1116 my $copy_count = @$all_copies;
1118 # map the potentials, so that we can pick up checkins
1119 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1120 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1121 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1122 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1124 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1127 for my $c (@$all_copies) {
1129 next if ($c->id eq $hold->current_copy);
1131 # circ lib is closed
1132 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1134 # target of another hold
1135 next if (action::hold_request
1137 { current_copy => $c->id,
1138 fulfillment_time => undef,
1139 cancel_time => undef,
1144 # we passed all three, keep it
1145 push @good_copies, $c if ($c);
1146 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1149 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1151 my $old_best = $hold->current_copy;
1152 $hold->update({ current_copy => undef }) if ($old_best);
1154 if (!scalar(@good_copies)) {
1155 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1156 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1157 # the old copy is still available
1158 $log->debug("\tPushing current_copy back onto the targeting list");
1159 push @good_copies, $old_best;
1161 # oops, old copy is not available
1162 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1163 $hold->update( { prev_check_time => 'today' } );
1164 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1165 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1174 $_->circ_lib == $hold->pickup_lib
1178 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1179 # $all_copies is now a list of copies not at the pickup library
1181 my $best = choose_nearest_copy($hold, $prox_list);
1182 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1185 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1187 my $max_loops = $actor->request(
1188 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1191 if (defined($max_loops)) {
1192 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1193 my $circ_lib_list = [keys %circ_lib_map];
1195 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1197 # Grab the "biggest" loop for this hold so far
1198 my $current_loop = $cstore->request(
1199 'open-ils.cstore.json_query',
1201 select => { aufhmxl => ['max'] },
1203 where => { hold => $hold->id}
1207 $current_loop = $current_loop->{max} if ($current_loop);
1208 $current_loop ||= 1;
1210 my $exclude_list = $cstore->request(
1211 'open-ils.cstore.json_query.atomic',
1213 select => { aufhol => [circ_lib] },
1215 where => { hold => $hold->id}
1220 if ($exclude_list && @$exclude_list) {
1221 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1222 # check to see if we've used up every library in the potentials list
1223 for my $l ( @$circ_lib_list ) {
1225 for my $ex ( @$exclude_list ) {
1231 push(@keepers, $l) if ($keep);
1234 @keepers = @$circ_lib_list;
1237 $current_loop++ if (!@keepers);
1239 if ($max_loops && $max_loops <= $current_loop) {
1240 # We haven't exceeded max_loops yet
1242 for my $cp ( @$all_copies ) {
1243 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1246 # We have, and should remove potentials and cancel the hold
1247 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1248 $_->delete for (@oldmaps);
1250 # cancel cause = un-targeted expiration
1251 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1252 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1254 # tell A/T the hold was cancelled
1255 my $fm_hold = $hold->to_fieldmapper;
1256 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1257 $ses->request('open-ils.trigger.event.autocreate',
1258 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1264 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1266 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1268 $best = choose_nearest_copy($hold, $prox_list);
1271 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1273 # hold wasn't fulfilled, record the fact
1275 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1276 action::unfulfilled_hold_list->create(
1277 { hold => ''.$hold->id,
1278 current_copy => ''.$old_best->id,
1279 circ_lib => ''.$old_best->circ_lib,
1284 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1285 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1288 action::hold_request
1290 { current_copy => $old_best->id,
1291 fulfillment_time => undef,
1292 cancel_time => undef,
1296 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1297 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1299 $hold->update( { prev_check_time => 'now' } );
1300 $log->info( "\tThere were no targetable copies for the hold" );
1303 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1304 $log->info("\tProcessing of hold ".$hold->id." complete.");
1307 { hold => $hold->id,
1308 old_target => ($old_best ? $old_best->id : undef),
1309 eligible_copies => $copy_count,
1310 target => ($best ? $best->id : undef) };
1315 $log->error("Processing of hold failed: $e");
1316 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1317 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1324 __PACKAGE__->register_method(
1325 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1327 method => 'new_hold_copy_targeter',
1330 sub reservation_targeter {
1333 my $one_reservation = shift;
1335 local $OpenILS::Application::Storage::WRITE = 1;
1340 if ($one_reservation) {
1341 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1342 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1345 # find all the reservations needing targeting
1347 booking::reservation->search_where(
1348 { current_resource => undef,
1349 cancel_time => undef,
1350 start_time => { '>' => 'now' }
1352 { order_by => 'start_time' }
1356 } catch Error with {
1358 die "Could not retrieve reservation requests:\n\n$e\n";
1362 for my $bresv (@$reservations) {
1364 #start a transaction if needed
1365 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1366 $log->debug("Cleaning up after previous transaction\n");
1367 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1369 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1370 $log->info("Processing reservation ".$bresv->id."...\n");
1372 #first, re-fetch the hold, to make sure it's not captured already
1373 $bresv->remove_from_object_index();
1374 $bresv = booking::reservation->retrieve( $bresv->id );
1376 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1378 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1379 if (DateTime->compare($end_time, DateTime->now) < 0) {
1381 # cancel cause = un-targeted expiration
1382 $bresv->update( { cancel_time => 'now' } );
1383 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1385 # tell A/T the reservation was cancelled
1386 my $fm_bresv = $bresv->to_fieldmapper;
1387 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1388 $ses->request('open-ils.trigger.event.autocreate',
1389 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1394 my $possible_resources;
1396 # find all the potential resources
1397 if (!$bresv->target_resource) {
1398 my $filter = { type => $bresv->target_resource_type };
1399 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1401 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1403 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1404 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1405 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1407 $possible_resources = $bresv->target_resource;
1410 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1411 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1414 my @good_resources = ();
1415 for my $res (@$all_resources) {
1416 unless (isTrue($res->type->catalog_item)) {
1417 push @good_resources, $res;
1421 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1424 push @good_resources, $res;
1428 if ($copy->status->id == 0 || $copy->status->id == 7) {
1429 push @good_resources, $res;
1433 if ($copy->status->id == 1) {
1434 my $circs = action::circulation->search_where(
1435 {target_copy => $copy->id, checkin_time => undef },
1436 { order_by => 'id DESC' }
1440 my $due_date = $circs->[0]->due_date;
1441 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1442 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1443 next if (DateTime->compare($start_time, $due_date) < 0);
1444 push @good_resources, $res;
1450 push @good_resources, $res if (isTrue($copy->status->holdable));
1453 # let 'em know we're still working
1454 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1456 # if we have no copies ...
1457 if (!@good_resources) {
1458 $log->info("\tNo resources available for targeting at all!\n");
1459 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1461 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1465 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1471 $_->owner == $bresv->pickup_lib
1475 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1476 # $all_copies is now a list of copies not at the pickup library
1478 my $best = shift @good_resources;
1479 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1482 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1486 sort { $a->[0] <=> $b->[0] }
1488 [ actor::org_unit_proximity->search_where(
1489 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1495 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1497 $best = shift @$prox_list
1501 $bresv->update( { current_resource => ''.$best->id } );
1502 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1505 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1506 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1509 { reservation => $bresv->id,
1510 current_resource => ($best ? $best->id : undef) };
1515 $log->error("Processing of bresv failed: $e");
1516 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1517 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1524 __PACKAGE__->register_method(
1525 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1527 method => 'reservation_targeter',
1532 my %cache = (titles => {}, cns => {});
1533 sub hold_copy_targeter {
1536 my $check_expire = shift;
1537 my $one_hold = shift;
1539 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1540 $self->{user_filter}->connect;
1541 $self->{client} = $client;
1544 $check_expire ||= '12h';
1545 $check_expire = interval_to_seconds( $check_expire );
1547 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1550 my $expire_threshold = sprintf(
1551 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1552 $year, $mon, $mday, $hour, $min, $sec
1556 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1558 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1562 %cache = (titles => {}, cns => {});
1566 $holds = [ action::hold_request->search(id => $one_hold) ];
1568 $holds = [ action::hold_request->search_where(
1569 { capture_time => undef,
1570 prev_check_time => { '<=' => $expire_threshold },
1572 { order_by => 'request_time,prev_check_time' } ) ];
1573 push @$holds, action::hold_request->search_where(
1574 { capture_time => undef,
1575 prev_check_time => undef,
1577 { order_by => 'request_time' } );
1579 } catch Error with {
1581 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1584 for my $hold (@$holds) {
1586 #action::hold_request->db_Main->begin_work;
1587 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1588 $client->respond("Cleaning up after previous transaction\n");
1589 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1591 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1592 $client->respond("Processing hold ".$hold->id."...\n");
1596 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1597 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1599 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1600 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1602 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1603 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1605 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1607 unless (ref $copies || !@$copies) {
1608 $client->respond("\tNo copies available for targeting at all!\n");
1612 for my $c (@$copies) {
1613 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1614 push @good_copies, $c if ($c);
1617 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1619 my $old_best = $hold->current_copy;
1620 $hold->update({ current_copy => undef });
1622 if (!scalar(@good_copies)) {
1623 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1624 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1625 $client->respond("\tPushing current_copy back onto the targeting list\n");
1626 push @good_copies, asset::copy->retrieve( $old_best );
1628 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1634 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1635 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1637 my $best = choose_nearest_copy($hold, $prox_list);
1640 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1641 $best = choose_nearest_copy($hold, $prox_list);
1645 # hold wasn't fulfilled, record the fact
1647 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1648 action::unfulfilled_hold_list->create(
1649 { hold => ''.$hold->id,
1650 current_copy => ''.$old_best->id,
1651 circ_lib => ''.$old_best->circ_lib,
1656 $hold->update( { current_copy => ''.$best->id } );
1657 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1660 $hold->update( { prev_check_time => 'now' } );
1661 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1663 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1664 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1666 #action::hold_request->dbi_commit;
1670 $log->error("Processing of hold failed: $e");
1671 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1672 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1673 #action::hold_request->dbi_rollback;
1677 $self->{user_filter}->disconnect;
1678 $self->{user_filter}->finish;
1679 delete $$self{user_filter};
1682 #__PACKAGE__->register_method(
1683 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1686 # method => 'hold_copy_targeter',
1690 sub copy_hold_capture {
1695 if (!defined($cps)) {
1697 $cps = [ asset::copy->search( id => $hold->target ) ];
1698 } catch Error with {
1700 die "Could not retrieve initial volume list:\n\n$e\n";
1704 my @copies = grep { $_->holdable } @$cps;
1706 for (my $i = 0; $i < @$cps; $i++) {
1707 next unless $$cps[$i];
1709 my $cn = $cache{cns}{$copies[$i]->call_number};
1710 my $rec = $cache{titles}{$cn->record};
1711 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1712 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1713 $copies[$i] = undef if (
1715 !$self->{user_filter}->request(
1716 'open-ils.circ.permit_hold',
1717 $hold->to_fieldmapper, do {
1718 my $cp_fm = $copies[$i]->to_fieldmapper;
1719 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1720 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1721 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1724 { title => $rec->to_fieldmapper,
1725 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1726 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1729 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1732 @copies = grep { $_ } @copies;
1734 my $count = @copies;
1736 return unless ($count);
1738 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1741 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1742 for my $c (@copies) {
1743 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1745 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1751 sub choose_nearest_copy {
1753 my $prox_list = shift;
1755 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1756 next unless (ref $$prox_list[$p]);
1758 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1759 next unless (@capturable);
1761 my $rand = int(rand(scalar(@capturable)));
1762 while (my ($c) = splice(@capturable,$rand)) {
1763 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1764 { title => $c->call_number->record->to_fieldmapper,
1765 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1766 patron => $hold->usr->to_fieldmapper,
1767 copy => $c->to_fieldmapper,
1768 requestor => $hold->requestor->to_fieldmapper,
1769 request_lib => $hold->request_lib->to_fieldmapper,
1770 pickup_lib => $hold->pickup_lib->id,
1774 last unless(@capturable);
1775 $rand = int(rand(scalar(@capturable)));
1780 sub create_prox_list {
1785 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1788 for my $cp (@$copies) {
1789 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1790 next unless (defined($prox));
1792 # Fetch the weighting value for hold targeting, defaulting to 1
1793 $self->{target_weight}{$lib} ||= $actor->request(
1794 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1797 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1798 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1799 push @{$prox_list[$prox]}, $cp;
1805 sub volume_hold_capture {
1810 if (!defined($vols)) {
1812 $vols = [ asset::call_number->search( id => $hold->target ) ];
1813 $cache{cns}{$_->id} = $_ for (@$vols);
1814 } catch Error with {
1816 die "Could not retrieve initial volume list:\n\n$e\n";
1820 my @v_ids = map { $_->id } @$vols;
1824 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1826 } catch Error with {
1828 warn "Could not retrieve copy list:\n\n$e\n";
1831 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1834 sub title_hold_capture {
1839 if (!defined($titles)) {
1841 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1842 $cache{titles}{$_->id} = $_ for (@$titles);
1843 } catch Error with {
1845 die "Could not retrieve initial title list:\n\n$e\n";
1849 my @t_ids = map { $_->id } @$titles;
1852 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1854 } catch Error with {
1856 warn "Could not retrieve volume list:\n\n$e\n";
1859 $cache{cns}{$_->id} = $_ for (@$cn_list);
1861 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1864 sub metarecord_hold_capture {
1870 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1872 } catch Error with {
1874 die "Could not retrieve initial title list:\n\n$e\n";
1878 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1880 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1882 } catch Error with {
1884 die "Could not retrieve format-pruned title list:\n\n$e\n";
1888 $cache{titles}{$_->id} = $_ for (@$titles);
1889 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);