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;
98 $grace = " - ($grace * (fine_interval))" if ($grace);
103 WHERE stop_fines IS NULL
104 AND due_date < ( CURRENT_TIMESTAMP $grace)
107 my $sth = action::circulation->db_Main->prepare_cached($sql);
110 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
114 sub complete_reshelving {
119 local $OpenILS::Application::Storage::WRITE = 1;
121 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
122 unless (interval_to_seconds( $window ));
124 my $setting = actor::org_unit_setting->table;
125 my $circ = action::circulation->table;
126 my $cp = asset::copy->table;
133 FROM (SELECT cp.id, MAX(circ.checkin_time)
135 JOIN $circ circ ON (circ.target_copy = cp.id)
136 LEFT JOIN $setting setting
137 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
138 WHERE circ.checkin_time IS NOT NULL
141 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
146 LEFT JOIN $setting setting
147 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
148 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
150 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
154 my $sth = action::circulation->db_Main->prepare_cached($sql);
155 $sth->execute($window, $window);
160 __PACKAGE__->register_method(
161 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
165 method => 'complete_reshelving',
168 sub auto_thaw_frozen_holds {
172 local $OpenILS::Application::Storage::WRITE = 1;
174 my $holds = action::hold_request->table;
176 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
178 my $sth = action::hold_request->db_Main->prepare_cached($sql);
184 __PACKAGE__->register_method(
185 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
189 method => 'auto_thaw_frozen_holds',
195 my $grace = shift || '';
197 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
202 __PACKAGE__->register_method(
203 api_name => 'open-ils.storage.action.circulation.overdue',
206 method => 'grab_overdue',
214 my $limit = int(shift()) || 10;
215 my $age = shift() || '0 seconds';
217 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
219 FROM action.hold_request h
220 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
221 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
222 WHERE hm.target_copy = ?
223 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
224 AND h.capture_time IS NULL
225 AND h.cancel_time IS NULL
226 AND (h.expire_time IS NULL OR h.expire_time > NOW())
227 AND h.frozen IS FALSE
230 h.selection_depth DESC,
235 $client->respond( $_ ) for ( @$ids );
238 __PACKAGE__->register_method(
239 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
242 method => 'nearest_hold',
245 sub next_resp_group_id {
249 # XXX This is not replication safe!!!
251 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
252 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
256 __PACKAGE__->register_method(
257 api_name => 'open-ils.storage.action.survey_response.next_group_id',
259 method => 'next_resp_group_id',
262 sub patron_circ_summary {
267 return undef unless ($id);
268 my $c_table = action::circulation->table;
269 my $b_table = money::billing->table;
271 $log->debug("Retrieving patron summary for id $id", DEBUG);
273 my $select = <<" SQL";
274 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
276 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
278 AND c.xact_finish IS NULL
280 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
281 OR c.stop_fines IS NULL
285 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
287 __PACKAGE__->register_method(
288 api_name => 'open-ils.storage.action.circulation.patron_summary',
290 method => 'patron_circ_summary',
293 #XXX Fix stored proc calls
294 sub find_local_surveys {
299 return undef unless ($ou);
300 my $s_table = action::survey->table;
302 my $select = <<" SQL";
305 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
306 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
309 my $sth = action::survey->db_Main->prepare_cached($select);
312 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
316 __PACKAGE__->register_method(
317 api_name => 'open-ils.storage.action.survey.all',
320 method => 'find_local_surveys',
323 #XXX Fix stored proc calls
324 sub find_opac_surveys {
329 return undef unless ($ou);
330 my $s_table = action::survey->table;
332 my $select = <<" SQL";
335 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
336 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
340 my $sth = action::survey->db_Main->prepare_cached($select);
343 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
347 __PACKAGE__->register_method(
348 api_name => 'open-ils.storage.action.survey.opac',
351 method => 'find_opac_surveys',
358 my $limit = shift || 10;
359 my $offset = shift || 0;
361 return undef unless ($ou);
362 my $h_table = action::hold_request->table;
363 my $a_table = asset::copy->table;
365 my $idlist = 1 if ($self->api_name =~/id_list/o);
367 my $status_filter = '';
368 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
370 my $select = <<" SQL";
373 JOIN $a_table a ON (h.current_copy = a.id)
375 AND h.capture_time IS NULL
376 AND h.cancel_time IS NULL
377 AND (h.expire_time IS NULL OR h.expire_time > NOW())
379 ORDER BY h.request_time ASC
384 my $sth = action::survey->db_Main->prepare_cached($select);
388 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
390 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
395 __PACKAGE__->register_method(
396 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
400 "Returns the hold ids for a specific library's pull list.",
401 [ [org_unit => "The library's org id", "number"],
402 [limit => 'An optional page size, defaults to 10', 'number'],
403 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
405 ['A list of holds for the stated library to pull for', 'array']
407 method => 'hold_pull_list',
409 __PACKAGE__->register_method(
410 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
414 "Returns the holds for a specific library's pull list.",
415 [ [org_unit => "The library's org id", "number"],
416 [limit => 'An optional page size, defaults to 10', 'number'],
417 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
419 ['A list of holds for the stated library to pull for', 'array']
421 method => 'hold_pull_list',
423 __PACKAGE__->register_method(
424 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
428 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
429 [ [org_unit => "The library's org id", "number"],
430 [limit => 'An optional page size, defaults to 10', 'number'],
431 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
433 ['A list of holds for the stated library to pull for', 'array']
435 method => 'hold_pull_list',
437 __PACKAGE__->register_method(
438 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
442 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
443 [ [org_unit => "The library's org id", "number"],
444 [limit => 'An optional page size, defaults to 10', 'number'],
445 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
447 ['A list of holds for the stated library to pull for', 'array']
449 method => 'hold_pull_list',
452 sub find_optional_surveys {
457 return undef unless ($ou);
458 my $s_table = action::survey->table;
460 my $select = <<" SQL";
463 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
464 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
465 AND s.required IS FALSE;
468 my $sth = action::survey->db_Main->prepare_cached($select);
471 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
475 __PACKAGE__->register_method(
476 api_name => 'open-ils.storage.action.survey.optional',
479 method => 'find_optional_surveys',
482 sub find_required_surveys {
487 return undef unless ($ou);
488 my $s_table = action::survey->table;
490 my $select = <<" SQL";
493 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
494 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
495 AND s.required IS TRUE;
498 my $sth = action::survey->db_Main->prepare_cached($select);
501 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
505 __PACKAGE__->register_method(
506 api_name => 'open-ils.storage.action.survey.required',
509 method => 'find_required_surveys',
512 sub find_usr_summary_surveys {
517 return undef unless ($ou);
518 my $s_table = action::survey->table;
520 my $select = <<" SQL";
523 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
524 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
525 AND s.usr_summary IS TRUE;
528 my $sth = action::survey->db_Main->prepare_cached($select);
531 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
535 __PACKAGE__->register_method(
536 api_name => 'open-ils.storage.action.survey.usr_summary',
539 method => 'find_usr_summary_surveys',
548 my $overbill = shift;
550 local $OpenILS::Application::Storage::WRITE = 1;
554 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
556 push @circs, overdue_circs($grace);
559 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
561 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
565 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
566 $log->debug("Cleaning up after previous transaction\n");
567 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
569 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
570 $log->info("Processing circ ".$c->id."...\n");
573 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
575 my $due = $due_dt->epoch;
578 my $fine_interval = $c->fine_interval;
579 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
580 $fine_interval = interval_to_seconds( $fine_interval );
582 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
584 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
585 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
588 $due -= ($due % $fine_interval) + $tz_offset_s;
589 $now -= ($now % $fine_interval) + $tz_offset_s;
593 "ARG! Overdue circulation ".$c->id.
594 " for item ".$c->target_copy.
595 " (user ".$c->usr.").\n".
596 "\tItem was due on or before: ".localtime($due)."\n");
598 my @fines = money::billing->search_where(
600 billing_type => 'Overdue materials',
601 billing_ts => { '>' => $c->due_date } },
602 { order_by => 'billing_ts DESC'}
606 my $fine = $fines[$f_idx] if (@fines);
608 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
611 my $current_fine_total = 0;
612 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
616 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
617 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
619 $log->info( "Potential first billing for circ ".$c->id );
623 if (my $h = $hoo{$c->circ_lib}) {
625 $log->info( "Circ lib has an hours-of-operation entry" );
626 # find the day after the due date...
627 $due_dt = $due_dt->add( days => 1 );
629 # get the day of the week for that day...
630 my $dow = $due_dt->day_of_week_0;
631 my $dow_open = "dow_${dow}_open";
632 my $dow_close = "dow_${dow}_close";
635 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
636 # if the circ lib is closed, add a day to the grace period...
639 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
640 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
642 $due_dt = $due_dt->add( days => 1 );
643 $dow = $due_dt->day_of_week_0;
644 $dow_open = "dow_${dow}_open";
645 $dow_close = "dow_${dow}_close";
649 # and check for up to a week
650 last if ($count > 6);
657 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
658 if ($pending_fine_count < 1 + $grace) {
659 $client->respond( "\tNo fines to create. " );
660 if ($grace && $now < $due + $fine_interval * $grace) {
661 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
662 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
664 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
669 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
671 my $recuring_fine = int($c->recuring_fine * 100);
672 my $max_fine = int($c->max_fine * 100);
674 my ($latest_billing_ts, $latest_amount) = ('',0);
675 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
677 if ($current_fine_total >= $max_fine) {
678 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
680 "\tMaximum fine level of ".$c->max_fine.
681 " reached for this circulation.\n".
682 "\tNo more fines will be generated.\n" );
686 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
688 my $dow = $billing_ts->day_of_week_0();
689 my $dow_open = "dow_${dow}_open";
690 my $dow_close = "dow_${dow}_close";
692 if (my $h = $hoo{$c->circ_lib}) {
693 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
696 my $timestamptz = $billing_ts->strftime('%FT%T%z');
697 my @cl = actor::org_unit::closed_date->search_where(
698 { close_start => { '<=' => $timestamptz },
699 close_end => { '>=' => $timestamptz },
700 org_unit => $c->circ_lib }
704 $current_fine_total += $recuring_fine;
705 $latest_amount += $recuring_fine;
706 $latest_billing_ts = $timestamptz;
708 money::billing->create(
710 note => "System Generated Overdue Fine",
711 billing_type => "Overdue materials",
712 amount => sprintf('%0.2f', $recuring_fine/100),
713 billing_ts => $timestamptz,
719 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
720 if ($latest_billing_ts and $latest_amount);
722 $self->method_lookup('open-ils.storage.transaction.commit')->run;
725 'open-ils.penalty.patron_penalty.calculate',
726 { patron => $c->usr->to_fieldmapper,
734 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
735 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
736 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
737 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
741 __PACKAGE__->register_method(
742 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
745 method => 'generate_fines',
750 sub new_hold_copy_targeter {
753 my $check_expire = shift;
754 my $one_hold = shift;
756 local $OpenILS::Application::Storage::WRITE = 1;
762 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
763 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
764 } elsif ( $check_expire ) {
766 # what's the retarget time threashold?
768 $check_expire ||= '12h';
769 $check_expire = interval_to_seconds( $check_expire );
771 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
774 my $expire_threshold = sprintf(
775 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
776 $year, $mon, $mday, $hour, $min, $sec
779 # find all the holds holds needing retargeting
780 $holds = [ action::hold_request->search_where(
781 { capture_time => undef,
782 fulfillment_time => undef,
783 cancel_time => undef,
785 prev_check_time => { '<=' => $expire_threshold },
787 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
789 # find all the holds holds needing first time targeting
790 push @$holds, action::hold_request->search(
791 capture_time => undef,
792 fulfillment_time => undef,
793 prev_check_time => undef,
795 cancel_time => undef,
796 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
799 # find all the holds holds needing first time targeting ONLY
800 $holds = [ action::hold_request->search(
801 capture_time => undef,
802 fulfillment_time => undef,
803 prev_check_time => undef,
804 cancel_time => undef,
806 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
810 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
813 my @closed = actor::org_unit::closed_date->search_where(
814 { close_start => { '<=', 'now' },
815 close_end => { '>=', 'now' } }
821 for my $hold (@$holds) {
823 #start a transaction if needed
824 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
825 $log->debug("Cleaning up after previous transaction\n");
826 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
828 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
829 $log->info("Processing hold ".$hold->id."...\n");
831 #first, re-fetch the hold, to make sure it's not captured already
832 $hold->remove_from_object_index();
833 $hold = action::hold_request->retrieve( $hold->id );
835 # remove old auto-targeting maps
836 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
837 $_->delete for (@oldmaps);
839 if ($hold->expire_time) {
840 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
841 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
842 $self->method_lookup('open-ils.storage.transaction.commit')->run;
845 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
849 # find filters for MR holds
850 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
852 # find all the potential copies
853 if ($hold->hold_type eq 'M') {
856 metabib::record_descriptor
860 isTrue($_->deleted) ? () : ($_->id)
861 } metabib::metarecord->retrieve($hold->target)->source_records
863 ( $types ? (item_type => [split '', $types]) : () ),
864 ( $formats ? (item_form => [split '', $formats]) : () ),
865 ( $lang ? (item_lang => $lang) : () ),
869 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
870 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
872 for my $cn ( @{ $rtree->call_numbers } ) {
874 asset::copy->search_where(
875 { id => [map {$_->id} @{ $cn->copies }],
877 ) if ($cn && @{ $cn->copies });
880 } elsif ($hold->hold_type eq 'T') {
882 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
883 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
886 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
890 for my $cn ( @{ $rtree->call_numbers } ) {
892 asset::copy->search_where(
893 { id => [map {$_->id} @{ $cn->copies }],
895 ) if ($cn && @{ $cn->copies });
897 } elsif ($hold->hold_type eq 'V') {
899 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
900 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
903 asset::copy->search_where(
904 { id => [map {$_->id} @{ $vtree->copies }],
906 ) if ($vtree && @{ $vtree->copies });
908 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
909 my $_cp = asset::copy->retrieve($hold->target);
910 push @$all_copies, $_cp if $_cp;
914 @$all_copies = grep { isTrue($_->status->holdable) &&
915 isTrue($_->location->holdable) &&
916 isTrue($_->holdable) &&
920 # let 'em know we're still working
921 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
923 # if we have no copies ...
924 if (!ref $all_copies || !@$all_copies) {
925 $log->info("\tNo copies available for targeting at all!\n");
926 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
928 $hold->update( { prev_check_time => 'today', current_copy => undef } );
929 $self->method_lookup('open-ils.storage.transaction.commit')->run;
933 my $copy_count = @$all_copies;
935 # map the potentials, so that we can pick up checkins
936 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
937 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
939 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
942 for my $c (@$all_copies) {
944 next if ($c->id eq $hold->current_copy);
947 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
949 # target of another hold
950 next if (action::hold_request
952 { current_copy => $c->id,
953 fulfillment_time => undef,
954 cancel_time => undef,
959 # we passed all three, keep it
960 push @good_copies, $c if ($c);
961 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
964 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
966 my $old_best = $hold->current_copy;
967 $hold->update({ current_copy => undef }) if ($old_best);
969 if (!scalar(@good_copies)) {
970 $log->info("\tNo (non-current) copies eligible to fill the hold.");
971 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
972 # the old copy is still available
973 $log->debug("\tPushing current_copy back onto the targeting list");
974 push @good_copies, $old_best;
976 # oops, old copy is not available
977 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
978 $hold->update( { prev_check_time => 'today' } );
979 $self->method_lookup('open-ils.storage.transaction.commit')->run;
980 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
985 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
990 $_->circ_lib == $hold->pickup_lib
994 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
996 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
997 my $best = choose_nearest_copy($hold, $prox_list);
998 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1001 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1002 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1004 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1006 $best = choose_nearest_copy($hold, $prox_list);
1009 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1011 # hold wasn't fulfilled, record the fact
1013 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1014 action::unfulfilled_hold_list->create(
1015 { hold => ''.$hold->id,
1016 current_copy => ''.$old_best->id,
1017 circ_lib => ''.$old_best->circ_lib,
1022 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1023 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1026 action::hold_request
1028 { current_copy => $old_best->id,
1029 fulfillment_time => undef,
1030 cancel_time => undef,
1034 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1035 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1037 $hold->update( { prev_check_time => 'now' } );
1038 $log->info( "\tThere were no targetable copies for the hold" );
1041 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1042 $log->info("\tProcessing of hold ".$hold->id." complete.");
1045 { hold => $hold->id,
1046 old_target => ($old_best ? $old_best->id : undef),
1047 eligible_copies => $copy_count,
1048 target => ($best ? $best->id : undef) };
1053 $log->error("Processing of hold failed: $e");
1054 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1055 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1062 __PACKAGE__->register_method(
1063 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1065 method => 'new_hold_copy_targeter',
1070 my %cache = (titles => {}, cns => {});
1071 sub hold_copy_targeter {
1074 my $check_expire = shift;
1075 my $one_hold = shift;
1077 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1078 $self->{user_filter}->connect;
1079 $self->{client} = $client;
1082 $check_expire ||= '12h';
1083 $check_expire = interval_to_seconds( $check_expire );
1085 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1088 my $expire_threshold = sprintf(
1089 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1090 $year, $mon, $mday, $hour, $min, $sec
1094 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1096 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1100 %cache = (titles => {}, cns => {});
1104 $holds = [ action::hold_request->search(id => $one_hold) ];
1106 $holds = [ action::hold_request->search_where(
1107 { capture_time => undef,
1108 prev_check_time => { '<=' => $expire_threshold },
1110 { order_by => 'request_time,prev_check_time' } ) ];
1111 push @$holds, action::hold_request->search_where(
1112 { capture_time => undef,
1113 prev_check_time => undef,
1115 { order_by => 'request_time' } );
1117 } catch Error with {
1119 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1122 for my $hold (@$holds) {
1124 #action::hold_request->db_Main->begin_work;
1125 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1126 $client->respond("Cleaning up after previous transaction\n");
1127 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1129 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1130 $client->respond("Processing hold ".$hold->id."...\n");
1134 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1135 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1137 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1138 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1140 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1141 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1143 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1145 unless (ref $copies || !@$copies) {
1146 $client->respond("\tNo copies available for targeting at all!\n");
1150 for my $c (@$copies) {
1151 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1152 push @good_copies, $c if ($c);
1155 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1157 my $old_best = $hold->current_copy;
1158 $hold->update({ current_copy => undef });
1160 if (!scalar(@good_copies)) {
1161 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1162 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1163 $client->respond("\tPushing current_copy back onto the targeting list\n");
1164 push @good_copies, asset::copy->retrieve( $old_best );
1166 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1172 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1173 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1175 my $best = choose_nearest_copy($hold, $prox_list);
1178 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1179 $best = choose_nearest_copy($hold, $prox_list);
1183 # hold wasn't fulfilled, record the fact
1185 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1186 action::unfulfilled_hold_list->create(
1187 { hold => ''.$hold->id,
1188 current_copy => ''.$old_best->id,
1189 circ_lib => ''.$old_best->circ_lib,
1194 $hold->update( { current_copy => ''.$best->id } );
1195 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1198 $hold->update( { prev_check_time => 'now' } );
1199 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1201 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1202 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1204 #action::hold_request->dbi_commit;
1208 $log->error("Processing of hold failed: $e");
1209 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1210 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1211 #action::hold_request->dbi_rollback;
1215 $self->{user_filter}->disconnect;
1216 $self->{user_filter}->finish;
1217 delete $$self{user_filter};
1220 __PACKAGE__->register_method(
1221 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1224 method => 'hold_copy_targeter',
1228 sub copy_hold_capture {
1233 if (!defined($cps)) {
1235 $cps = [ asset::copy->search( id => $hold->target ) ];
1236 } catch Error with {
1238 die "Could not retrieve initial volume list:\n\n$e\n";
1242 my @copies = grep { $_->holdable } @$cps;
1244 for (my $i = 0; $i < @$cps; $i++) {
1245 next unless $$cps[$i];
1247 my $cn = $cache{cns}{$copies[$i]->call_number};
1248 my $rec = $cache{titles}{$cn->record};
1249 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1250 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1251 $copies[$i] = undef if (
1253 !$self->{user_filter}->request(
1254 'open-ils.circ.permit_hold',
1255 $hold->to_fieldmapper, do {
1256 my $cp_fm = $copies[$i]->to_fieldmapper;
1257 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1258 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1259 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1262 { title => $rec->to_fieldmapper,
1263 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1264 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1267 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1270 @copies = grep { $_ } @copies;
1272 my $count = @copies;
1274 return unless ($count);
1276 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1279 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1280 for my $c (@copies) {
1281 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1283 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1289 sub choose_nearest_copy {
1291 my $prox_list = shift;
1293 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1294 next unless (ref $$prox_list[$p]);
1296 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1297 next unless (@capturable);
1299 my $rand = int(rand(scalar(@capturable)));
1300 while (my ($c) = splice(@capturable,$rand)) {
1301 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1302 { title => $c->call_number->record->to_fieldmapper,
1303 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1304 patron => $hold->usr->to_fieldmapper,
1305 copy => $c->to_fieldmapper,
1306 requestor => $hold->requestor->to_fieldmapper,
1307 request_lib => $hold->request_lib->to_fieldmapper,
1308 pickup_lib => $hold->pickup_lib->id,
1312 last unless(@capturable);
1313 $rand = int(rand(scalar(@capturable)));
1318 sub create_prox_list {
1324 for my $cp (@$copies) {
1325 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1326 next unless (defined($prox));
1327 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1328 push @{$prox_list[$prox]}, $cp;
1333 sub volume_hold_capture {
1338 if (!defined($vols)) {
1340 $vols = [ asset::call_number->search( id => $hold->target ) ];
1341 $cache{cns}{$_->id} = $_ for (@$vols);
1342 } catch Error with {
1344 die "Could not retrieve initial volume list:\n\n$e\n";
1348 my @v_ids = map { $_->id } @$vols;
1352 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1354 } catch Error with {
1356 warn "Could not retrieve copy list:\n\n$e\n";
1359 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1362 sub title_hold_capture {
1367 if (!defined($titles)) {
1369 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1370 $cache{titles}{$_->id} = $_ for (@$titles);
1371 } catch Error with {
1373 die "Could not retrieve initial title list:\n\n$e\n";
1377 my @t_ids = map { $_->id } @$titles;
1380 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1382 } catch Error with {
1384 warn "Could not retrieve volume list:\n\n$e\n";
1387 $cache{cns}{$_->id} = $_ for (@$cn_list);
1389 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1392 sub metarecord_hold_capture {
1398 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1400 } catch Error with {
1402 die "Could not retrieve initial title list:\n\n$e\n";
1406 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1408 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1410 } catch Error with {
1412 die "Could not retrieve format-pruned title list:\n\n$e\n";
1416 $cache{titles}{$_->id} = $_ for (@$titles);
1417 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);