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 if ($ctype eq 'reservation') {
677 $due_date_method = 'end_time';
678 $target_copy_method = 'current_resource';
679 $circ_lib_method = 'pickup_lib';
680 $recurring_fine_method = 'fine_amount';
681 next unless ($c->fine_interval);
685 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
686 $log->debug("Cleaning up after previous transaction\n");
687 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
689 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
690 $log->info("Processing circ ".$c->id."...\n");
693 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
695 my $due = $due_dt->epoch;
698 my $fine_interval = $c->fine_interval;
699 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
700 $fine_interval = interval_to_seconds( $fine_interval );
702 if ( $fine_interval >= interval_to_seconds('1d') ) {
704 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
705 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
708 $due -= ($due % $fine_interval) + $tz_offset_s;
709 $now -= ($now % $fine_interval) + $tz_offset_s;
713 "ARG! Overdue $ctype ".$c->id.
714 " for item ".$c->$target_copy_method.
715 " (user ".$c->usr.").\n".
716 "\tItem was due on or before: ".localtime($due)."\n");
718 my @fines = money::billing->search_where(
721 billing_ts => { '>' => $c->$due_date_method } },
722 { order_by => 'billing_ts DESC'}
726 my $fine = $fines[$f_idx] if (@fines);
728 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
731 my $current_fine_total = 0;
732 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
736 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
737 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
739 $log->info( "Potential first billing for circ ".$c->id );
743 if (my $h = $hoo{$c->$circ_lib_method}) {
745 $log->info( "Circ lib has an hours-of-operation entry" );
746 # find the day after the due date...
747 $due_dt = $due_dt->add( days => 1 );
749 # get the day of the week for that day...
750 my $dow = $due_dt->day_of_week_0;
751 my $dow_open = "dow_${dow}_open";
752 my $dow_close = "dow_${dow}_close";
755 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
756 # if the circ lib is closed, add a day to the grace period...
759 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
760 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
762 $due_dt = $due_dt->add( days => 1 );
763 $dow = $due_dt->day_of_week_0;
764 $dow_open = "dow_${dow}_open";
765 $dow_close = "dow_${dow}_close";
769 # and check for up to a week
770 last if ($count > 6);
777 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
778 if ($pending_fine_count < 1 + $grace) {
779 $client->respond( "\tNo fines to create. " );
780 if ($grace && $now < $due + $fine_interval * $grace) {
781 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
782 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
784 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
789 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
791 my $recurring_fine = int($c->$recurring_fine_method * 100);
792 my $max_fine = int($c->max_fine * 100);
794 my ($latest_billing_ts, $latest_amount) = ('',0);
795 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
797 if ($current_fine_total >= $max_fine) {
798 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
800 "\tMaximum fine level of ".$c->max_fine.
801 " reached for this $ctype.\n".
802 "\tNo more fines will be generated.\n" );
806 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
808 my $dow = $billing_ts->day_of_week_0();
809 my $dow_open = "dow_${dow}_open";
810 my $dow_close = "dow_${dow}_close";
812 if (my $h = $hoo{$c->$circ_lib_method}) {
813 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
816 my $timestamptz = $billing_ts->strftime('%FT%T%z');
817 my @cl = actor::org_unit::closed_date->search_where(
818 { close_start => { '<=' => $timestamptz },
819 close_end => { '>=' => $timestamptz },
820 org_unit => $c->$circ_lib_method }
824 $current_fine_total += $recurring_fine;
825 $latest_amount += $recurring_fine;
826 $latest_billing_ts = $timestamptz;
828 money::billing->create(
830 note => "System Generated Overdue Fine",
831 billing_type => "Overdue materials",
833 amount => sprintf('%0.2f', $recurring_fine/100),
834 billing_ts => $timestamptz,
840 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
841 if ($latest_billing_ts and $latest_amount);
843 $self->method_lookup('open-ils.storage.transaction.commit')->run;
847 # Caluclate penalties inline
848 OpenILS::Utils::Penalty->calculate_penalties(
849 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
853 # Calculate penalties with an aysnc call to the penalty server. This approach
854 # may lead to duplicate penalties since multiple penalty processes for a
855 # given user may be running at the same time. Leave this here for reference
856 # in case we later find that asyc calls are needed in some environments.
858 'open-ils.penalty.patron_penalty.calculate',
859 { patronid => ''.$c->usr,
860 context_org => ''.$c->$circ_lib_method,
869 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
870 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
871 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
872 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
876 __PACKAGE__->register_method(
877 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
880 method => 'generate_fines',
885 sub new_hold_copy_targeter {
888 my $check_expire = shift;
889 my $one_hold = shift;
891 local $OpenILS::Application::Storage::WRITE = 1;
893 $self->{target_weight} = {};
899 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
900 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
901 } elsif ( $check_expire ) {
903 # what's the retarget time threashold?
905 $check_expire ||= '12h';
906 $check_expire = interval_to_seconds( $check_expire );
908 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
911 my $expire_threshold = sprintf(
912 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
913 $year, $mon, $mday, $hour, $min, $sec
916 # find all the holds holds needing retargeting
917 $holds = [ action::hold_request->search_where(
918 { capture_time => undef,
919 fulfillment_time => undef,
920 cancel_time => undef,
922 prev_check_time => { '<=' => $expire_threshold },
924 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
926 # find all the holds holds needing first time targeting
927 push @$holds, action::hold_request->search(
928 capture_time => undef,
929 fulfillment_time => undef,
930 prev_check_time => undef,
932 cancel_time => undef,
933 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
936 # find all the holds holds needing first time targeting ONLY
937 $holds = [ action::hold_request->search(
938 capture_time => undef,
939 fulfillment_time => undef,
940 prev_check_time => undef,
941 cancel_time => undef,
943 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
947 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
950 my @closed = actor::org_unit::closed_date->search_where(
951 { close_start => { '<=', 'now' },
952 close_end => { '>=', 'now' } }
957 # $check_expire, if it exists, was already converted to seconds
958 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
962 my $next_check_time = sprintf(
963 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
964 $year, $mon, $mday, $hour, $min, $sec
968 my @closed_at_next = actor::org_unit::closed_date->search_where(
969 { close_start => { '<=', $next_check_time },
970 close_end => { '>=', $next_check_time } }
974 for my $c_at_n (@closed_at_next) {
975 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
976 push @new_closed, $c_at_n;
979 @closed = @new_closed;
983 my $actor = OpenSRF::AppSession->create('open-ils.actor');
985 for my $hold (@$holds) {
987 #start a transaction if needed
988 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
989 $log->debug("Cleaning up after previous transaction\n");
990 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
992 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
993 $log->info("Processing hold ".$hold->id."...\n");
995 #first, re-fetch the hold, to make sure it's not captured already
996 $hold->remove_from_object_index();
997 $hold = action::hold_request->retrieve( $hold->id );
999 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1001 # remove old auto-targeting maps
1002 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1003 $_->delete for (@oldmaps);
1005 if ($hold->expire_time) {
1006 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1007 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1009 # cancel cause = un-targeted expiration
1010 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1011 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1013 # tell A/T the hold was cancelled
1014 my $fm_hold = $hold->to_fieldmapper;
1015 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1016 $ses->request('open-ils.trigger.event.autocreate',
1017 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1023 my $all_copies = [];
1025 # find filters for MR holds
1026 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1028 # find all the potential copies
1029 if ($hold->hold_type eq 'M') {
1032 metabib::record_descriptor
1036 isTrue($_->deleted) ? () : ($_->id)
1037 } metabib::metarecord->retrieve($hold->target)->source_records
1039 ( $types ? (item_type => [split '', $types]) : () ),
1040 ( $formats ? (item_form => [split '', $formats]) : () ),
1041 ( $lang ? (item_lang => $lang) : () ),
1045 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1046 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1048 for my $cn ( @{ $rtree->call_numbers } ) {
1050 asset::copy->search_where(
1051 { id => [map {$_->id} @{ $cn->copies }],
1053 ) if ($cn && @{ $cn->copies });
1056 } elsif ($hold->hold_type eq 'T') {
1058 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1059 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1062 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1066 for my $cn ( @{ $rtree->call_numbers } ) {
1068 asset::copy->search_where(
1069 { id => [map {$_->id} @{ $cn->copies }],
1071 ) if ($cn && @{ $cn->copies });
1073 } elsif ($hold->hold_type eq 'V') {
1075 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1076 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1079 asset::copy->search_where(
1080 { id => [map {$_->id} @{ $vtree->copies }],
1082 ) if ($vtree && @{ $vtree->copies });
1084 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1085 my $_cp = asset::copy->retrieve($hold->target);
1086 push @$all_copies, $_cp if $_cp;
1090 @$all_copies = grep { isTrue($_->status->holdable) &&
1091 isTrue($_->location->holdable) &&
1092 isTrue($_->holdable) &&
1093 !isTrue($_->deleted) &&
1094 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1097 # let 'em know we're still working
1098 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1100 # if we have no copies ...
1101 if (!ref $all_copies || !@$all_copies) {
1102 $log->info("\tNo copies available for targeting at all!\n");
1103 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1105 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1106 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1110 my $copy_count = @$all_copies;
1112 # map the potentials, so that we can pick up checkins
1113 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1114 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1115 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1116 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1118 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1121 for my $c (@$all_copies) {
1123 next if ($c->id eq $hold->current_copy);
1125 # circ lib is closed
1126 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1128 # target of another hold
1129 next if (action::hold_request
1131 { current_copy => $c->id,
1132 fulfillment_time => undef,
1133 cancel_time => undef,
1138 # we passed all three, keep it
1139 push @good_copies, $c if ($c);
1140 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1143 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1145 my $old_best = $hold->current_copy;
1146 $hold->update({ current_copy => undef }) if ($old_best);
1148 if (!scalar(@good_copies)) {
1149 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1150 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1151 # the old copy is still available
1152 $log->debug("\tPushing current_copy back onto the targeting list");
1153 push @good_copies, $old_best;
1155 # oops, old copy is not available
1156 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1157 $hold->update( { prev_check_time => 'today' } );
1158 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1159 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1168 $_->circ_lib == $hold->pickup_lib
1172 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1173 # $all_copies is now a list of copies not at the pickup library
1175 my $best = choose_nearest_copy($hold, $prox_list);
1176 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1179 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1181 my $max_loops = $actor->request(
1182 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1185 if (defined($max_loops)) {
1186 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1187 my $circ_lib_list = [keys %circ_lib_map];
1189 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1191 # Grab the "biggest" loop for this hold so far
1192 my $current_loop = $cstore->request(
1193 'open-ils.cstore.json_query',
1195 select => { aufhmxl => ['max'] },
1197 where => { hold => $hold->id}
1201 $current_loop = $current_loop->{max} if ($current_loop);
1202 $current_loop ||= 1;
1204 my $exclude_list = $cstore->request(
1205 'open-ils.cstore.json_query.atomic',
1207 select => { aufhol => [circ_lib] },
1209 where => { hold => $hold->id}
1214 if ($exclude_list && @$exclude_list) {
1215 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1216 # check to see if we've used up every library in the potentials list
1217 for my $l ( @$circ_lib_list ) {
1219 for my $ex ( @$exclude_list ) {
1225 push(@keepers, $l) if ($keep);
1228 @keepers = @$circ_lib_list;
1231 $current_loop++ if (!@keepers);
1233 if ($max_loops && $max_loops <= $current_loop) {
1234 # We haven't exceeded max_loops yet
1236 for my $cp ( @$all_copies ) {
1237 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1240 # We have, and should remove potentials and cancel the hold
1241 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1242 $_->delete for (@oldmaps);
1244 # cancel cause = un-targeted expiration
1245 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1246 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1248 # tell A/T the hold was cancelled
1249 my $fm_hold = $hold->to_fieldmapper;
1250 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1251 $ses->request('open-ils.trigger.event.autocreate',
1252 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1258 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1260 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1262 $best = choose_nearest_copy($hold, $prox_list);
1265 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1267 # hold wasn't fulfilled, record the fact
1269 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1270 action::unfulfilled_hold_list->create(
1271 { hold => ''.$hold->id,
1272 current_copy => ''.$old_best->id,
1273 circ_lib => ''.$old_best->circ_lib,
1278 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1279 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1282 action::hold_request
1284 { current_copy => $old_best->id,
1285 fulfillment_time => undef,
1286 cancel_time => undef,
1290 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1291 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1293 $hold->update( { prev_check_time => 'now' } );
1294 $log->info( "\tThere were no targetable copies for the hold" );
1297 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1298 $log->info("\tProcessing of hold ".$hold->id." complete.");
1301 { hold => $hold->id,
1302 old_target => ($old_best ? $old_best->id : undef),
1303 eligible_copies => $copy_count,
1304 target => ($best ? $best->id : undef) };
1309 $log->error("Processing of hold failed: $e");
1310 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1311 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1318 __PACKAGE__->register_method(
1319 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1321 method => 'new_hold_copy_targeter',
1324 sub reservation_targeter {
1327 my $one_reservation = shift;
1329 local $OpenILS::Application::Storage::WRITE = 1;
1334 if ($one_reservation) {
1335 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1336 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1339 # find all the reservations needing targeting
1341 booking::reservation->search_where(
1342 { current_resource => undef,
1343 cancel_time => undef,
1344 start_time => { '>' => 'now' }
1346 { order_by => 'start_time' }
1350 } catch Error with {
1352 die "Could not retrieve reservation requests:\n\n$e\n";
1356 for my $bresv (@$reservations) {
1358 #start a transaction if needed
1359 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1360 $log->debug("Cleaning up after previous transaction\n");
1361 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1363 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1364 $log->info("Processing reservation ".$bresv->id."...\n");
1366 #first, re-fetch the hold, to make sure it's not captured already
1367 $bresv->remove_from_object_index();
1368 $bresv = booking::reservation->retrieve( $bresv->id );
1370 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1372 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1373 if (DateTime->compare($end_time, DateTime->now) < 0) {
1375 # cancel cause = un-targeted expiration
1376 $bresv->update( { cancel_time => 'now' } );
1377 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1379 # tell A/T the reservation was cancelled
1380 my $fm_bresv = $bresv->to_fieldmapper;
1381 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1382 $ses->request('open-ils.trigger.event.autocreate',
1383 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1388 my $possible_resources;
1390 # find all the potential resources
1391 if (!$bresv->target_resource) {
1392 my $filter = { type => $bresv->target_resource_type };
1393 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1395 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1397 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1398 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1399 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1401 $possible_resources = $bresv->target_resource;
1404 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1405 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1408 my @good_resources = ();
1409 for my $res (@$all_resources) {
1410 unless (isTrue($res->type->catalog_item)) {
1411 push @good_resources, $res;
1415 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1418 push @good_resources, $res;
1422 if ($copy->status->id == 0 || $copy->status->id == 7) {
1423 push @good_resources, $res;
1427 if ($copy->status->id == 1) {
1428 my $circs = action::circulation->search_where(
1429 {target_copy => $copy->id, checkin_time => undef },
1430 { order_by => 'id DESC' }
1434 my $due_date = $circs->[0]->due_date;
1435 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1436 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1437 next if (DateTime->compare($start_time, $due_date) < 0);
1438 push @good_resources, $res;
1444 push @good_resources, $res if (isTrue($copy->status->holdable));
1447 # let 'em know we're still working
1448 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1450 # if we have no copies ...
1451 if (!@good_resources) {
1452 $log->info("\tNo resources available for targeting at all!\n");
1453 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1455 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1459 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1465 $_->owner == $bresv->pickup_lib
1469 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1470 # $all_copies is now a list of copies not at the pickup library
1472 my $best = shift @good_resources;
1473 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1476 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1480 sort { $a->[0] <=> $b->[0] }
1482 [ actor::org_unit_proximity->search_where(
1483 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1489 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1491 $best = shift @$prox_list
1495 $bresv->update( { current_resource => ''.$best->id } );
1496 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1499 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1500 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1503 { reservation => $bresv->id,
1504 current_resource => ($best ? $best->id : undef) };
1509 $log->error("Processing of bresv failed: $e");
1510 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1511 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1518 __PACKAGE__->register_method(
1519 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1521 method => 'reservation_targeter',
1526 my %cache = (titles => {}, cns => {});
1527 sub hold_copy_targeter {
1530 my $check_expire = shift;
1531 my $one_hold = shift;
1533 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1534 $self->{user_filter}->connect;
1535 $self->{client} = $client;
1538 $check_expire ||= '12h';
1539 $check_expire = interval_to_seconds( $check_expire );
1541 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1544 my $expire_threshold = sprintf(
1545 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1546 $year, $mon, $mday, $hour, $min, $sec
1550 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1552 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1556 %cache = (titles => {}, cns => {});
1560 $holds = [ action::hold_request->search(id => $one_hold) ];
1562 $holds = [ action::hold_request->search_where(
1563 { capture_time => undef,
1564 prev_check_time => { '<=' => $expire_threshold },
1566 { order_by => 'request_time,prev_check_time' } ) ];
1567 push @$holds, action::hold_request->search_where(
1568 { capture_time => undef,
1569 prev_check_time => undef,
1571 { order_by => 'request_time' } );
1573 } catch Error with {
1575 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1578 for my $hold (@$holds) {
1580 #action::hold_request->db_Main->begin_work;
1581 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1582 $client->respond("Cleaning up after previous transaction\n");
1583 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1585 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1586 $client->respond("Processing hold ".$hold->id."...\n");
1590 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1591 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1593 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1594 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1596 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1597 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1599 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1601 unless (ref $copies || !@$copies) {
1602 $client->respond("\tNo copies available for targeting at all!\n");
1606 for my $c (@$copies) {
1607 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1608 push @good_copies, $c if ($c);
1611 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1613 my $old_best = $hold->current_copy;
1614 $hold->update({ current_copy => undef });
1616 if (!scalar(@good_copies)) {
1617 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1618 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1619 $client->respond("\tPushing current_copy back onto the targeting list\n");
1620 push @good_copies, asset::copy->retrieve( $old_best );
1622 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1628 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1629 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1631 my $best = choose_nearest_copy($hold, $prox_list);
1634 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1635 $best = choose_nearest_copy($hold, $prox_list);
1639 # hold wasn't fulfilled, record the fact
1641 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1642 action::unfulfilled_hold_list->create(
1643 { hold => ''.$hold->id,
1644 current_copy => ''.$old_best->id,
1645 circ_lib => ''.$old_best->circ_lib,
1650 $hold->update( { current_copy => ''.$best->id } );
1651 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1654 $hold->update( { prev_check_time => 'now' } );
1655 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1657 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1658 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1660 #action::hold_request->dbi_commit;
1664 $log->error("Processing of hold failed: $e");
1665 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1666 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1667 #action::hold_request->dbi_rollback;
1671 $self->{user_filter}->disconnect;
1672 $self->{user_filter}->finish;
1673 delete $$self{user_filter};
1676 #__PACKAGE__->register_method(
1677 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1680 # method => 'hold_copy_targeter',
1684 sub copy_hold_capture {
1689 if (!defined($cps)) {
1691 $cps = [ asset::copy->search( id => $hold->target ) ];
1692 } catch Error with {
1694 die "Could not retrieve initial volume list:\n\n$e\n";
1698 my @copies = grep { $_->holdable } @$cps;
1700 for (my $i = 0; $i < @$cps; $i++) {
1701 next unless $$cps[$i];
1703 my $cn = $cache{cns}{$copies[$i]->call_number};
1704 my $rec = $cache{titles}{$cn->record};
1705 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1706 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1707 $copies[$i] = undef if (
1709 !$self->{user_filter}->request(
1710 'open-ils.circ.permit_hold',
1711 $hold->to_fieldmapper, do {
1712 my $cp_fm = $copies[$i]->to_fieldmapper;
1713 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1714 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1715 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1718 { title => $rec->to_fieldmapper,
1719 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1720 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1723 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1726 @copies = grep { $_ } @copies;
1728 my $count = @copies;
1730 return unless ($count);
1732 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1735 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1736 for my $c (@copies) {
1737 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1739 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1745 sub choose_nearest_copy {
1747 my $prox_list = shift;
1749 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1750 next unless (ref $$prox_list[$p]);
1752 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1753 next unless (@capturable);
1755 my $rand = int(rand(scalar(@capturable)));
1756 while (my ($c) = splice(@capturable,$rand)) {
1757 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1758 { title => $c->call_number->record->to_fieldmapper,
1759 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1760 patron => $hold->usr->to_fieldmapper,
1761 copy => $c->to_fieldmapper,
1762 requestor => $hold->requestor->to_fieldmapper,
1763 request_lib => $hold->request_lib->to_fieldmapper,
1764 pickup_lib => $hold->pickup_lib->id,
1768 last unless(@capturable);
1769 $rand = int(rand(scalar(@capturable)));
1774 sub create_prox_list {
1779 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1782 for my $cp (@$copies) {
1783 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1784 next unless (defined($prox));
1786 # Fetch the weighting value for hold targeting, defaulting to 1
1787 $self->{target_weight}{$lib} ||= $actor->request(
1788 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1791 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1792 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1793 push @{$prox_list[$prox]}, $cp;
1799 sub volume_hold_capture {
1804 if (!defined($vols)) {
1806 $vols = [ asset::call_number->search( id => $hold->target ) ];
1807 $cache{cns}{$_->id} = $_ for (@$vols);
1808 } catch Error with {
1810 die "Could not retrieve initial volume list:\n\n$e\n";
1814 my @v_ids = map { $_->id } @$vols;
1818 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1820 } catch Error with {
1822 warn "Could not retrieve copy list:\n\n$e\n";
1825 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1828 sub title_hold_capture {
1833 if (!defined($titles)) {
1835 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1836 $cache{titles}{$_->id} = $_ for (@$titles);
1837 } catch Error with {
1839 die "Could not retrieve initial title list:\n\n$e\n";
1843 my @t_ids = map { $_->id } @$titles;
1846 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1848 } catch Error with {
1850 warn "Could not retrieve volume list:\n\n$e\n";
1853 $cache{cns}{$_->id} = $_ for (@$cn_list);
1855 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1858 sub metarecord_hold_capture {
1864 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1866 } catch Error with {
1868 die "Could not retrieve initial title list:\n\n$e\n";
1872 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1874 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1876 } catch Error with {
1878 die "Could not retrieve format-pruned title list:\n\n$e\n";
1882 $cache{titles}{$_->id} = $_ for (@$titles);
1883 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);