1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage::Publisher/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::PermitHold;
10 use DateTime::Format::ISO8601;
14 return 1 if ($v == 1);
15 return 1 if ($v =~ /^t/io);
16 return 1 if ($v =~ /^y/io);
20 my $parser = DateTime::Format::ISO8601->new;
21 my $log = 'OpenSRF::Utils::Logger';
23 sub open_noncat_circs {
28 my $a = action::non_cataloged_circulation->table;
29 my $c = config::non_cataloged_type->table;
34 JOIN $c c ON (a.item_type = c.id)
35 WHERE a.circ_time + c.circ_duration > current_timestamp
39 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
41 __PACKAGE__->register_method(
42 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
45 method => 'open_noncat_circs',
49 sub ou_hold_requests {
54 my $h_table = action::hold_request->table;
55 my $c_table = asset::copy->table;
56 my $o_table = actor::org_unit->table;
61 JOIN $c_table cp ON (cp.id = h.current_copy)
62 JOIN $o_table ou ON (ou.id = cp.circ_lib)
64 AND h.capture_time IS NULL
65 AND h.cancel_time IS NULL
66 AND (h.expire_time IS NULL OR h.expire_time > NOW())
67 ORDER BY h.request_time
70 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
73 $client->respond($_) for (
76 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
80 } @{ $sth->fetchall_arrayref }
84 __PACKAGE__->register_method(
85 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
89 method => 'ou_hold_requests',
96 my $c_t = action::circulation->table;
99 $grace = " - ($grace * (fine_interval))";
107 WHERE stop_fines IS NULL
108 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 my $sth = action::circulation->db_Main->prepare_cached($sql);
114 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
118 sub complete_reshelving {
123 local $OpenILS::Application::Storage::WRITE = 1;
125 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
126 unless (interval_to_seconds( $window ));
128 my $setting = actor::org_unit_setting->table;
129 my $circ = action::circulation->table;
130 my $cp = asset::copy->table;
137 FROM (SELECT cp.id, MAX(circ.checkin_time)
139 JOIN $circ circ ON (circ.target_copy = cp.id)
140 LEFT JOIN $setting setting
141 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
142 WHERE circ.checkin_time IS NOT NULL
145 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL)
150 LEFT JOIN $setting setting
151 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
152 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
154 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
158 my $sth = action::circulation->db_Main->prepare_cached($sql);
159 $sth->execute($window, $window);
164 __PACKAGE__->register_method(
165 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
168 method => 'complete_reshelving',
171 sub mark_longoverdue {
176 local $OpenILS::Application::Storage::WRITE = 1;
178 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
179 unless (interval_to_seconds( $window ));
181 my $setting = actor::org_unit_setting->table;
182 my $circ = action::circulation->table;
186 SET stop_fines = 'LONGOVERDUE',
187 stop_fines_time = now()
191 LEFT JOIN $setting setting
192 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
193 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
194 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
198 my $sth = action::circulation->db_Main->prepare_cached($sql);
199 $sth->execute($window);
204 __PACKAGE__->register_method(
205 api_name => 'open-ils.storage.action.circulation.long_overdue',
208 method => 'mark_longoverdue',
211 sub auto_thaw_frozen_holds {
215 local $OpenILS::Application::Storage::WRITE = 1;
217 my $holds = action::hold_request->table;
219 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
221 my $sth = action::hold_request->db_Main->prepare_cached($sql);
227 __PACKAGE__->register_method(
228 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
232 method => 'auto_thaw_frozen_holds',
238 my $grace = shift || '';
240 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
245 __PACKAGE__->register_method(
246 api_name => 'open-ils.storage.action.circulation.overdue',
249 method => 'grab_overdue',
257 my $limit = int(shift()) || 10;
258 my $age = shift() || '0 seconds';
260 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
262 FROM action.hold_request h
263 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
264 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
265 WHERE hm.target_copy = ?
266 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
267 AND h.capture_time IS NULL
268 AND h.cancel_time IS NULL
269 AND (h.expire_time IS NULL OR h.expire_time > NOW())
270 AND h.frozen IS FALSE
273 h.selection_depth DESC,
278 $client->respond( $_ ) for ( @$ids );
281 __PACKAGE__->register_method(
282 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
285 method => 'nearest_hold',
288 sub next_resp_group_id {
292 # XXX This is not replication safe!!!
294 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
295 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
299 __PACKAGE__->register_method(
300 api_name => 'open-ils.storage.action.survey_response.next_group_id',
302 method => 'next_resp_group_id',
305 sub patron_circ_summary {
310 return undef unless ($id);
311 my $c_table = action::circulation->table;
312 my $b_table = money::billing->table;
314 $log->debug("Retrieving patron summary for id $id", DEBUG);
316 my $select = <<" SQL";
317 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
319 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
321 AND c.xact_finish IS NULL
323 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
324 OR c.stop_fines IS NULL
328 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
330 __PACKAGE__->register_method(
331 api_name => 'open-ils.storage.action.circulation.patron_summary',
333 method => 'patron_circ_summary',
336 #XXX Fix stored proc calls
337 sub find_local_surveys {
342 return undef unless ($ou);
343 my $s_table = action::survey->table;
345 my $select = <<" SQL";
348 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
349 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
352 my $sth = action::survey->db_Main->prepare_cached($select);
355 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
359 __PACKAGE__->register_method(
360 api_name => 'open-ils.storage.action.survey.all',
363 method => 'find_local_surveys',
366 #XXX Fix stored proc calls
367 sub find_opac_surveys {
372 return undef unless ($ou);
373 my $s_table = action::survey->table;
375 my $select = <<" SQL";
378 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
379 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
383 my $sth = action::survey->db_Main->prepare_cached($select);
386 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
390 __PACKAGE__->register_method(
391 api_name => 'open-ils.storage.action.survey.opac',
394 method => 'find_opac_surveys',
401 my $limit = shift || 10;
402 my $offset = shift || 0;
404 return undef unless ($ou);
405 my $h_table = action::hold_request->table;
406 my $a_table = asset::copy->table;
408 my $idlist = 1 if ($self->api_name =~/id_list/o);
410 my $status_filter = '';
411 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
413 my $select = <<" SQL";
416 JOIN $a_table a ON (h.current_copy = a.id)
418 AND h.capture_time IS NULL
419 AND h.cancel_time IS NULL
420 AND (h.expire_time IS NULL OR h.expire_time > NOW())
422 ORDER BY h.request_time ASC
427 my $sth = action::survey->db_Main->prepare_cached($select);
431 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
433 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
438 __PACKAGE__->register_method(
439 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
443 "Returns the hold ids for a specific library's pull list.",
444 [ [org_unit => "The library's org id", "number"],
445 [limit => 'An optional page size, defaults to 10', 'number'],
446 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
448 ['A list of holds for the stated library to pull for', 'array']
450 method => 'hold_pull_list',
452 __PACKAGE__->register_method(
453 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
457 "Returns the holds for a specific library's pull list.",
458 [ [org_unit => "The library's org id", "number"],
459 [limit => 'An optional page size, defaults to 10', 'number'],
460 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
462 ['A list of holds for the stated library to pull for', 'array']
464 method => 'hold_pull_list',
466 __PACKAGE__->register_method(
467 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
471 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
472 [ [org_unit => "The library's org id", "number"],
473 [limit => 'An optional page size, defaults to 10', 'number'],
474 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
476 ['A list of holds for the stated library to pull for', 'array']
478 method => 'hold_pull_list',
480 __PACKAGE__->register_method(
481 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
485 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
486 [ [org_unit => "The library's org id", "number"],
487 [limit => 'An optional page size, defaults to 10', 'number'],
488 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
490 ['A list of holds for the stated library to pull for', 'array']
492 method => 'hold_pull_list',
495 sub find_optional_surveys {
500 return undef unless ($ou);
501 my $s_table = action::survey->table;
503 my $select = <<" SQL";
506 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
507 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
508 AND s.required IS FALSE;
511 my $sth = action::survey->db_Main->prepare_cached($select);
514 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
518 __PACKAGE__->register_method(
519 api_name => 'open-ils.storage.action.survey.optional',
522 method => 'find_optional_surveys',
525 sub find_required_surveys {
530 return undef unless ($ou);
531 my $s_table = action::survey->table;
533 my $select = <<" SQL";
536 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
537 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
538 AND s.required IS TRUE;
541 my $sth = action::survey->db_Main->prepare_cached($select);
544 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
548 __PACKAGE__->register_method(
549 api_name => 'open-ils.storage.action.survey.required',
552 method => 'find_required_surveys',
555 sub find_usr_summary_surveys {
560 return undef unless ($ou);
561 my $s_table = action::survey->table;
563 my $select = <<" SQL";
566 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
567 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
568 AND s.usr_summary IS TRUE;
571 my $sth = action::survey->db_Main->prepare_cached($select);
574 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
578 __PACKAGE__->register_method(
579 api_name => 'open-ils.storage.action.survey.usr_summary',
582 method => 'find_usr_summary_surveys',
591 my $overbill = shift;
593 local $OpenILS::Application::Storage::WRITE = 1;
597 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
599 push @circs, overdue_circs($grace);
602 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
604 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
608 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
609 $log->debug("Cleaning up after previous transaction\n");
610 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
612 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
613 $log->info("Processing circ ".$c->id."...\n");
616 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
618 my $due = $due_dt->epoch;
621 my $fine_interval = $c->fine_interval;
622 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
623 $fine_interval = interval_to_seconds( $fine_interval );
625 if ( $fine_interval >= interval_to_seconds('1d') ) {
627 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
628 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
631 $due -= ($due % $fine_interval) + $tz_offset_s;
632 $now -= ($now % $fine_interval) + $tz_offset_s;
636 "ARG! Overdue circulation ".$c->id.
637 " for item ".$c->target_copy.
638 " (user ".$c->usr.").\n".
639 "\tItem was due on or before: ".localtime($due)."\n");
641 my @fines = money::billing->search_where(
643 billing_type => 'Overdue materials',
644 billing_ts => { '>' => $c->due_date } },
645 { order_by => 'billing_ts DESC'}
649 my $fine = $fines[$f_idx] if (@fines);
651 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
654 my $current_fine_total = 0;
655 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
659 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
660 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
662 $log->info( "Potential first billing for circ ".$c->id );
666 if (my $h = $hoo{$c->circ_lib}) {
668 $log->info( "Circ lib has an hours-of-operation entry" );
669 # find the day after the due date...
670 $due_dt = $due_dt->add( days => 1 );
672 # get the day of the week for that day...
673 my $dow = $due_dt->day_of_week_0;
674 my $dow_open = "dow_${dow}_open";
675 my $dow_close = "dow_${dow}_close";
678 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
679 # if the circ lib is closed, add a day to the grace period...
682 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
683 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
685 $due_dt = $due_dt->add( days => 1 );
686 $dow = $due_dt->day_of_week_0;
687 $dow_open = "dow_${dow}_open";
688 $dow_close = "dow_${dow}_close";
692 # and check for up to a week
693 last if ($count > 6);
700 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
701 if ($pending_fine_count < 1 + $grace) {
702 $client->respond( "\tNo fines to create. " );
703 if ($grace && $now < $due + $fine_interval * $grace) {
704 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
705 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
707 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
712 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
714 my $recuring_fine = int($c->recuring_fine * 100);
715 my $max_fine = int($c->max_fine * 100);
717 my ($latest_billing_ts, $latest_amount) = ('',0);
718 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
720 if ($current_fine_total >= $max_fine) {
721 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
723 "\tMaximum fine level of ".$c->max_fine.
724 " reached for this circulation.\n".
725 "\tNo more fines will be generated.\n" );
729 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
731 my $dow = $billing_ts->day_of_week_0();
732 my $dow_open = "dow_${dow}_open";
733 my $dow_close = "dow_${dow}_close";
735 if (my $h = $hoo{$c->circ_lib}) {
736 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
739 my $timestamptz = $billing_ts->strftime('%FT%T%z');
740 my @cl = actor::org_unit::closed_date->search_where(
741 { close_start => { '<=' => $timestamptz },
742 close_end => { '>=' => $timestamptz },
743 org_unit => $c->circ_lib }
747 $current_fine_total += $recuring_fine;
748 $latest_amount += $recuring_fine;
749 $latest_billing_ts = $timestamptz;
751 money::billing->create(
753 note => "System Generated Overdue Fine",
754 billing_type => "Overdue materials",
755 amount => sprintf('%0.2f', $recuring_fine/100),
756 billing_ts => $timestamptz,
762 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
763 if ($latest_billing_ts and $latest_amount);
765 $self->method_lookup('open-ils.storage.transaction.commit')->run;
768 'open-ils.penalty.patron_penalty.calculate',
769 { patron => $c->usr->to_fieldmapper,
777 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
778 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
779 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
780 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
784 __PACKAGE__->register_method(
785 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
788 method => 'generate_fines',
793 sub new_hold_copy_targeter {
796 my $check_expire = shift;
797 my $one_hold = shift;
799 local $OpenILS::Application::Storage::WRITE = 1;
805 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
806 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
807 } elsif ( $check_expire ) {
809 # what's the retarget time threashold?
811 $check_expire ||= '12h';
812 $check_expire = interval_to_seconds( $check_expire );
814 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
817 my $expire_threshold = sprintf(
818 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
819 $year, $mon, $mday, $hour, $min, $sec
822 # find all the holds holds needing retargeting
823 $holds = [ action::hold_request->search_where(
824 { capture_time => undef,
825 fulfillment_time => undef,
826 cancel_time => undef,
828 prev_check_time => { '<=' => $expire_threshold },
830 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
832 # find all the holds holds needing first time targeting
833 push @$holds, action::hold_request->search(
834 capture_time => undef,
835 fulfillment_time => undef,
836 prev_check_time => undef,
838 cancel_time => undef,
839 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
842 # find all the holds holds needing first time targeting ONLY
843 $holds = [ action::hold_request->search(
844 capture_time => undef,
845 fulfillment_time => undef,
846 prev_check_time => undef,
847 cancel_time => undef,
849 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
853 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
856 my @closed = actor::org_unit::closed_date->search_where(
857 { close_start => { '<=', 'now' },
858 close_end => { '>=', 'now' } }
864 for my $hold (@$holds) {
866 #start a transaction if needed
867 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
868 $log->debug("Cleaning up after previous transaction\n");
869 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
871 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
872 $log->info("Processing hold ".$hold->id."...\n");
874 #first, re-fetch the hold, to make sure it's not captured already
875 $hold->remove_from_object_index();
876 $hold = action::hold_request->retrieve( $hold->id );
878 # remove old auto-targeting maps
879 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
880 $_->delete for (@oldmaps);
882 if ($hold->expire_time) {
883 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
884 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
885 $self->method_lookup('open-ils.storage.transaction.commit')->run;
888 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
892 # find filters for MR holds
893 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
895 # find all the potential copies
896 if ($hold->hold_type eq 'M') {
899 metabib::record_descriptor
903 isTrue($_->deleted) ? () : ($_->id)
904 } metabib::metarecord->retrieve($hold->target)->source_records
906 ( $types ? (item_type => [split '', $types]) : () ),
907 ( $formats ? (item_form => [split '', $formats]) : () ),
908 ( $lang ? (item_lang => $lang) : () ),
912 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
913 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
915 for my $cn ( @{ $rtree->call_numbers } ) {
917 asset::copy->search_where(
918 { id => [map {$_->id} @{ $cn->copies }],
920 ) if ($cn && @{ $cn->copies });
923 } elsif ($hold->hold_type eq 'T') {
925 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
926 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
929 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
933 for my $cn ( @{ $rtree->call_numbers } ) {
935 asset::copy->search_where(
936 { id => [map {$_->id} @{ $cn->copies }],
938 ) if ($cn && @{ $cn->copies });
940 } elsif ($hold->hold_type eq 'V') {
942 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
943 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
946 asset::copy->search_where(
947 { id => [map {$_->id} @{ $vtree->copies }],
949 ) if ($vtree && @{ $vtree->copies });
951 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
952 my $_cp = asset::copy->retrieve($hold->target);
953 push @$all_copies, $_cp if $_cp;
957 @$all_copies = grep { isTrue($_->status->holdable) &&
958 isTrue($_->location->holdable) &&
959 isTrue($_->holdable) &&
963 # let 'em know we're still working
964 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
966 # if we have no copies ...
967 if (!ref $all_copies || !@$all_copies) {
968 $log->info("\tNo copies available for targeting at all!\n");
969 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
971 $hold->update( { prev_check_time => 'today', current_copy => undef } );
972 $self->method_lookup('open-ils.storage.transaction.commit')->run;
976 my $copy_count = @$all_copies;
978 # map the potentials, so that we can pick up checkins
979 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
980 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
982 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
985 for my $c (@$all_copies) {
987 next if ($c->id eq $hold->current_copy);
990 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
992 # target of another hold
993 next if (action::hold_request
995 { current_copy => $c->id,
996 fulfillment_time => undef,
997 cancel_time => undef,
1002 # we passed all three, keep it
1003 push @good_copies, $c if ($c);
1004 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1007 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1009 my $old_best = $hold->current_copy;
1010 $hold->update({ current_copy => undef }) if ($old_best);
1012 if (!scalar(@good_copies)) {
1013 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1014 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1015 # the old copy is still available
1016 $log->debug("\tPushing current_copy back onto the targeting list");
1017 push @good_copies, $old_best;
1019 # oops, old copy is not available
1020 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1021 $hold->update( { prev_check_time => 'today' } );
1022 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1023 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1028 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1033 $_->circ_lib == $hold->pickup_lib
1037 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1039 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1040 my $best = choose_nearest_copy($hold, $prox_list);
1041 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1044 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1045 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1047 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1049 $best = choose_nearest_copy($hold, $prox_list);
1052 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1054 # hold wasn't fulfilled, record the fact
1056 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1057 action::unfulfilled_hold_list->create(
1058 { hold => ''.$hold->id,
1059 current_copy => ''.$old_best->id,
1060 circ_lib => ''.$old_best->circ_lib,
1065 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1066 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1069 action::hold_request
1071 { current_copy => $old_best->id,
1072 fulfillment_time => undef,
1073 cancel_time => undef,
1077 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1078 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1080 $hold->update( { prev_check_time => 'now' } );
1081 $log->info( "\tThere were no targetable copies for the hold" );
1084 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1085 $log->info("\tProcessing of hold ".$hold->id." complete.");
1088 { hold => $hold->id,
1089 old_target => ($old_best ? $old_best->id : undef),
1090 eligible_copies => $copy_count,
1091 target => ($best ? $best->id : undef) };
1096 $log->error("Processing of hold failed: $e");
1097 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1098 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1105 __PACKAGE__->register_method(
1106 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1108 method => 'new_hold_copy_targeter',
1113 my %cache = (titles => {}, cns => {});
1114 sub hold_copy_targeter {
1117 my $check_expire = shift;
1118 my $one_hold = shift;
1120 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1121 $self->{user_filter}->connect;
1122 $self->{client} = $client;
1125 $check_expire ||= '12h';
1126 $check_expire = interval_to_seconds( $check_expire );
1128 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1131 my $expire_threshold = sprintf(
1132 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1133 $year, $mon, $mday, $hour, $min, $sec
1137 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1139 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1143 %cache = (titles => {}, cns => {});
1147 $holds = [ action::hold_request->search(id => $one_hold) ];
1149 $holds = [ action::hold_request->search_where(
1150 { capture_time => undef,
1151 prev_check_time => { '<=' => $expire_threshold },
1153 { order_by => 'request_time,prev_check_time' } ) ];
1154 push @$holds, action::hold_request->search_where(
1155 { capture_time => undef,
1156 prev_check_time => undef,
1158 { order_by => 'request_time' } );
1160 } catch Error with {
1162 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1165 for my $hold (@$holds) {
1167 #action::hold_request->db_Main->begin_work;
1168 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1169 $client->respond("Cleaning up after previous transaction\n");
1170 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1172 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1173 $client->respond("Processing hold ".$hold->id."...\n");
1177 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1178 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1180 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1181 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1183 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1184 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1186 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1188 unless (ref $copies || !@$copies) {
1189 $client->respond("\tNo copies available for targeting at all!\n");
1193 for my $c (@$copies) {
1194 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1195 push @good_copies, $c if ($c);
1198 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1200 my $old_best = $hold->current_copy;
1201 $hold->update({ current_copy => undef });
1203 if (!scalar(@good_copies)) {
1204 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1205 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1206 $client->respond("\tPushing current_copy back onto the targeting list\n");
1207 push @good_copies, asset::copy->retrieve( $old_best );
1209 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1215 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1216 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1218 my $best = choose_nearest_copy($hold, $prox_list);
1221 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1222 $best = choose_nearest_copy($hold, $prox_list);
1226 # hold wasn't fulfilled, record the fact
1228 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1229 action::unfulfilled_hold_list->create(
1230 { hold => ''.$hold->id,
1231 current_copy => ''.$old_best->id,
1232 circ_lib => ''.$old_best->circ_lib,
1237 $hold->update( { current_copy => ''.$best->id } );
1238 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1241 $hold->update( { prev_check_time => 'now' } );
1242 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1244 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1245 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1247 #action::hold_request->dbi_commit;
1251 $log->error("Processing of hold failed: $e");
1252 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1253 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1254 #action::hold_request->dbi_rollback;
1258 $self->{user_filter}->disconnect;
1259 $self->{user_filter}->finish;
1260 delete $$self{user_filter};
1263 __PACKAGE__->register_method(
1264 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1267 method => 'hold_copy_targeter',
1271 sub copy_hold_capture {
1276 if (!defined($cps)) {
1278 $cps = [ asset::copy->search( id => $hold->target ) ];
1279 } catch Error with {
1281 die "Could not retrieve initial volume list:\n\n$e\n";
1285 my @copies = grep { $_->holdable } @$cps;
1287 for (my $i = 0; $i < @$cps; $i++) {
1288 next unless $$cps[$i];
1290 my $cn = $cache{cns}{$copies[$i]->call_number};
1291 my $rec = $cache{titles}{$cn->record};
1292 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1293 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1294 $copies[$i] = undef if (
1296 !$self->{user_filter}->request(
1297 'open-ils.circ.permit_hold',
1298 $hold->to_fieldmapper, do {
1299 my $cp_fm = $copies[$i]->to_fieldmapper;
1300 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1301 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1302 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1305 { title => $rec->to_fieldmapper,
1306 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1307 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1310 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1313 @copies = grep { $_ } @copies;
1315 my $count = @copies;
1317 return unless ($count);
1319 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1322 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1323 for my $c (@copies) {
1324 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1326 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1332 sub choose_nearest_copy {
1334 my $prox_list = shift;
1336 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1337 next unless (ref $$prox_list[$p]);
1339 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1340 next unless (@capturable);
1342 my $rand = int(rand(scalar(@capturable)));
1343 while (my ($c) = splice(@capturable,$rand)) {
1344 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1345 { title => $c->call_number->record->to_fieldmapper,
1346 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1347 patron => $hold->usr->to_fieldmapper,
1348 copy => $c->to_fieldmapper,
1349 requestor => $hold->requestor->to_fieldmapper,
1350 request_lib => $hold->request_lib->to_fieldmapper,
1351 pickup_lib => $hold->pickup_lib->id,
1355 last unless(@capturable);
1356 $rand = int(rand(scalar(@capturable)));
1361 sub create_prox_list {
1367 for my $cp (@$copies) {
1368 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1369 next unless (defined($prox));
1370 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1371 push @{$prox_list[$prox]}, $cp;
1376 sub volume_hold_capture {
1381 if (!defined($vols)) {
1383 $vols = [ asset::call_number->search( id => $hold->target ) ];
1384 $cache{cns}{$_->id} = $_ for (@$vols);
1385 } catch Error with {
1387 die "Could not retrieve initial volume list:\n\n$e\n";
1391 my @v_ids = map { $_->id } @$vols;
1395 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1397 } catch Error with {
1399 warn "Could not retrieve copy list:\n\n$e\n";
1402 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1405 sub title_hold_capture {
1410 if (!defined($titles)) {
1412 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1413 $cache{titles}{$_->id} = $_ for (@$titles);
1414 } catch Error with {
1416 die "Could not retrieve initial title list:\n\n$e\n";
1420 my @t_ids = map { $_->id } @$titles;
1423 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1425 } catch Error with {
1427 warn "Could not retrieve volume list:\n\n$e\n";
1430 $cache{cns}{$_->id} = $_ for (@$cn_list);
1432 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1435 sub metarecord_hold_capture {
1441 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1443 } catch Error with {
1445 die "Could not retrieve initial title list:\n\n$e\n";
1449 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1451 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1453 } catch Error with {
1455 die "Could not retrieve format-pruned title list:\n\n$e\n";
1459 $cache{titles}{$_->id} = $_ for (@$titles);
1460 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);