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',
44 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;
150 my $atc = action::transit_copy->table;
157 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
159 JOIN $circ circ ON (circ.target_copy = cp.id)
160 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
161 LEFT JOIN $setting setting
162 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
163 WHERE circ.checkin_time IS NOT NULL
167 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
168 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
170 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
171 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
177 LEFT JOIN $setting setting
178 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
179 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
182 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
185 my $sth = action::circulation->db_Main->prepare_cached($sql);
186 $sth->execute($window, $window, $window);
191 __PACKAGE__->register_method(
192 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
195 method => 'complete_reshelving',
198 sub mark_longoverdue {
203 local $OpenILS::Application::Storage::WRITE = 1;
205 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
206 unless (interval_to_seconds( $window ));
208 my $setting = actor::org_unit_setting->table;
209 my $circ = action::circulation->table;
213 SET stop_fines = 'LONGOVERDUE',
214 stop_fines_time = now()
218 LEFT JOIN $setting setting
219 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
220 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
221 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
225 my $sth = action::circulation->db_Main->prepare_cached($sql);
226 $sth->execute($window);
231 __PACKAGE__->register_method(
232 api_name => 'open-ils.storage.action.circulation.long_overdue',
235 method => 'mark_longoverdue',
238 sub auto_thaw_frozen_holds {
242 local $OpenILS::Application::Storage::WRITE = 1;
244 my $holds = action::hold_request->table;
246 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
248 my $sth = action::hold_request->db_Main->prepare_cached($sql);
254 __PACKAGE__->register_method(
255 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
259 method => 'auto_thaw_frozen_holds',
265 my $grace = shift || '';
267 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
272 __PACKAGE__->register_method(
273 api_name => 'open-ils.storage.action.circulation.overdue',
276 method => 'grab_overdue',
284 my $limit = int(shift()) || 10;
285 my $age = shift() || '0 seconds';
288 my $holdsort = isTrue($fifo) ?
289 "CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.request_time, h.selection_depth DESC, p.prox " :
290 "p.prox, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
292 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
294 FROM action.hold_request h
295 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
296 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
297 WHERE hm.target_copy = ?
298 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
299 AND h.capture_time IS NULL
300 AND h.cancel_time IS NULL
301 AND (h.expire_time IS NULL OR h.expire_time > NOW())
302 AND h.frozen IS FALSE
307 $client->respond( $_ ) for ( @$ids );
310 __PACKAGE__->register_method(
311 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
314 method => 'nearest_hold',
317 sub next_resp_group_id {
321 # XXX This is not replication safe!!!
323 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
324 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
328 __PACKAGE__->register_method(
329 api_name => 'open-ils.storage.action.survey_response.next_group_id',
331 method => 'next_resp_group_id',
334 sub patron_circ_summary {
339 return undef unless ($id);
340 my $c_table = action::circulation->table;
341 my $b_table = money::billing->table;
343 $log->debug("Retrieving patron summary for id $id", DEBUG);
345 my $select = <<" SQL";
346 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
348 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
350 AND c.xact_finish IS NULL
352 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
353 OR c.stop_fines IS NULL
357 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
359 __PACKAGE__->register_method(
360 api_name => 'open-ils.storage.action.circulation.patron_summary',
362 method => 'patron_circ_summary',
365 #XXX Fix stored proc calls
366 sub find_local_surveys {
371 return undef unless ($ou);
372 my $s_table = action::survey->table;
374 my $select = <<" SQL";
377 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
378 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
381 my $sth = action::survey->db_Main->prepare_cached($select);
384 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
388 __PACKAGE__->register_method(
389 api_name => 'open-ils.storage.action.survey.all',
392 method => 'find_local_surveys',
395 #XXX Fix stored proc calls
396 sub find_opac_surveys {
401 return undef unless ($ou);
402 my $s_table = action::survey->table;
404 my $select = <<" SQL";
407 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
408 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
412 my $sth = action::survey->db_Main->prepare_cached($select);
415 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
419 __PACKAGE__->register_method(
420 api_name => 'open-ils.storage.action.survey.opac',
423 method => 'find_opac_surveys',
430 my $limit = shift || 10;
431 my $offset = shift || 0;
433 return undef unless ($ou);
434 my $h_table = action::hold_request->table;
435 my $a_table = asset::copy->table;
436 my $ord_table = asset::copy_location_order->table;
438 my $idlist = 1 if ($self->api_name =~/id_list/o);
439 my $count = 1 if ($self->api_name =~/count$/o);
441 my $status_filter = '';
442 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
444 my $select = <<" SQL";
447 JOIN $a_table a ON (h.current_copy = a.id)
448 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
450 AND h.capture_time IS NULL
451 AND h.cancel_time IS NULL
452 AND (h.expire_time IS NULL OR h.expire_time > NOW())
454 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
463 JOIN $a_table a ON (h.current_copy = a.id)
465 AND h.capture_time IS NULL
466 AND h.cancel_time IS NULL
467 AND (h.expire_time IS NULL OR h.expire_time > NOW())
472 my $sth = action::survey->db_Main->prepare_cached($select);
476 $client->respond( $sth->fetchall_arrayref()->[0][0] );
478 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
480 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
485 __PACKAGE__->register_method(
486 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
490 "Returns a count of holds for a specific library's pull list.",
491 [ [org_unit => "The library's org id", "number"] ],
492 ['A count of holds for the stated library to pull ', 'number']
494 method => 'hold_pull_list',
496 __PACKAGE__->register_method(
497 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
501 "Returns a status filtered count of holds for a specific library's pull list.",
502 [ [org_unit => "The library's org id", "number"] ],
503 ['A status filtered count of holds for the stated library to pull ', 'number']
505 method => 'hold_pull_list',
507 __PACKAGE__->register_method(
508 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
512 "Returns the hold ids for a specific library's pull list.",
513 [ [org_unit => "The library's org id", "number"],
514 [limit => 'An optional page size, defaults to 10', 'number'],
515 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
517 ['A list of holds for the stated library to pull for', 'array']
519 method => 'hold_pull_list',
521 __PACKAGE__->register_method(
522 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
526 "Returns the holds for a specific library's pull list.",
527 [ [org_unit => "The library's org id", "number"],
528 [limit => 'An optional page size, defaults to 10', 'number'],
529 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
531 ['A list of holds for the stated library to pull for', 'array']
533 method => 'hold_pull_list',
535 __PACKAGE__->register_method(
536 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
540 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
541 [ [org_unit => "The library's org id", "number"],
542 [limit => 'An optional page size, defaults to 10', 'number'],
543 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
545 ['A list of holds for the stated library to pull for', 'array']
547 method => 'hold_pull_list',
549 __PACKAGE__->register_method(
550 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
554 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
555 [ [org_unit => "The library's org id", "number"],
556 [limit => 'An optional page size, defaults to 10', 'number'],
557 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
559 ['A list of holds for the stated library to pull for', 'array']
561 method => 'hold_pull_list',
564 sub find_optional_surveys {
569 return undef unless ($ou);
570 my $s_table = action::survey->table;
572 my $select = <<" SQL";
575 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
576 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
577 AND s.required IS FALSE;
580 my $sth = action::survey->db_Main->prepare_cached($select);
583 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
587 __PACKAGE__->register_method(
588 api_name => 'open-ils.storage.action.survey.optional',
591 method => 'find_optional_surveys',
594 sub find_required_surveys {
599 return undef unless ($ou);
600 my $s_table = action::survey->table;
602 my $select = <<" SQL";
605 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
606 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
607 AND s.required IS TRUE;
610 my $sth = action::survey->db_Main->prepare_cached($select);
613 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
617 __PACKAGE__->register_method(
618 api_name => 'open-ils.storage.action.survey.required',
621 method => 'find_required_surveys',
624 sub find_usr_summary_surveys {
629 return undef unless ($ou);
630 my $s_table = action::survey->table;
632 my $select = <<" SQL";
635 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
636 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
637 AND s.usr_summary IS TRUE;
640 my $sth = action::survey->db_Main->prepare_cached($select);
643 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
647 __PACKAGE__->register_method(
648 api_name => 'open-ils.storage.action.survey.usr_summary',
651 method => 'find_usr_summary_surveys',
654 sub seconds_to_interval_hash {
655 my $interval = shift;
656 my $limit = shift || 's';
657 $limit =~ s/^(.)/$1/o;
661 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
662 my ($year, $month, $week, $day, $hour, $minute, $second) =
663 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
665 if ($y = int($interval / (60 * 60 * 24 * 365))) {
667 $ym = $interval % (60 * 60 * 24 * 365);
671 return %output if ($limit eq 'y');
673 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
674 $output{$month} = $M;
675 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
679 return %output if ($limit eq 'M');
681 if ($w = int($Mm / 604800)) {
687 return %output if ($limit eq 'w');
689 if ($d = int($wm / 86400)) {
695 return %output if ($limit eq 'd');
697 if ($h = int($dm / 3600)) {
703 return %output if ($limit eq 'h');
705 if ($m = int($hm / 60)) {
706 $output{$minute} = $m;
711 return %output if ($limit eq 'm');
714 $output{$second} = $s;
716 $output{$second} = 0 unless (keys %output);
727 my $overbill = shift;
729 local $OpenILS::Application::Storage::WRITE = 1;
734 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
735 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
737 push @circs, overdue_circs($grace);
740 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
742 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
746 $ctype =~ s/^.+::(\w+)$/$1/;
748 my $due_date_method = 'due_date';
749 my $target_copy_method = 'target_copy';
750 my $circ_lib_method = 'circ_lib';
751 my $recurring_fine_method = 'recurring_fine';
752 my $is_reservation = 0;
753 if ($ctype eq 'reservation') {
755 $due_date_method = 'end_time';
756 $target_copy_method = 'current_resource';
757 $circ_lib_method = 'pickup_lib';
758 $recurring_fine_method = 'fine_amount';
759 next unless ($c->fine_interval);
763 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
764 $log->debug("Cleaning up after previous transaction\n");
765 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
767 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
769 sprintf("Processing %s %d...",
770 ($is_reservation ? "reservation" : "circ"), $c->id
775 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
777 my $due = $due_dt->epoch;
780 my $fine_interval = $c->fine_interval;
781 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
782 $fine_interval = interval_to_seconds( $fine_interval );
784 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
786 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
787 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
790 $due -= ($due % $fine_interval) + $tz_offset_s;
791 $now -= ($now % $fine_interval) + $tz_offset_s;
795 "ARG! Overdue $ctype ".$c->id.
796 " for item ".$c->$target_copy_method.
797 " (user ".$c->usr.").\n".
798 "\tItem was due on or before: ".localtime($due)."\n");
800 my @fines = money::billing->search_where(
803 billing_ts => { '>' => $c->$due_date_method } },
804 { order_by => 'billing_ts DESC'}
808 my $fine = $fines[$f_idx] if (@fines);
810 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
813 my $current_fine_total = 0;
814 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
818 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
819 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
821 $log->info( "Potential first billing for circ ".$c->id );
825 if (my $h = $hoo{$c->$circ_lib_method}) {
827 $log->info( "Circ lib has an hours-of-operation entry" );
828 # find the day after the due date...
829 $due_dt = $due_dt->add( days => 1 );
831 # get the day of the week for that day...
832 my $dow = $due_dt->day_of_week_0;
833 my $dow_open = "dow_${dow}_open";
834 my $dow_close = "dow_${dow}_close";
837 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
838 # if the circ lib is closed, add a day to the grace period...
841 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
842 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
844 $due_dt = $due_dt->add( days => 1 );
845 $dow = $due_dt->day_of_week_0;
846 $dow_open = "dow_${dow}_open";
847 $dow_close = "dow_${dow}_close";
851 # and check for up to a week
852 last if ($count > 6);
858 next if ($last_fine > $now);
859 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
861 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
862 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
864 if ( $last_fine == $due # we have no fines yet
865 && $grace # and we have a grace period
866 && $pending_fine_count <= $grace # and we seem to be inside that period
867 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
869 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
870 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
874 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
875 next unless ($pending_fine_count);
877 my $recurring_fine = int($c->$recurring_fine_method * 100);
878 my $max_fine = int($c->max_fine * 100);
880 my ($latest_billing_ts, $latest_amount) = ('',0);
881 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
883 if ($current_fine_total >= $max_fine) {
884 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
886 "\tMaximum fine level of ".$c->max_fine.
887 " reached for this $ctype.\n".
888 "\tNo more fines will be generated.\n" );
892 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
893 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
894 my $current_bill_count = $bill;
895 while ( $current_bill_count ) {
896 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
897 $current_bill_count--;
900 my $dow = $billing_ts->day_of_week_0();
901 my $dow_open = "dow_${dow}_open";
902 my $dow_close = "dow_${dow}_close";
904 if (my $h = $hoo{$c->$circ_lib_method}) {
905 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
908 my $timestamptz = $billing_ts->strftime('%FT%T%z');
909 my @cl = actor::org_unit::closed_date->search_where(
910 { close_start => { '<=' => $timestamptz },
911 close_end => { '>=' => $timestamptz },
912 org_unit => $c->$circ_lib_method }
916 $current_fine_total += $recurring_fine;
917 $latest_amount += $recurring_fine;
918 $latest_billing_ts = $timestamptz;
920 money::billing->create(
922 note => "System Generated Overdue Fine",
923 billing_type => "Overdue materials",
925 amount => sprintf('%0.2f', $recurring_fine/100),
926 billing_ts => $timestamptz,
932 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
933 if ($latest_billing_ts and $latest_amount);
935 $self->method_lookup('open-ils.storage.transaction.commit')->run;
939 # Caluclate penalties inline
940 OpenILS::Utils::Penalty->calculate_penalties(
941 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
945 # Calculate penalties with an aysnc call to the penalty server. This approach
946 # may lead to duplicate penalties since multiple penalty processes for a
947 # given user may be running at the same time. Leave this here for reference
948 # in case we later find that asyc calls are needed in some environments.
950 'open-ils.penalty.patron_penalty.calculate',
951 { patronid => ''.$c->usr,
952 context_org => ''.$c->$circ_lib_method,
961 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
962 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
963 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
964 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
968 __PACKAGE__->register_method(
969 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
972 method => 'generate_fines',
977 sub new_hold_copy_targeter {
980 my $check_expire = shift;
981 my $one_hold = shift;
983 local $OpenILS::Application::Storage::WRITE = 1;
985 $self->{target_weight} = {};
986 $self->{max_loops} = {};
992 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
993 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
994 } elsif ( $check_expire ) {
996 # what's the retarget time threashold?
998 $check_expire ||= '12h';
999 $check_expire = interval_to_seconds( $check_expire );
1001 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1004 my $expire_threshold = sprintf(
1005 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1006 $year, $mon, $mday, $hour, $min, $sec
1009 # find all the holds holds needing retargeting
1010 $holds = [ action::hold_request->search_where(
1011 { capture_time => undef,
1012 fulfillment_time => undef,
1013 cancel_time => undef,
1015 prev_check_time => { '<=' => $expire_threshold },
1017 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1019 # find all the holds holds needing first time targeting
1020 push @$holds, action::hold_request->search(
1021 capture_time => undef,
1022 fulfillment_time => undef,
1023 prev_check_time => undef,
1025 cancel_time => undef,
1026 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1029 # find all the holds holds needing first time targeting ONLY
1030 $holds = [ action::hold_request->search(
1031 capture_time => undef,
1032 fulfillment_time => undef,
1033 prev_check_time => undef,
1034 cancel_time => undef,
1036 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1038 } catch Error with {
1040 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1043 my @closed = actor::org_unit::closed_date->search_where(
1044 { close_start => { '<=', 'now' },
1045 close_end => { '>=', 'now' } }
1048 if ($check_expire) {
1050 # $check_expire, if it exists, was already converted to seconds
1051 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1055 my $next_check_time = sprintf(
1056 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1057 $year, $mon, $mday, $hour, $min, $sec
1061 my @closed_at_next = actor::org_unit::closed_date->search_where(
1062 { close_start => { '<=', $next_check_time },
1063 close_end => { '>=', $next_check_time } }
1067 for my $c_at_n (@closed_at_next) {
1068 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1069 push @new_closed, $c_at_n;
1072 @closed = @new_closed;
1076 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1078 for my $hold (@$holds) {
1080 #start a transaction if needed
1081 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1082 $log->debug("Cleaning up after previous transaction\n");
1083 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1085 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1086 $log->info("Processing hold ".$hold->id."...\n");
1088 #first, re-fetch the hold, to make sure it's not captured already
1089 $hold->remove_from_object_index();
1090 $hold = action::hold_request->retrieve( $hold->id );
1092 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1094 # remove old auto-targeting maps
1095 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1096 $_->delete for (@oldmaps);
1098 if ($hold->expire_time) {
1099 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1100 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1102 # cancel cause = un-targeted expiration
1103 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1104 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1106 # tell A/T the hold was cancelled
1107 my $fm_hold = $hold->to_fieldmapper;
1108 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1109 $ses->request('open-ils.trigger.event.autocreate',
1110 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1116 my $all_copies = [];
1118 # find filters for MR holds
1119 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1121 # find all the potential copies
1122 if ($hold->hold_type eq 'M') {
1125 metabib::record_descriptor
1129 isTrue($_->deleted) ? () : ($_->id)
1130 } metabib::metarecord->retrieve($hold->target)->source_records
1132 ( $types ? (item_type => [split '', $types]) : () ),
1133 ( $formats ? (item_form => [split '', $formats]) : () ),
1134 ( $lang ? (item_lang => $lang) : () ),
1138 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1139 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1141 for my $cn ( @{ $rtree->call_numbers } ) {
1143 asset::copy->search_where(
1144 { id => [map {$_->id} @{ $cn->copies }],
1146 ) if ($cn && @{ $cn->copies });
1149 } elsif ($hold->hold_type eq 'T') {
1151 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1152 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1155 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1159 for my $cn ( @{ $rtree->call_numbers } ) {
1161 asset::copy->search_where(
1162 { id => [map {$_->id} @{ $cn->copies }],
1164 ) if ($cn && @{ $cn->copies });
1166 } elsif ($hold->hold_type eq 'V') {
1168 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1169 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1172 asset::copy->search_where(
1173 { id => [map {$_->id} @{ $vtree->copies }],
1175 ) if ($vtree && @{ $vtree->copies });
1177 } elsif ($hold->hold_type eq 'I') {
1179 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1180 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1183 asset::copy->search_where(
1184 { id => [map {$_->unit->id} @{ $itree->items }],
1186 ) if ($itree && @{ $itree->items });
1188 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1189 my $_cp = asset::copy->retrieve($hold->target);
1190 push @$all_copies, $_cp if $_cp;
1194 @$all_copies = grep { isTrue($_->status->holdable) &&
1195 isTrue($_->location->holdable) &&
1196 isTrue($_->holdable) &&
1197 !isTrue($_->deleted) &&
1198 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1201 # let 'em know we're still working
1202 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1204 # if we have no copies ...
1205 if (!ref $all_copies || !@$all_copies) {
1206 $log->info("\tNo copies available for targeting at all!\n");
1207 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1209 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1210 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1214 my $copy_count = @$all_copies;
1216 # map the potentials, so that we can pick up checkins
1217 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1218 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1219 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1220 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1222 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1225 for my $c (@$all_copies) {
1227 next if ($c->id eq $hold->current_copy);
1229 # circ lib is closed
1230 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1232 # target of another hold
1233 next if (action::hold_request
1235 { current_copy => $c->id,
1236 fulfillment_time => undef,
1237 cancel_time => undef,
1242 # we passed all three, keep it
1243 push @good_copies, $c if ($c);
1244 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1247 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1249 my $old_best = $hold->current_copy;
1250 $hold->update({ current_copy => undef }) if ($old_best);
1252 if (!scalar(@good_copies)) {
1253 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1254 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1255 # the old copy is still available
1256 $log->debug("\tPushing current_copy back onto the targeting list");
1257 push @good_copies, $old_best;
1259 # oops, old copy is not available
1260 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1261 $hold->update( { prev_check_time => 'today' } );
1262 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1263 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1268 my $pu_lib = ''.$hold->pickup_lib;
1274 ''.$_->circ_lib eq $pu_lib &&
1275 ( $_->status == 0 || $_->status == 7 )
1279 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1280 # $all_copies is now a list of copies not at the pickup library
1282 my $best = choose_nearest_copy($hold, $prox_list);
1283 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1286 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1288 $self->{max_loops}{$pu_lib} = $actor->request(
1289 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1292 if (defined($self->{max_loops}{$pu_lib})) {
1293 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1295 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1296 my $circ_lib_list = [keys %circ_lib_map];
1298 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1300 # Grab the "biggest" loop for this hold so far
1301 my $current_loop = $cstore->request(
1302 'open-ils.cstore.json_query',
1304 select => { aufhmxl => ['max'] },
1306 where => { hold => $hold->id}
1310 $current_loop = $current_loop->{max} if ($current_loop);
1311 $current_loop ||= 1;
1313 my $exclude_list = $cstore->request(
1314 'open-ils.cstore.json_query.atomic',
1316 select => { aufhol => ['circ_lib'] },
1318 where => { hold => $hold->id}
1323 if ($exclude_list && @$exclude_list) {
1324 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1325 # check to see if we've used up every library in the potentials list
1326 for my $l ( @$circ_lib_list ) {
1328 for my $ex ( @$exclude_list ) {
1334 push(@keepers, $l) if ($keep);
1337 @keepers = @$circ_lib_list;
1340 $current_loop++ if (!@keepers);
1342 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1343 # We haven't exceeded max_loops yet
1345 for my $cp ( @$all_copies ) {
1346 push(@keeper_copies, $cp) if ( grep { $_ eq ''.$cp->circ_lib } @keepers );
1348 $all_copies = [@keeper_copies];
1350 # We have, and should remove potentials and cancel the hold
1351 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1352 $_->delete for (@oldmaps);
1354 # cancel cause = un-targeted expiration
1355 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1356 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1358 # tell A/T the hold was cancelled
1359 my $fm_hold = $hold->to_fieldmapper;
1360 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1361 $ses->request('open-ils.trigger.event.autocreate',
1362 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1368 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1370 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1372 $best = choose_nearest_copy($hold, $prox_list);
1375 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1377 # hold wasn't fulfilled, record the fact
1379 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1380 action::unfulfilled_hold_list->create(
1381 { hold => ''.$hold->id,
1382 current_copy => ''.$old_best->id,
1383 circ_lib => ''.$old_best->circ_lib,
1388 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1389 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1392 action::hold_request
1394 { current_copy => $old_best->id,
1395 fulfillment_time => undef,
1396 cancel_time => undef,
1400 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1401 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1403 $hold->update( { prev_check_time => 'now' } );
1404 $log->info( "\tThere were no targetable copies for the hold" );
1407 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1408 $log->info("\tProcessing of hold ".$hold->id." complete.");
1411 { hold => $hold->id,
1412 old_target => ($old_best ? $old_best->id : undef),
1413 eligible_copies => $copy_count,
1414 target => ($best ? $best->id : undef) };
1419 $log->error("Processing of hold failed: $e");
1420 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1421 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1428 __PACKAGE__->register_method(
1429 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1431 method => 'new_hold_copy_targeter',
1434 sub reservation_targeter {
1437 my $one_reservation = shift;
1439 local $OpenILS::Application::Storage::WRITE = 1;
1444 if ($one_reservation) {
1445 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1446 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1449 # find all the reservations needing targeting
1451 booking::reservation->search_where(
1452 { current_resource => undef,
1453 cancel_time => undef,
1454 start_time => { '>' => 'now' }
1456 { order_by => 'start_time' }
1460 } catch Error with {
1462 die "Could not retrieve reservation requests:\n\n$e\n";
1466 for my $bresv (@$reservations) {
1468 #start a transaction if needed
1469 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1470 $log->debug("Cleaning up after previous transaction\n");
1471 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1473 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1474 $log->info("Processing reservation ".$bresv->id."...\n");
1476 #first, re-fetch the hold, to make sure it's not captured already
1477 $bresv->remove_from_object_index();
1478 $bresv = booking::reservation->retrieve( $bresv->id );
1480 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1482 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1483 if (DateTime->compare($end_time, DateTime->now) < 0) {
1485 # cancel cause = un-targeted expiration
1486 $bresv->update( { cancel_time => 'now' } );
1487 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1489 # tell A/T the reservation was cancelled
1490 my $fm_bresv = $bresv->to_fieldmapper;
1491 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1492 $ses->request('open-ils.trigger.event.autocreate',
1493 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1498 my $possible_resources;
1500 # find all the potential resources
1501 if (!$bresv->target_resource) {
1502 my $filter = { type => $bresv->target_resource_type };
1503 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1505 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1507 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1508 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1509 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1511 $possible_resources = $bresv->target_resource;
1514 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1515 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1518 my @good_resources = ();
1520 for my $res (@$all_resources) {
1521 unless (isTrue($res->type->catalog_item)) {
1522 push @good_resources, $res;
1526 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1529 push @good_resources, $res;
1533 if ($copy->status->id == 0 || $copy->status->id == 7) {
1534 push @good_resources, $res;
1538 if ($copy->status->id == 1) {
1539 my $circs = [ action::circulation->search_where(
1540 {target_copy => $copy->id, checkin_time => undef },
1541 { order_by => 'id DESC' }
1545 my $due_date = $circs->[0]->due_date;
1546 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1547 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1548 if (DateTime->compare($start_time, $due_date) < 0) {
1549 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1553 push @good_resources, $res;
1559 push @good_resources, $res if (isTrue($copy->status->holdable));
1562 # let 'em know we're still working
1563 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1565 # if we have no copies ...
1566 if (!@good_resources) {
1567 $log->info("\tNo resources available for targeting at all!\n");
1568 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1571 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1575 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1581 $_->owner == $bresv->pickup_lib
1585 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1586 # $all_copies is now a list of copies not at the pickup library
1588 my $best = shift @good_resources;
1589 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1592 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1596 sort { $a->[0] <=> $b->[0] }
1598 [ actor::org_unit_proximity->search_where(
1599 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1605 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1607 $best = shift @$prox_list
1611 $bresv->update( { current_resource => ''.$best->id } );
1612 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1615 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1616 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1619 { reservation => $bresv->id,
1620 current_resource => ($best ? $best->id : undef) };
1625 $log->error("Processing of bresv failed: $e");
1626 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1627 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1634 __PACKAGE__->register_method(
1635 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1637 method => 'reservation_targeter',
1642 my %cache = (titles => {}, cns => {});
1644 sub copy_hold_capture {
1649 if (!defined($cps)) {
1651 $cps = [ asset::copy->search( id => $hold->target ) ];
1652 } catch Error with {
1654 die "Could not retrieve initial volume list:\n\n$e\n";
1658 my @copies = grep { $_->holdable } @$cps;
1660 for (my $i = 0; $i < @$cps; $i++) {
1661 next unless $$cps[$i];
1663 my $cn = $cache{cns}{$copies[$i]->call_number};
1664 my $rec = $cache{titles}{$cn->record};
1665 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1666 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1667 $copies[$i] = undef if (
1669 !$self->{user_filter}->request(
1670 'open-ils.circ.permit_hold',
1671 $hold->to_fieldmapper, do {
1672 my $cp_fm = $copies[$i]->to_fieldmapper;
1673 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1674 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1675 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1678 { title => $rec->to_fieldmapper,
1679 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1680 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1683 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1686 @copies = grep { $_ } @copies;
1688 my $count = @copies;
1690 return unless ($count);
1692 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1695 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1696 for my $c (@copies) {
1697 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1699 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1705 sub choose_nearest_copy {
1707 my $prox_list = shift;
1709 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1710 next unless (ref $$prox_list[$p]);
1712 # We do this in the main body now
1713 #my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1714 next unless (@capturable);
1716 my $rand = int(rand(scalar(@capturable)));
1718 while (my ($c) = splice(@capturable, $rand, 1)) {
1719 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1720 { title => $c->call_number->record->to_fieldmapper,
1721 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1722 patron => $hold->usr->to_fieldmapper,
1723 copy => $c->to_fieldmapper,
1724 requestor => $hold->requestor->to_fieldmapper,
1725 request_lib => $hold->request_lib->to_fieldmapper,
1726 pickup_lib => $hold->pickup_lib->id,
1731 last unless(@capturable);
1732 $rand = int(rand(scalar(@capturable)));
1737 sub create_prox_list {
1742 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1745 for my $cp (@$copies) {
1746 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1747 next unless (defined($prox));
1749 my $copy_circ_lib = ''.$cp->circ_lib;
1750 # Fetch the weighting value for hold targeting, defaulting to 1
1751 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1752 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1754 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1755 $self->{target_weight}{$copy_circ_lib} ||= 1;
1757 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1758 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1759 push @{$prox_list[$prox]}, $cp;
1765 sub volume_hold_capture {
1770 if (!defined($vols)) {
1772 $vols = [ asset::call_number->search( id => $hold->target ) ];
1773 $cache{cns}{$_->id} = $_ for (@$vols);
1774 } catch Error with {
1776 die "Could not retrieve initial volume list:\n\n$e\n";
1780 my @v_ids = map { $_->id } @$vols;
1784 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1786 } catch Error with {
1788 warn "Could not retrieve copy list:\n\n$e\n";
1791 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1794 sub title_hold_capture {
1799 if (!defined($titles)) {
1801 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1802 $cache{titles}{$_->id} = $_ for (@$titles);
1803 } catch Error with {
1805 die "Could not retrieve initial title list:\n\n$e\n";
1809 my @t_ids = map { $_->id } @$titles;
1812 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1814 } catch Error with {
1816 warn "Could not retrieve volume list:\n\n$e\n";
1819 $cache{cns}{$_->id} = $_ for (@$cn_list);
1821 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1824 sub metarecord_hold_capture {
1830 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1832 } catch Error with {
1834 die "Could not retrieve initial title list:\n\n$e\n";
1838 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1840 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1842 } catch Error with {
1844 die "Could not retrieve format-pruned title list:\n\n$e\n";
1848 $cache{titles}{$_->id} = $_ for (@$titles);
1849 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);