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 $circ = action::circulation->table;
125 my $cp = asset::copy->table;
132 SELECT cp.id, MAX(circ.checkin_time)
134 JOIN $circ circ ON (circ.target_copy = cp.id)
135 WHERE circ.checkin_time IS NOT NULL
138 HAVING MAX(circ.checkin_time) < NOW() - CAST(? AS INTERVAL)
144 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
146 AND cp.create_date < NOW() - CAST(? AS INTERVAL)
150 my $sth = action::circulation->db_Main->prepare_cached($sql);
151 $sth->execute($window, $window);
156 __PACKAGE__->register_method(
157 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
161 method => 'complete_reshelving',
164 sub auto_thaw_frozen_holds {
168 local $OpenILS::Application::Storage::WRITE = 1;
170 my $holds = action::hold_request->table;
172 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
174 my $sth = action::hold_request->db_Main->prepare_cached($sql);
180 __PACKAGE__->register_method(
181 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
185 method => 'auto_thaw_frozen_holds',
191 my $grace = shift || '';
193 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
198 __PACKAGE__->register_method(
199 api_name => 'open-ils.storage.action.circulation.overdue',
202 method => 'grab_overdue',
210 my $limit = int(shift()) || 10;
211 my $age = shift() || '0 seconds';
213 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
215 FROM action.hold_request h
216 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
217 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
218 WHERE hm.target_copy = ?
219 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
220 AND h.capture_time IS NULL
221 AND h.cancel_time IS NULL
222 AND (h.expire_time IS NULL OR h.expire_time > NOW())
223 AND h.frozen IS FALSE
226 h.selection_depth DESC,
231 $client->respond( $_ ) for ( @$ids );
234 __PACKAGE__->register_method(
235 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
238 method => 'nearest_hold',
241 sub next_resp_group_id {
245 # XXX This is not replication safe!!!
247 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
248 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
252 __PACKAGE__->register_method(
253 api_name => 'open-ils.storage.action.survey_response.next_group_id',
255 method => 'next_resp_group_id',
258 sub patron_circ_summary {
263 return undef unless ($id);
264 my $c_table = action::circulation->table;
265 my $b_table = money::billing->table;
267 $log->debug("Retrieving patron summary for id $id", DEBUG);
269 my $select = <<" SQL";
270 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
272 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
274 AND c.xact_finish IS NULL
276 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
277 OR c.stop_fines IS NULL
281 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
283 __PACKAGE__->register_method(
284 api_name => 'open-ils.storage.action.circulation.patron_summary',
286 method => 'patron_circ_summary',
289 #XXX Fix stored proc calls
290 sub find_local_surveys {
295 return undef unless ($ou);
296 my $s_table = action::survey->table;
298 my $select = <<" SQL";
301 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
302 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
305 my $sth = action::survey->db_Main->prepare_cached($select);
308 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
312 __PACKAGE__->register_method(
313 api_name => 'open-ils.storage.action.survey.all',
316 method => 'find_local_surveys',
319 #XXX Fix stored proc calls
320 sub find_opac_surveys {
325 return undef unless ($ou);
326 my $s_table = action::survey->table;
328 my $select = <<" SQL";
331 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
332 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
336 my $sth = action::survey->db_Main->prepare_cached($select);
339 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
343 __PACKAGE__->register_method(
344 api_name => 'open-ils.storage.action.survey.opac',
347 method => 'find_opac_surveys',
354 my $limit = shift || 10;
355 my $offset = shift || 0;
357 return undef unless ($ou);
358 my $h_table = action::hold_request->table;
359 my $a_table = asset::copy->table;
361 my $idlist = 1 if ($self->api_name =~/id_list/o);
363 my $status_filter = '';
364 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
366 my $select = <<" SQL";
369 JOIN $a_table a ON (h.current_copy = a.id)
371 AND h.capture_time IS NULL
372 AND h.cancel_time IS NULL
373 AND (h.expire_time IS NULL OR h.expire_time > NOW())
375 ORDER BY h.request_time ASC
380 my $sth = action::survey->db_Main->prepare_cached($select);
384 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
386 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
391 __PACKAGE__->register_method(
392 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
396 "Returns the hold ids for a specific library's pull list.",
397 [ [org_unit => "The library's org id", "number"],
398 [limit => 'An optional page size, defaults to 10', 'number'],
399 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
401 ['A list of holds for the stated library to pull for', 'array']
403 method => 'hold_pull_list',
405 __PACKAGE__->register_method(
406 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
410 "Returns the holds for a specific library's pull list.",
411 [ [org_unit => "The library's org id", "number"],
412 [limit => 'An optional page size, defaults to 10', 'number'],
413 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
415 ['A list of holds for the stated library to pull for', 'array']
417 method => 'hold_pull_list',
419 __PACKAGE__->register_method(
420 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
424 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
425 [ [org_unit => "The library's org id", "number"],
426 [limit => 'An optional page size, defaults to 10', 'number'],
427 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
429 ['A list of holds for the stated library to pull for', 'array']
431 method => 'hold_pull_list',
433 __PACKAGE__->register_method(
434 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
438 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
439 [ [org_unit => "The library's org id", "number"],
440 [limit => 'An optional page size, defaults to 10', 'number'],
441 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
443 ['A list of holds for the stated library to pull for', 'array']
445 method => 'hold_pull_list',
448 sub find_optional_surveys {
453 return undef unless ($ou);
454 my $s_table = action::survey->table;
456 my $select = <<" SQL";
459 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
460 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
461 AND s.required IS FALSE;
464 my $sth = action::survey->db_Main->prepare_cached($select);
467 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
471 __PACKAGE__->register_method(
472 api_name => 'open-ils.storage.action.survey.optional',
475 method => 'find_optional_surveys',
478 sub find_required_surveys {
483 return undef unless ($ou);
484 my $s_table = action::survey->table;
486 my $select = <<" SQL";
489 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
490 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
491 AND s.required IS TRUE;
494 my $sth = action::survey->db_Main->prepare_cached($select);
497 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
501 __PACKAGE__->register_method(
502 api_name => 'open-ils.storage.action.survey.required',
505 method => 'find_required_surveys',
508 sub find_usr_summary_surveys {
513 return undef unless ($ou);
514 my $s_table = action::survey->table;
516 my $select = <<" SQL";
519 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
520 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
521 AND s.usr_summary IS TRUE;
524 my $sth = action::survey->db_Main->prepare_cached($select);
527 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
531 __PACKAGE__->register_method(
532 api_name => 'open-ils.storage.action.survey.usr_summary',
535 method => 'find_usr_summary_surveys',
544 my $overbill = shift;
546 local $OpenILS::Application::Storage::WRITE = 1;
550 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
552 push @circs, overdue_circs($grace);
555 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
557 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
561 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
562 $log->debug("Cleaning up after previous transaction\n");
563 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
565 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
566 $log->info("Processing circ ".$c->id."...\n");
569 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
571 my $due = $due_dt->epoch;
573 my $fine_interval = interval_to_seconds( $c->fine_interval );
575 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
577 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
578 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
581 $due -= ($due % $fine_interval) + $tz_offset_s;
582 $now -= ($now % $fine_interval) + $tz_offset_s;
586 "ARG! Overdue circulation ".$c->id.
587 " for item ".$c->target_copy.
588 " (user ".$c->usr.").\n".
589 "\tItem was due on or before: ".localtime($due)."\n");
591 my @fines = money::billing->search_where(
593 billing_type => 'Overdue materials',
594 billing_ts => { '>' => $c->due_date } },
595 { order_by => 'billing_ts DESC'}
599 my $fine = $fines[$f_idx] if (@fines);
601 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
604 my $current_fine_total = 0;
605 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
609 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
610 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
612 $log->info( "Potential first billing for circ ".$c->id );
616 if (my $h = $hoo{$c->circ_lib}) {
618 $log->info( "Circ lib has an hours-of-operation entry" );
619 # find the day after the due date...
620 $due_dt = $due_dt->add( days => 1 );
622 # get the day of the week for that day...
623 my $dow = $due_dt->day_of_week_0;
624 my $dow_open = "dow_${dow}_open";
625 my $dow_close = "dow_${dow}_close";
628 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
629 # if the circ lib is closed, add a day to the grace period...
632 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
633 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
635 $due_dt = $due_dt->add( days => 1 );
636 $dow = $due_dt->day_of_week_0;
637 $dow_open = "dow_${dow}_open";
638 $dow_close = "dow_${dow}_close";
642 # and check for up to a week
643 last if ($count > 6);
650 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
651 if ($pending_fine_count < 1 + $grace) {
652 $client->respond( "\tNo fines to create. " );
653 if ($grace && $now < $due + $fine_interval * $grace) {
654 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
655 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
657 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
662 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
664 my $recuring_fine = int($c->recuring_fine * 100);
665 my $max_fine = int($c->max_fine * 100);
667 my ($latest_billing_ts, $latest_amount) = ('',0);
668 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
670 if ($current_fine_total >= $max_fine) {
671 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
673 "\tMaximum fine level of ".$c->max_fine.
674 " reached for this circulation.\n".
675 "\tNo more fines will be generated.\n" );
679 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
681 my $dow = $billing_ts->day_of_week_0();
682 my $dow_open = "dow_${dow}_open";
683 my $dow_close = "dow_${dow}_close";
685 if (my $h = $hoo{$c->circ_lib}) {
686 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
689 my $timestamptz = $billing_ts->strftime('%FT%T%z');
690 my @cl = actor::org_unit::closed_date->search_where(
691 { close_start => { '<=' => $timestamptz },
692 close_end => { '>=' => $timestamptz },
693 org_unit => $c->circ_lib }
697 $current_fine_total += $recuring_fine;
698 $latest_amount += $recuring_fine;
699 $latest_billing_ts = $timestamptz;
701 money::billing->create(
703 note => "System Generated Overdue Fine",
704 billing_type => "Overdue materials",
705 amount => sprintf('%0.2f', $recuring_fine/100),
706 billing_ts => $timestamptz,
712 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
713 if ($latest_billing_ts and $latest_amount);
715 $self->method_lookup('open-ils.storage.transaction.commit')->run;
718 'open-ils.penalty.patron_penalty.calculate',
719 { patron => $c->usr->to_fieldmapper,
727 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
728 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
729 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
730 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
734 __PACKAGE__->register_method(
735 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
738 method => 'generate_fines',
743 sub new_hold_copy_targeter {
746 my $check_expire = shift;
747 my $one_hold = shift;
749 local $OpenILS::Application::Storage::WRITE = 1;
755 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
756 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
757 } elsif ( $check_expire ) {
759 # what's the retarget time threashold?
761 $check_expire ||= '12h';
762 $check_expire = interval_to_seconds( $check_expire );
764 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
767 my $expire_threshold = sprintf(
768 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
769 $year, $mon, $mday, $hour, $min, $sec
772 # find all the holds holds needing retargeting
773 $holds = [ action::hold_request->search_where(
774 { capture_time => undef,
775 fulfillment_time => undef,
776 cancel_time => undef,
778 prev_check_time => { '<=' => $expire_threshold },
780 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
782 # find all the holds holds needing first time targeting
783 push @$holds, action::hold_request->search(
784 capture_time => undef,
785 fulfillment_time => undef,
786 prev_check_time => undef,
788 cancel_time => undef,
789 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
792 # find all the holds holds needing first time targeting ONLY
793 $holds = [ action::hold_request->search(
794 capture_time => undef,
795 fulfillment_time => undef,
796 prev_check_time => undef,
797 cancel_time => undef,
799 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
803 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
806 my @closed = actor::org_unit::closed_date->search_where(
807 { close_start => { '<=', 'now' },
808 close_end => { '>=', 'now' } }
814 for my $hold (@$holds) {
816 #start a transaction if needed
817 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
818 $log->debug("Cleaning up after previous transaction\n");
819 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
821 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
822 $log->info("Processing hold ".$hold->id."...\n");
824 #first, re-fetch the hold, to make sure it's not captured already
825 $hold->remove_from_object_index();
826 $hold = action::hold_request->retrieve( $hold->id );
828 # remove old auto-targeting maps
829 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
830 $_->delete for (@oldmaps);
832 if ($hold->expire_time) {
833 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
834 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
835 $self->method_lookup('open-ils.storage.transaction.commit')->run;
838 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
842 # find filters for MR holds
843 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
845 # find all the potential copies
846 if ($hold->hold_type eq 'M') {
849 metabib::record_descriptor
853 isTrue($_->deleted) ? () : ($_->id)
854 } metabib::metarecord->retrieve($hold->target)->source_records
856 ( $types ? (item_type => [split '', $types]) : () ),
857 ( $formats ? (item_form => [split '', $formats]) : () ),
858 ( $lang ? (item_lang => $lang) : () ),
862 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
863 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
865 for my $cn ( @{ $rtree->call_numbers } ) {
867 asset::copy->search_where(
868 { id => [map {$_->id} @{ $cn->copies }],
870 ) if ($cn && @{ $cn->copies });
873 } elsif ($hold->hold_type eq 'T') {
875 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
876 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
879 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
883 for my $cn ( @{ $rtree->call_numbers } ) {
885 asset::copy->search_where(
886 { id => [map {$_->id} @{ $cn->copies }],
888 ) if ($cn && @{ $cn->copies });
890 } elsif ($hold->hold_type eq 'V') {
892 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
893 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
896 asset::copy->search_where(
897 { id => [map {$_->id} @{ $vtree->copies }],
899 ) if ($vtree && @{ $vtree->copies });
901 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
902 my $_cp = asset::copy->retrieve($hold->target);
903 push @$all_copies, $_cp if $_cp;
907 @$all_copies = grep { isTrue($_->status->holdable) &&
908 isTrue($_->location->holdable) &&
909 isTrue($_->holdable) &&
913 # let 'em know we're still working
914 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
916 # if we have no copies ...
917 if (!ref $all_copies || !@$all_copies) {
918 $log->info("\tNo copies available for targeting at all!\n");
919 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
921 $hold->update( { prev_check_time => 'today', current_copy => undef } );
922 $self->method_lookup('open-ils.storage.transaction.commit')->run;
926 my $copy_count = @$all_copies;
928 # map the potentials, so that we can pick up checkins
929 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
930 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
932 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
935 for my $c (@$all_copies) {
937 next if ($c->id eq $hold->current_copy);
940 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
942 # target of another hold
943 next if (action::hold_request
945 { current_copy => $c->id,
946 fulfillment_time => undef,
947 cancel_time => undef,
952 # we passed all three, keep it
953 push @good_copies, $c if ($c);
954 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
957 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
959 my $old_best = $hold->current_copy;
960 $hold->update({ current_copy => undef }) if ($old_best);
962 if (!scalar(@good_copies)) {
963 $log->info("\tNo (non-current) copies eligible to fill the hold.");
964 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
965 # the old copy is still available
966 $log->debug("\tPushing current_copy back onto the targeting list");
967 push @good_copies, $old_best;
969 # oops, old copy is not available
970 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
971 $hold->update( { prev_check_time => 'today' } );
972 $self->method_lookup('open-ils.storage.transaction.commit')->run;
973 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
978 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
983 $_->circ_lib == $hold->pickup_lib
987 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
989 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
990 my $best = choose_nearest_copy($hold, $prox_list);
991 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
994 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
995 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
997 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
999 $best = choose_nearest_copy($hold, $prox_list);
1002 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1004 # hold wasn't fulfilled, record the fact
1006 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1007 action::unfulfilled_hold_list->create(
1008 { hold => ''.$hold->id,
1009 current_copy => ''.$old_best->id,
1010 circ_lib => ''.$old_best->circ_lib,
1015 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1016 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1019 action::hold_request
1021 { current_copy => $old_best->id,
1022 fulfillment_time => undef,
1023 cancel_time => undef,
1027 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1028 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1030 $hold->update( { prev_check_time => 'now' } );
1031 $log->info( "\tThere were no targetable copies for the hold" );
1034 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1035 $log->info("\tProcessing of hold ".$hold->id." complete.");
1038 { hold => $hold->id,
1039 old_target => ($old_best ? $old_best->id : undef),
1040 eligible_copies => $copy_count,
1041 target => ($best ? $best->id : undef) };
1046 $log->error("Processing of hold failed: $e");
1047 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1048 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1055 __PACKAGE__->register_method(
1056 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1058 method => 'new_hold_copy_targeter',
1063 my %cache = (titles => {}, cns => {});
1064 sub hold_copy_targeter {
1067 my $check_expire = shift;
1068 my $one_hold = shift;
1070 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1071 $self->{user_filter}->connect;
1072 $self->{client} = $client;
1075 $check_expire ||= '12h';
1076 $check_expire = interval_to_seconds( $check_expire );
1078 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1081 my $expire_threshold = sprintf(
1082 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1083 $year, $mon, $mday, $hour, $min, $sec
1087 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1089 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1093 %cache = (titles => {}, cns => {});
1097 $holds = [ action::hold_request->search(id => $one_hold) ];
1099 $holds = [ action::hold_request->search_where(
1100 { capture_time => undef,
1101 prev_check_time => { '<=' => $expire_threshold },
1103 { order_by => 'request_time,prev_check_time' } ) ];
1104 push @$holds, action::hold_request->search_where(
1105 { capture_time => undef,
1106 prev_check_time => undef,
1108 { order_by => 'request_time' } );
1110 } catch Error with {
1112 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1115 for my $hold (@$holds) {
1117 #action::hold_request->db_Main->begin_work;
1118 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1119 $client->respond("Cleaning up after previous transaction\n");
1120 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1122 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1123 $client->respond("Processing hold ".$hold->id."...\n");
1127 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1128 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1130 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1131 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1133 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1134 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1136 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1138 unless (ref $copies || !@$copies) {
1139 $client->respond("\tNo copies available for targeting at all!\n");
1143 for my $c (@$copies) {
1144 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1145 push @good_copies, $c if ($c);
1148 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1150 my $old_best = $hold->current_copy;
1151 $hold->update({ current_copy => undef });
1153 if (!scalar(@good_copies)) {
1154 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1155 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1156 $client->respond("\tPushing current_copy back onto the targeting list\n");
1157 push @good_copies, asset::copy->retrieve( $old_best );
1159 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1165 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1166 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1168 my $best = choose_nearest_copy($hold, $prox_list);
1171 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1172 $best = choose_nearest_copy($hold, $prox_list);
1176 # hold wasn't fulfilled, record the fact
1178 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1179 action::unfulfilled_hold_list->create(
1180 { hold => ''.$hold->id,
1181 current_copy => ''.$old_best->id,
1182 circ_lib => ''.$old_best->circ_lib,
1187 $hold->update( { current_copy => ''.$best->id } );
1188 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1191 $hold->update( { prev_check_time => 'now' } );
1192 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1194 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1195 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1197 #action::hold_request->dbi_commit;
1201 $log->error("Processing of hold failed: $e");
1202 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1203 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1204 #action::hold_request->dbi_rollback;
1208 $self->{user_filter}->disconnect;
1209 $self->{user_filter}->finish;
1210 delete $$self{user_filter};
1213 __PACKAGE__->register_method(
1214 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1217 method => 'hold_copy_targeter',
1221 sub copy_hold_capture {
1226 if (!defined($cps)) {
1228 $cps = [ asset::copy->search( id => $hold->target ) ];
1229 } catch Error with {
1231 die "Could not retrieve initial volume list:\n\n$e\n";
1235 my @copies = grep { $_->holdable } @$cps;
1237 for (my $i = 0; $i < @$cps; $i++) {
1238 next unless $$cps[$i];
1240 my $cn = $cache{cns}{$copies[$i]->call_number};
1241 my $rec = $cache{titles}{$cn->record};
1242 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1243 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1244 $copies[$i] = undef if (
1246 !$self->{user_filter}->request(
1247 'open-ils.circ.permit_hold',
1248 $hold->to_fieldmapper, do {
1249 my $cp_fm = $copies[$i]->to_fieldmapper;
1250 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1251 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1252 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1255 { title => $rec->to_fieldmapper,
1256 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1257 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1260 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1263 @copies = grep { $_ } @copies;
1265 my $count = @copies;
1267 return unless ($count);
1269 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1272 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1273 for my $c (@copies) {
1274 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1276 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1282 sub choose_nearest_copy {
1284 my $prox_list = shift;
1286 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1287 next unless (ref $$prox_list[$p]);
1289 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1290 next unless (@capturable);
1292 my $rand = int(rand(scalar(@capturable)));
1293 while (my ($c) = splice(@capturable,$rand)) {
1294 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1295 { title => $c->call_number->record->to_fieldmapper,
1296 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1297 patron => $hold->usr->to_fieldmapper,
1298 copy => $c->to_fieldmapper,
1299 requestor => $hold->requestor->to_fieldmapper,
1300 request_lib => $hold->request_lib->to_fieldmapper,
1301 pickup_lib => $hold->pickup_lib->id,
1305 last unless(@capturable);
1306 $rand = int(rand(scalar(@capturable)));
1311 sub create_prox_list {
1317 for my $cp (@$copies) {
1318 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1319 next unless (defined($prox));
1320 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1321 push @{$prox_list[$prox]}, $cp;
1326 sub volume_hold_capture {
1331 if (!defined($vols)) {
1333 $vols = [ asset::call_number->search( id => $hold->target ) ];
1334 $cache{cns}{$_->id} = $_ for (@$vols);
1335 } catch Error with {
1337 die "Could not retrieve initial volume list:\n\n$e\n";
1341 my @v_ids = map { $_->id } @$vols;
1345 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1347 } catch Error with {
1349 warn "Could not retrieve copy list:\n\n$e\n";
1352 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1355 sub title_hold_capture {
1360 if (!defined($titles)) {
1362 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1363 $cache{titles}{$_->id} = $_ for (@$titles);
1364 } catch Error with {
1366 die "Could not retrieve initial title list:\n\n$e\n";
1370 my @t_ids = map { $_->id } @$titles;
1373 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1375 } catch Error with {
1377 warn "Could not retrieve volume list:\n\n$e\n";
1380 $cache{cns}{$_->id} = $_ for (@$cn_list);
1382 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1385 sub metarecord_hold_capture {
1391 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1393 } catch Error with {
1395 die "Could not retrieve initial title list:\n\n$e\n";
1399 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1401 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1403 } catch Error with {
1405 die "Could not retrieve format-pruned title list:\n\n$e\n";
1409 $cache{titles}{$_->id} = $_ for (@$titles);
1410 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);