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;
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';
287 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
289 FROM action.hold_request h
290 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
291 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
292 WHERE hm.target_copy = ?
293 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
294 AND h.capture_time IS NULL
295 AND h.cancel_time IS NULL
296 AND (h.expire_time IS NULL OR h.expire_time > NOW())
297 AND h.frozen IS FALSE
300 CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
301 h.selection_depth DESC,
306 $client->respond( $_ ) for ( @$ids );
309 __PACKAGE__->register_method(
310 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
313 method => 'nearest_hold',
316 sub next_resp_group_id {
320 # XXX This is not replication safe!!!
322 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
323 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
327 __PACKAGE__->register_method(
328 api_name => 'open-ils.storage.action.survey_response.next_group_id',
330 method => 'next_resp_group_id',
333 sub patron_circ_summary {
338 return undef unless ($id);
339 my $c_table = action::circulation->table;
340 my $b_table = money::billing->table;
342 $log->debug("Retrieving patron summary for id $id", DEBUG);
344 my $select = <<" SQL";
345 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
347 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
349 AND c.xact_finish IS NULL
351 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
352 OR c.stop_fines IS NULL
356 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
358 __PACKAGE__->register_method(
359 api_name => 'open-ils.storage.action.circulation.patron_summary',
361 method => 'patron_circ_summary',
364 #XXX Fix stored proc calls
365 sub find_local_surveys {
370 return undef unless ($ou);
371 my $s_table = action::survey->table;
373 my $select = <<" SQL";
376 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
377 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
380 my $sth = action::survey->db_Main->prepare_cached($select);
383 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
387 __PACKAGE__->register_method(
388 api_name => 'open-ils.storage.action.survey.all',
391 method => 'find_local_surveys',
394 #XXX Fix stored proc calls
395 sub find_opac_surveys {
400 return undef unless ($ou);
401 my $s_table = action::survey->table;
403 my $select = <<" SQL";
406 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
407 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
411 my $sth = action::survey->db_Main->prepare_cached($select);
414 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
418 __PACKAGE__->register_method(
419 api_name => 'open-ils.storage.action.survey.opac',
422 method => 'find_opac_surveys',
429 my $limit = shift || 10;
430 my $offset = shift || 0;
432 return undef unless ($ou);
433 my $h_table = action::hold_request->table;
434 my $a_table = asset::copy->table;
435 my $ord_table = asset::copy_location_order->table;
437 my $idlist = 1 if ($self->api_name =~/id_list/o);
438 my $count = 1 if ($self->api_name =~/count$/o);
440 my $status_filter = '';
441 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
443 my $select = <<" SQL";
446 JOIN $a_table a ON (h.current_copy = a.id)
447 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
449 AND h.capture_time IS NULL
450 AND h.cancel_time IS NULL
451 AND (h.expire_time IS NULL OR h.expire_time > NOW())
453 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
462 JOIN $a_table a ON (h.current_copy = a.id)
464 AND h.capture_time IS NULL
465 AND h.cancel_time IS NULL
466 AND (h.expire_time IS NULL OR h.expire_time > NOW())
471 my $sth = action::survey->db_Main->prepare_cached($select);
475 $client->respond( $sth->fetchall_arrayref()->[0][0] );
477 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
479 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
484 __PACKAGE__->register_method(
485 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
489 "Returns a count of holds for a specific library's pull list.",
490 [ [org_unit => "The library's org id", "number"] ],
491 ['A count of holds for the stated library to pull ', 'number']
493 method => 'hold_pull_list',
495 __PACKAGE__->register_method(
496 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
500 "Returns a status filtered count of holds for a specific library's pull list.",
501 [ [org_unit => "The library's org id", "number"] ],
502 ['A status filtered count of holds for the stated library to pull ', 'number']
504 method => 'hold_pull_list',
506 __PACKAGE__->register_method(
507 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
511 "Returns the hold ids for a specific library's pull list.",
512 [ [org_unit => "The library's org id", "number"],
513 [limit => 'An optional page size, defaults to 10', 'number'],
514 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
516 ['A list of holds for the stated library to pull for', 'array']
518 method => 'hold_pull_list',
520 __PACKAGE__->register_method(
521 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
525 "Returns the holds for a specific library's pull list.",
526 [ [org_unit => "The library's org id", "number"],
527 [limit => 'An optional page size, defaults to 10', 'number'],
528 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
530 ['A list of holds for the stated library to pull for', 'array']
532 method => 'hold_pull_list',
534 __PACKAGE__->register_method(
535 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
539 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
540 [ [org_unit => "The library's org id", "number"],
541 [limit => 'An optional page size, defaults to 10', 'number'],
542 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
544 ['A list of holds for the stated library to pull for', 'array']
546 method => 'hold_pull_list',
548 __PACKAGE__->register_method(
549 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
553 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
554 [ [org_unit => "The library's org id", "number"],
555 [limit => 'An optional page size, defaults to 10', 'number'],
556 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
558 ['A list of holds for the stated library to pull for', 'array']
560 method => 'hold_pull_list',
563 sub find_optional_surveys {
568 return undef unless ($ou);
569 my $s_table = action::survey->table;
571 my $select = <<" SQL";
574 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
575 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
576 AND s.required IS FALSE;
579 my $sth = action::survey->db_Main->prepare_cached($select);
582 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
586 __PACKAGE__->register_method(
587 api_name => 'open-ils.storage.action.survey.optional',
590 method => 'find_optional_surveys',
593 sub find_required_surveys {
598 return undef unless ($ou);
599 my $s_table = action::survey->table;
601 my $select = <<" SQL";
604 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
605 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
606 AND s.required IS TRUE;
609 my $sth = action::survey->db_Main->prepare_cached($select);
612 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
616 __PACKAGE__->register_method(
617 api_name => 'open-ils.storage.action.survey.required',
620 method => 'find_required_surveys',
623 sub find_usr_summary_surveys {
628 return undef unless ($ou);
629 my $s_table = action::survey->table;
631 my $select = <<" SQL";
634 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
635 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
636 AND s.usr_summary IS TRUE;
639 my $sth = action::survey->db_Main->prepare_cached($select);
642 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
646 __PACKAGE__->register_method(
647 api_name => 'open-ils.storage.action.survey.usr_summary',
650 method => 'find_usr_summary_surveys',
659 my $overbill = shift;
661 local $OpenILS::Application::Storage::WRITE = 1;
666 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
667 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
669 push @circs, overdue_circs($grace);
672 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
674 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
678 $ctype =~ s/^.*([^:]+)$/$1/o;
680 my $due_date_method = 'due_date';
681 my $target_copy_method = 'target_copy';
682 my $circ_lib_method = 'circ_lib';
683 my $recurring_fine_method = 'recurring_fine';
684 my $is_reservation = 0;
685 if ($ctype eq 'reservation') {
687 $due_date_method = 'end_time';
688 $target_copy_method = 'current_resource';
689 $circ_lib_method = 'pickup_lib';
690 $recurring_fine_method = 'fine_amount';
691 next unless ($c->fine_interval);
695 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
696 $log->debug("Cleaning up after previous transaction\n");
697 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
699 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
700 $log->info("Processing circ ".$c->id."...\n");
703 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
705 my $due = $due_dt->epoch;
708 my $fine_interval = $c->fine_interval;
709 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
710 $fine_interval = interval_to_seconds( $fine_interval );
712 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
714 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
715 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
718 $due -= ($due % $fine_interval) + $tz_offset_s;
719 $now -= ($now % $fine_interval) + $tz_offset_s;
723 "ARG! Overdue $ctype ".$c->id.
724 " for item ".$c->$target_copy_method.
725 " (user ".$c->usr.").\n".
726 "\tItem was due on or before: ".localtime($due)."\n");
728 my @fines = money::billing->search_where(
731 billing_ts => { '>' => $c->$due_date_method } },
732 { order_by => 'billing_ts DESC'}
736 my $fine = $fines[$f_idx] if (@fines);
738 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
741 my $current_fine_total = 0;
742 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
746 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
747 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
749 $log->info( "Potential first billing for circ ".$c->id );
753 if (my $h = $hoo{$c->$circ_lib_method}) {
755 $log->info( "Circ lib has an hours-of-operation entry" );
756 # find the day after the due date...
757 $due_dt = $due_dt->add( days => 1 );
759 # get the day of the week for that day...
760 my $dow = $due_dt->day_of_week_0;
761 my $dow_open = "dow_${dow}_open";
762 my $dow_close = "dow_${dow}_close";
765 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
766 # if the circ lib is closed, add a day to the grace period...
769 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
770 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
772 $due_dt = $due_dt->add( days => 1 );
773 $dow = $due_dt->day_of_week_0;
774 $dow_open = "dow_${dow}_open";
775 $dow_close = "dow_${dow}_close";
779 # and check for up to a week
780 last if ($count > 6);
786 next if ($last_fine > $now);
787 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
789 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
790 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
792 if ( $last_fine == $due # we have no fines yet
793 && $grace # and we have a grace period
794 && $pending_fine_count <= $grace # and we seem to be inside that period
795 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
797 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
798 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
802 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
803 next unless ($pending_fine_count);
805 my $recurring_fine = int($c->$recurring_fine_method * 100);
806 my $max_fine = int($c->max_fine * 100);
808 my ($latest_billing_ts, $latest_amount) = ('',0);
809 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
811 if ($current_fine_total >= $max_fine) {
812 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
814 "\tMaximum fine level of ".$c->max_fine.
815 " reached for this $ctype.\n".
816 "\tNo more fines will be generated.\n" );
820 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
821 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill, time_zone => 'local' );
823 my $dow = $billing_ts->day_of_week_0();
824 my $dow_open = "dow_${dow}_open";
825 my $dow_close = "dow_${dow}_close";
827 if (my $h = $hoo{$c->$circ_lib_method}) {
828 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
831 my $timestamptz = $billing_ts->strftime('%FT%T%z');
832 my @cl = actor::org_unit::closed_date->search_where(
833 { close_start => { '<=' => $timestamptz },
834 close_end => { '>=' => $timestamptz },
835 org_unit => $c->$circ_lib_method }
839 $current_fine_total += $recurring_fine;
840 $latest_amount += $recurring_fine;
841 $latest_billing_ts = $timestamptz;
843 money::billing->create(
845 note => "System Generated Overdue Fine",
846 billing_type => "Overdue materials",
848 amount => sprintf('%0.2f', $recurring_fine/100),
849 billing_ts => $timestamptz,
855 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
856 if ($latest_billing_ts and $latest_amount);
858 $self->method_lookup('open-ils.storage.transaction.commit')->run;
862 # Caluclate penalties inline
863 OpenILS::Utils::Penalty->calculate_penalties(
864 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
868 # Calculate penalties with an aysnc call to the penalty server. This approach
869 # may lead to duplicate penalties since multiple penalty processes for a
870 # given user may be running at the same time. Leave this here for reference
871 # in case we later find that asyc calls are needed in some environments.
873 'open-ils.penalty.patron_penalty.calculate',
874 { patronid => ''.$c->usr,
875 context_org => ''.$c->$circ_lib_method,
884 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
885 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
886 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
887 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
891 __PACKAGE__->register_method(
892 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
895 method => 'generate_fines',
900 sub new_hold_copy_targeter {
903 my $check_expire = shift;
904 my $one_hold = shift;
906 local $OpenILS::Application::Storage::WRITE = 1;
908 $self->{target_weight} = {};
914 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
915 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
916 } elsif ( $check_expire ) {
918 # what's the retarget time threashold?
920 $check_expire ||= '12h';
921 $check_expire = interval_to_seconds( $check_expire );
923 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
926 my $expire_threshold = sprintf(
927 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
928 $year, $mon, $mday, $hour, $min, $sec
931 # find all the holds holds needing retargeting
932 $holds = [ action::hold_request->search_where(
933 { capture_time => undef,
934 fulfillment_time => undef,
935 cancel_time => undef,
937 prev_check_time => { '<=' => $expire_threshold },
939 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
941 # find all the holds holds needing first time targeting
942 push @$holds, action::hold_request->search(
943 capture_time => undef,
944 fulfillment_time => undef,
945 prev_check_time => undef,
947 cancel_time => undef,
948 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
951 # find all the holds holds needing first time targeting ONLY
952 $holds = [ action::hold_request->search(
953 capture_time => undef,
954 fulfillment_time => undef,
955 prev_check_time => undef,
956 cancel_time => undef,
958 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
962 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
965 my @closed = actor::org_unit::closed_date->search_where(
966 { close_start => { '<=', 'now' },
967 close_end => { '>=', 'now' } }
972 # $check_expire, if it exists, was already converted to seconds
973 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
977 my $next_check_time = sprintf(
978 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
979 $year, $mon, $mday, $hour, $min, $sec
983 my @closed_at_next = actor::org_unit::closed_date->search_where(
984 { close_start => { '<=', $next_check_time },
985 close_end => { '>=', $next_check_time } }
989 for my $c_at_n (@closed_at_next) {
990 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
991 push @new_closed, $c_at_n;
994 @closed = @new_closed;
998 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1000 for my $hold (@$holds) {
1002 #start a transaction if needed
1003 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1004 $log->debug("Cleaning up after previous transaction\n");
1005 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1007 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1008 $log->info("Processing hold ".$hold->id."...\n");
1010 #first, re-fetch the hold, to make sure it's not captured already
1011 $hold->remove_from_object_index();
1012 $hold = action::hold_request->retrieve( $hold->id );
1014 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1016 # remove old auto-targeting maps
1017 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1018 $_->delete for (@oldmaps);
1020 if ($hold->expire_time) {
1021 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1022 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1024 # cancel cause = un-targeted expiration
1025 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1026 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1028 # tell A/T the hold was cancelled
1029 my $fm_hold = $hold->to_fieldmapper;
1030 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1031 $ses->request('open-ils.trigger.event.autocreate',
1032 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1038 my $all_copies = [];
1040 # find filters for MR holds
1041 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1043 # find all the potential copies
1044 if ($hold->hold_type eq 'M') {
1047 metabib::record_descriptor
1051 isTrue($_->deleted) ? () : ($_->id)
1052 } metabib::metarecord->retrieve($hold->target)->source_records
1054 ( $types ? (item_type => [split '', $types]) : () ),
1055 ( $formats ? (item_form => [split '', $formats]) : () ),
1056 ( $lang ? (item_lang => $lang) : () ),
1060 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1061 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1063 for my $cn ( @{ $rtree->call_numbers } ) {
1065 asset::copy->search_where(
1066 { id => [map {$_->id} @{ $cn->copies }],
1068 ) if ($cn && @{ $cn->copies });
1071 } elsif ($hold->hold_type eq 'T') {
1073 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1074 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1077 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1081 for my $cn ( @{ $rtree->call_numbers } ) {
1083 asset::copy->search_where(
1084 { id => [map {$_->id} @{ $cn->copies }],
1086 ) if ($cn && @{ $cn->copies });
1088 } elsif ($hold->hold_type eq 'V') {
1090 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1091 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1094 asset::copy->search_where(
1095 { id => [map {$_->id} @{ $vtree->copies }],
1097 ) if ($vtree && @{ $vtree->copies });
1099 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1100 my $_cp = asset::copy->retrieve($hold->target);
1101 push @$all_copies, $_cp if $_cp;
1105 @$all_copies = grep { isTrue($_->status->holdable) &&
1106 isTrue($_->location->holdable) &&
1107 isTrue($_->holdable) &&
1108 !isTrue($_->deleted) &&
1109 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1112 # let 'em know we're still working
1113 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1115 # if we have no copies ...
1116 if (!ref $all_copies || !@$all_copies) {
1117 $log->info("\tNo copies available for targeting at all!\n");
1118 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1120 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1121 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1125 my $copy_count = @$all_copies;
1127 # map the potentials, so that we can pick up checkins
1128 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1129 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1130 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1131 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1133 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1136 for my $c (@$all_copies) {
1138 next if ($c->id eq $hold->current_copy);
1140 # circ lib is closed
1141 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1143 # target of another hold
1144 next if (action::hold_request
1146 { current_copy => $c->id,
1147 fulfillment_time => undef,
1148 cancel_time => undef,
1153 # we passed all three, keep it
1154 push @good_copies, $c if ($c);
1155 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1158 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1160 my $old_best = $hold->current_copy;
1161 $hold->update({ current_copy => undef }) if ($old_best);
1163 if (!scalar(@good_copies)) {
1164 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1165 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1166 # the old copy is still available
1167 $log->debug("\tPushing current_copy back onto the targeting list");
1168 push @good_copies, $old_best;
1170 # oops, old copy is not available
1171 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1172 $hold->update( { prev_check_time => 'today' } );
1173 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1174 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1183 $_->circ_lib == $hold->pickup_lib
1187 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1188 # $all_copies is now a list of copies not at the pickup library
1190 my $best = choose_nearest_copy($hold, $prox_list);
1191 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1194 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1196 my $max_loops = $actor->request(
1197 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1200 if (defined($max_loops)) {
1201 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1202 my $circ_lib_list = [keys %circ_lib_map];
1204 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1206 # Grab the "biggest" loop for this hold so far
1207 my $current_loop = $cstore->request(
1208 'open-ils.cstore.json_query',
1210 select => { aufhmxl => ['max'] },
1212 where => { hold => $hold->id}
1216 $current_loop = $current_loop->{max} if ($current_loop);
1217 $current_loop ||= 1;
1219 my $exclude_list = $cstore->request(
1220 'open-ils.cstore.json_query.atomic',
1222 select => { aufhol => [circ_lib] },
1224 where => { hold => $hold->id}
1229 if ($exclude_list && @$exclude_list) {
1230 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1231 # check to see if we've used up every library in the potentials list
1232 for my $l ( @$circ_lib_list ) {
1234 for my $ex ( @$exclude_list ) {
1240 push(@keepers, $l) if ($keep);
1243 @keepers = @$circ_lib_list;
1246 $current_loop++ if (!@keepers);
1248 if ($max_loops && $max_loops <= $current_loop) {
1249 # We haven't exceeded max_loops yet
1251 for my $cp ( @$all_copies ) {
1252 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1255 # We have, and should remove potentials and cancel the hold
1256 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1257 $_->delete for (@oldmaps);
1259 # cancel cause = un-targeted expiration
1260 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1261 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1263 # tell A/T the hold was cancelled
1264 my $fm_hold = $hold->to_fieldmapper;
1265 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1266 $ses->request('open-ils.trigger.event.autocreate',
1267 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1273 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1275 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1277 $best = choose_nearest_copy($hold, $prox_list);
1280 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1282 # hold wasn't fulfilled, record the fact
1284 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1285 action::unfulfilled_hold_list->create(
1286 { hold => ''.$hold->id,
1287 current_copy => ''.$old_best->id,
1288 circ_lib => ''.$old_best->circ_lib,
1293 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1294 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1297 action::hold_request
1299 { current_copy => $old_best->id,
1300 fulfillment_time => undef,
1301 cancel_time => undef,
1305 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1306 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1308 $hold->update( { prev_check_time => 'now' } );
1309 $log->info( "\tThere were no targetable copies for the hold" );
1312 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1313 $log->info("\tProcessing of hold ".$hold->id." complete.");
1316 { hold => $hold->id,
1317 old_target => ($old_best ? $old_best->id : undef),
1318 eligible_copies => $copy_count,
1319 target => ($best ? $best->id : undef) };
1324 $log->error("Processing of hold failed: $e");
1325 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1326 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1333 __PACKAGE__->register_method(
1334 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1336 method => 'new_hold_copy_targeter',
1339 sub reservation_targeter {
1342 my $one_reservation = shift;
1344 local $OpenILS::Application::Storage::WRITE = 1;
1349 if ($one_reservation) {
1350 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1351 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1354 # find all the reservations needing targeting
1356 booking::reservation->search_where(
1357 { current_resource => undef,
1358 cancel_time => undef,
1359 start_time => { '>' => 'now' }
1361 { order_by => 'start_time' }
1365 } catch Error with {
1367 die "Could not retrieve reservation requests:\n\n$e\n";
1371 for my $bresv (@$reservations) {
1373 #start a transaction if needed
1374 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1375 $log->debug("Cleaning up after previous transaction\n");
1376 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1378 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1379 $log->info("Processing reservation ".$bresv->id."...\n");
1381 #first, re-fetch the hold, to make sure it's not captured already
1382 $bresv->remove_from_object_index();
1383 $bresv = booking::reservation->retrieve( $bresv->id );
1385 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1387 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1388 if (DateTime->compare($end_time, DateTime->now) < 0) {
1390 # cancel cause = un-targeted expiration
1391 $bresv->update( { cancel_time => 'now' } );
1392 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1394 # tell A/T the reservation was cancelled
1395 my $fm_bresv = $bresv->to_fieldmapper;
1396 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1397 $ses->request('open-ils.trigger.event.autocreate',
1398 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1403 my $possible_resources;
1405 # find all the potential resources
1406 if (!$bresv->target_resource) {
1407 my $filter = { type => $bresv->target_resource_type };
1408 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1410 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1412 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1413 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1414 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1416 $possible_resources = $bresv->target_resource;
1419 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1420 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1423 my @good_resources = ();
1424 for my $res (@$all_resources) {
1425 unless (isTrue($res->type->catalog_item)) {
1426 push @good_resources, $res;
1430 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1433 push @good_resources, $res;
1437 if ($copy->status->id == 0 || $copy->status->id == 7) {
1438 push @good_resources, $res;
1442 if ($copy->status->id == 1) {
1443 my $circs = action::circulation->search_where(
1444 {target_copy => $copy->id, checkin_time => undef },
1445 { order_by => 'id DESC' }
1449 my $due_date = $circs->[0]->due_date;
1450 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1451 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1452 next if (DateTime->compare($start_time, $due_date) < 0);
1453 push @good_resources, $res;
1459 push @good_resources, $res if (isTrue($copy->status->holdable));
1462 # let 'em know we're still working
1463 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1465 # if we have no copies ...
1466 if (!@good_resources) {
1467 $log->info("\tNo resources available for targeting at all!\n");
1468 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1470 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1474 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1480 $_->owner == $bresv->pickup_lib
1484 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1485 # $all_copies is now a list of copies not at the pickup library
1487 my $best = shift @good_resources;
1488 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1491 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1495 sort { $a->[0] <=> $b->[0] }
1497 [ actor::org_unit_proximity->search_where(
1498 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1504 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1506 $best = shift @$prox_list
1510 $bresv->update( { current_resource => ''.$best->id } );
1511 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1514 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1515 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1518 { reservation => $bresv->id,
1519 current_resource => ($best ? $best->id : undef) };
1524 $log->error("Processing of bresv failed: $e");
1525 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1526 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1533 __PACKAGE__->register_method(
1534 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1536 method => 'reservation_targeter',
1541 my %cache = (titles => {}, cns => {});
1542 sub hold_copy_targeter {
1545 my $check_expire = shift;
1546 my $one_hold = shift;
1548 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1549 $self->{user_filter}->connect;
1550 $self->{client} = $client;
1553 $check_expire ||= '12h';
1554 $check_expire = interval_to_seconds( $check_expire );
1556 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1559 my $expire_threshold = sprintf(
1560 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1561 $year, $mon, $mday, $hour, $min, $sec
1565 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1567 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1571 %cache = (titles => {}, cns => {});
1575 $holds = [ action::hold_request->search(id => $one_hold) ];
1577 $holds = [ action::hold_request->search_where(
1578 { capture_time => undef,
1579 prev_check_time => { '<=' => $expire_threshold },
1581 { order_by => 'request_time,prev_check_time' } ) ];
1582 push @$holds, action::hold_request->search_where(
1583 { capture_time => undef,
1584 prev_check_time => undef,
1586 { order_by => 'request_time' } );
1588 } catch Error with {
1590 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1593 for my $hold (@$holds) {
1595 #action::hold_request->db_Main->begin_work;
1596 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1597 $client->respond("Cleaning up after previous transaction\n");
1598 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1600 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1601 $client->respond("Processing hold ".$hold->id."...\n");
1605 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1606 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1608 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1609 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1611 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1612 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1614 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1616 unless (ref $copies || !@$copies) {
1617 $client->respond("\tNo copies available for targeting at all!\n");
1621 for my $c (@$copies) {
1622 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1623 push @good_copies, $c if ($c);
1626 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1628 my $old_best = $hold->current_copy;
1629 $hold->update({ current_copy => undef });
1631 if (!scalar(@good_copies)) {
1632 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1633 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1634 $client->respond("\tPushing current_copy back onto the targeting list\n");
1635 push @good_copies, asset::copy->retrieve( $old_best );
1637 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1643 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1644 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1646 my $best = choose_nearest_copy($hold, $prox_list);
1649 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1650 $best = choose_nearest_copy($hold, $prox_list);
1654 # hold wasn't fulfilled, record the fact
1656 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1657 action::unfulfilled_hold_list->create(
1658 { hold => ''.$hold->id,
1659 current_copy => ''.$old_best->id,
1660 circ_lib => ''.$old_best->circ_lib,
1665 $hold->update( { current_copy => ''.$best->id } );
1666 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1669 $hold->update( { prev_check_time => 'now' } );
1670 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1672 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1673 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1675 #action::hold_request->dbi_commit;
1679 $log->error("Processing of hold failed: $e");
1680 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1681 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1682 #action::hold_request->dbi_rollback;
1686 $self->{user_filter}->disconnect;
1687 $self->{user_filter}->finish;
1688 delete $$self{user_filter};
1691 #__PACKAGE__->register_method(
1692 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1695 # method => 'hold_copy_targeter',
1699 sub copy_hold_capture {
1704 if (!defined($cps)) {
1706 $cps = [ asset::copy->search( id => $hold->target ) ];
1707 } catch Error with {
1709 die "Could not retrieve initial volume list:\n\n$e\n";
1713 my @copies = grep { $_->holdable } @$cps;
1715 for (my $i = 0; $i < @$cps; $i++) {
1716 next unless $$cps[$i];
1718 my $cn = $cache{cns}{$copies[$i]->call_number};
1719 my $rec = $cache{titles}{$cn->record};
1720 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1721 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1722 $copies[$i] = undef if (
1724 !$self->{user_filter}->request(
1725 'open-ils.circ.permit_hold',
1726 $hold->to_fieldmapper, do {
1727 my $cp_fm = $copies[$i]->to_fieldmapper;
1728 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1729 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1730 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1733 { title => $rec->to_fieldmapper,
1734 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1735 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1738 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1741 @copies = grep { $_ } @copies;
1743 my $count = @copies;
1745 return unless ($count);
1747 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1750 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1751 for my $c (@copies) {
1752 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1754 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1760 sub choose_nearest_copy {
1762 my $prox_list = shift;
1764 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1765 next unless (ref $$prox_list[$p]);
1767 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1768 next unless (@capturable);
1770 my $rand = int(rand(scalar(@capturable)));
1771 while (my ($c) = splice(@capturable,$rand)) {
1772 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1773 { title => $c->call_number->record->to_fieldmapper,
1774 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1775 patron => $hold->usr->to_fieldmapper,
1776 copy => $c->to_fieldmapper,
1777 requestor => $hold->requestor->to_fieldmapper,
1778 request_lib => $hold->request_lib->to_fieldmapper,
1779 pickup_lib => $hold->pickup_lib->id,
1783 last unless(@capturable);
1784 $rand = int(rand(scalar(@capturable)));
1789 sub create_prox_list {
1794 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1797 for my $cp (@$copies) {
1798 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1799 next unless (defined($prox));
1801 # Fetch the weighting value for hold targeting, defaulting to 1
1802 $self->{target_weight}{$lib} ||= $actor->request(
1803 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1806 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1807 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1808 push @{$prox_list[$prox]}, $cp;
1814 sub volume_hold_capture {
1819 if (!defined($vols)) {
1821 $vols = [ asset::call_number->search( id => $hold->target ) ];
1822 $cache{cns}{$_->id} = $_ for (@$vols);
1823 } catch Error with {
1825 die "Could not retrieve initial volume list:\n\n$e\n";
1829 my @v_ids = map { $_->id } @$vols;
1833 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1835 } catch Error with {
1837 warn "Could not retrieve copy list:\n\n$e\n";
1840 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1843 sub title_hold_capture {
1848 if (!defined($titles)) {
1850 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1851 $cache{titles}{$_->id} = $_ for (@$titles);
1852 } catch Error with {
1854 die "Could not retrieve initial title list:\n\n$e\n";
1858 my @t_ids = map { $_->id } @$titles;
1861 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1863 } catch Error with {
1865 warn "Could not retrieve volume list:\n\n$e\n";
1868 $cache{cns}{$_->id} = $_ for (@$cn_list);
1870 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1873 sub metarecord_hold_capture {
1879 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1881 } catch Error with {
1883 die "Could not retrieve initial title list:\n\n$e\n";
1887 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1889 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1891 } catch Error with {
1893 die "Could not retrieve format-pruned title list:\n\n$e\n";
1897 $cache{titles}{$_->id} = $_ for (@$titles);
1898 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);