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 ORDER BY h.request_time
69 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
72 $client->respond($_) for (
75 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
79 } @{ $sth->fetchall_arrayref }
83 __PACKAGE__->register_method(
84 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
88 method => 'ou_hold_requests',
95 my $c_t = action::circulation->table;
97 $grace = " - ($grace * (fine_interval))" if ($grace);
102 WHERE stop_fines IS NULL
103 AND due_date < ( CURRENT_TIMESTAMP $grace)
106 my $sth = action::circulation->db_Main->prepare_cached($sql);
109 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
113 sub complete_reshelving {
118 local $OpenILS::Application::Storage::WRITE = 1;
120 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
121 unless (interval_to_seconds( $window ));
123 my $circ = action::circulation->table;
124 my $cp = asset::copy->table;
131 SELECT cp.id, MAX(circ.checkin_time)
133 JOIN $circ circ ON (circ.target_copy = cp.id)
134 WHERE circ.checkin_time IS NOT NULL
137 HAVING MAX(circ.checkin_time) < NOW() - CAST(? AS INTERVAL)
143 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
145 AND cp.create_date < NOW() - CAST(? AS INTERVAL)
149 my $sth = action::circulation->db_Main->prepare_cached($sql);
150 $sth->execute($window, $window);
155 __PACKAGE__->register_method(
156 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
160 method => 'complete_reshelving',
166 my $grace = shift || '';
168 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
173 __PACKAGE__->register_method(
174 api_name => 'open-ils.storage.action.circulation.overdue',
177 method => 'grab_overdue',
185 my $limit = int(shift()) || 10;
187 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
189 FROM action.hold_request h
190 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
191 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
192 WHERE hm.target_copy = ?
194 AND h.capture_time IS NULL
195 AND h.cancel_time IS NULL
198 h.selection_depth DESC,
204 __PACKAGE__->register_method(
205 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
208 method => 'nearest_hold',
211 sub next_resp_group_id {
215 # XXX This is not replication safe!!!
217 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
218 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
222 __PACKAGE__->register_method(
223 api_name => 'open-ils.storage.action.survey_response.next_group_id',
225 method => 'next_resp_group_id',
228 sub patron_circ_summary {
233 return undef unless ($id);
234 my $c_table = action::circulation->table;
235 my $b_table = money::billing->table;
237 $log->debug("Retrieving patron summary for id $id", DEBUG);
239 my $select = <<" SQL";
240 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
242 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
244 AND c.xact_finish IS NULL
246 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
247 OR c.stop_fines IS NULL
251 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
253 __PACKAGE__->register_method(
254 api_name => 'open-ils.storage.action.circulation.patron_summary',
256 method => 'patron_circ_summary',
259 #XXX Fix stored proc calls
260 sub find_local_surveys {
265 return undef unless ($ou);
266 my $s_table = action::survey->table;
268 my $select = <<" SQL";
271 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
272 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
275 my $sth = action::survey->db_Main->prepare_cached($select);
278 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
282 __PACKAGE__->register_method(
283 api_name => 'open-ils.storage.action.survey.all',
286 method => 'find_local_surveys',
289 #XXX Fix stored proc calls
290 sub find_opac_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
306 my $sth = action::survey->db_Main->prepare_cached($select);
309 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
313 __PACKAGE__->register_method(
314 api_name => 'open-ils.storage.action.survey.opac',
317 method => 'find_opac_surveys',
324 my $limit = shift || 10;
325 my $offset = shift || 0;
327 return undef unless ($ou);
328 my $h_table = action::hold_request->table;
329 my $a_table = asset::copy->table;
331 my $idlist = 1 if ($self->api_name =~/id_list/o);
333 my $select = <<" SQL";
336 JOIN $a_table a ON (h.current_copy = a.id)
338 AND h.capture_time IS NULL
339 AND h.cancel_time IS NULL
340 ORDER BY h.request_time ASC
345 my $sth = action::survey->db_Main->prepare_cached($select);
349 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
351 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
356 __PACKAGE__->register_method(
357 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
361 "Returns the hold ids for a specific library's pull list.",
362 [ [org_unit => "The library's org id", "number"],
363 [limit => 'An optional page size, defaults to 10', 'number'],
364 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
366 ['A list of holds for the stated library to pull for', 'array']
368 method => 'hold_pull_list',
370 __PACKAGE__->register_method(
371 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
375 "Returns the holds for a specific library's pull list.",
376 [ [org_unit => "The library's org id", "number"],
377 [limit => 'An optional page size, defaults to 10', 'number'],
378 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
380 ['A list of holds for the stated library to pull for', 'array']
382 method => 'hold_pull_list',
385 sub find_optional_surveys {
390 return undef unless ($ou);
391 my $s_table = action::survey->table;
393 my $select = <<" SQL";
396 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
397 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
398 AND s.required IS FALSE;
401 my $sth = action::survey->db_Main->prepare_cached($select);
404 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
408 __PACKAGE__->register_method(
409 api_name => 'open-ils.storage.action.survey.optional',
412 method => 'find_optional_surveys',
415 sub find_required_surveys {
420 return undef unless ($ou);
421 my $s_table = action::survey->table;
423 my $select = <<" SQL";
426 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
427 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
428 AND s.required IS TRUE;
431 my $sth = action::survey->db_Main->prepare_cached($select);
434 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
438 __PACKAGE__->register_method(
439 api_name => 'open-ils.storage.action.survey.required',
442 method => 'find_required_surveys',
445 sub find_usr_summary_surveys {
450 return undef unless ($ou);
451 my $s_table = action::survey->table;
453 my $select = <<" SQL";
456 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
457 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
458 AND s.usr_summary IS TRUE;
461 my $sth = action::survey->db_Main->prepare_cached($select);
464 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
468 __PACKAGE__->register_method(
469 api_name => 'open-ils.storage.action.survey.usr_summary',
472 method => 'find_usr_summary_surveys',
481 my $overbill = shift;
483 local $OpenILS::Application::Storage::WRITE = 1;
487 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
489 push @circs, overdue_circs($grace);
492 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
494 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
498 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
499 $log->debug("Cleaning up after previous transaction\n");
500 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
502 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
503 $log->info("Processing circ ".$c->id."...\n");
506 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
508 my $due = $due_dt->epoch;
510 my $fine_interval = interval_to_seconds( $c->fine_interval );
512 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
514 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
515 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
518 $due -= ($due % $fine_interval) + $tz_offset_s;
519 $now -= ($now % $fine_interval) + $tz_offset_s;
523 "ARG! Overdue circulation ".$c->id.
524 " for item ".$c->target_copy.
525 " (user ".$c->usr.").\n".
526 "\tItem was due on or before: ".localtime($due)."\n");
528 my @fines = money::billing->search_where(
529 { xact => $c->id, billing_type => 'Overdue materials' },
530 { order_by => 'billing_ts DESC'}
534 my $fine = $fines[$f_idx] if (@fines);
536 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
539 my $current_fine_total = 0;
540 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
544 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
545 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
547 $log->info( "Potential first billing for circ ".$c->id );
551 if (my $h = $hoo{$c->circ_lib}) {
553 $log->info( "Circ lib has an hours-of-operation entry" );
554 # find the day after the due date...
555 $due_dt = $due_dt->add( days => 1 );
557 # get the day of the week for that day...
558 my $dow = $due_dt->day_of_week_0;
559 my $dow_open = "dow_${dow}_open";
560 my $dow_close = "dow_${dow}_close";
563 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
564 # if the circ lib is closed, add a day to the grace period...
567 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
568 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
570 $due_dt = $due_dt->add( days => 1 );
571 $dow = $due_dt->day_of_week_0;
572 $dow_open = "dow_${dow}_open";
573 $dow_close = "dow_${dow}_close";
577 # and check for up to a week
578 last if ($count > 6);
585 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
586 if ($pending_fine_count < 1 + $grace) {
587 $client->respond( "\tNo fines to create. " );
588 if ($grace && $now < $due + $fine_interval * $grace) {
589 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
590 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
592 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
597 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
599 my $recuring_fine = int($c->recuring_fine * 100);
600 my $max_fine = int($c->max_fine * 100);
602 my ($latest_billing_ts, $latest_amount) = ('',0);
603 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
605 if ($current_fine_total >= $max_fine) {
606 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
608 "\tMaximum fine level of ".$c->max_fine.
609 " reached for this circulation.\n".
610 "\tNo more fines will be generated.\n" );
614 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
616 my $dow = $billing_ts->day_of_week_0();
617 my $dow_open = "dow_${dow}_open";
618 my $dow_close = "dow_${dow}_close";
620 if (my $h = $hoo{$c->circ_lib}) {
621 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
624 my $timestamptz = $billing_ts->strftime('%FT%T%z');
625 my @cl = actor::org_unit::closed_date->search_where(
626 { close_start => { '<=' => $timestamptz },
627 close_end => { '>=' => $timestamptz },
628 org_unit => $c->circ_lib }
632 $current_fine_total += $recuring_fine;
633 $latest_amount += $recuring_fine;
634 $latest_billing_ts = $timestamptz;
636 money::billing->create(
638 note => "System Generated Overdue Fine",
639 billing_type => "Overdue materials",
640 amount => sprintf('%0.2f', $recuring_fine/100),
641 billing_ts => $timestamptz,
647 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
648 if ($latest_billing_ts and $latest_amount);
650 $self->method_lookup('open-ils.storage.transaction.commit')->run;
653 'open-ils.penalty.patron_penalty.calculate',
654 { patron => $c->usr->to_fieldmapper,
662 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
663 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
664 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
665 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
669 __PACKAGE__->register_method(
670 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
673 method => 'generate_fines',
678 sub new_hold_copy_targeter {
681 my $check_expire = shift;
682 my $one_hold = shift;
684 local $OpenILS::Application::Storage::WRITE = 1;
690 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
691 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
692 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
693 } elsif ( $check_expire ) {
695 # what's the retarget time threashold?
697 $check_expire ||= '12h';
698 $check_expire = interval_to_seconds( $check_expire );
700 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
703 my $expire_threshold = sprintf(
704 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
705 $year, $mon, $mday, $hour, $min, $sec
708 # find all the holds holds needing retargeting
709 $holds = [ action::hold_request->search_where(
710 { capture_time => undef,
711 fulfillment_time => undef,
712 cancel_time => undef,
713 prev_check_time => { '<=' => $expire_threshold },
715 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
717 # find all the holds holds needing first time targeting
718 push @$holds, action::hold_request->search(
719 capture_time => undef,
720 fulfillment_time => undef,
721 prev_check_time => undef,
722 cancel_time => undef,
723 { order_by => 'selection_depth DESC, request_time' } );
726 # find all the holds holds needing first time targeting ONLY
727 $holds = [ action::hold_request->search(
728 capture_time => undef,
729 fulfillment_time => undef,
730 prev_check_time => undef,
731 cancel_time => undef,
732 { order_by => 'selection_depth DESC, request_time' } ) ];
736 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
739 my @closed = actor::org_unit::closed_date->search_where(
740 { close_start => { '<=', 'today' },
741 close_end => { '>=', 'today' } }
747 for my $hold (@$holds) {
749 #first, re-fetch the hold, to make sure it's not captured already
750 $hold = action::hold_request->retrieve( $hold->id );
751 die "OK\n" if (!$hold or $hold->capture_time);
753 #start a transaction if needed
754 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
755 $log->debug("Cleaning up after previous transaction\n");
756 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
758 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
759 $log->info("Processing hold ".$hold->id."...\n");
761 # remove old auto-targeting maps
762 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
763 $_->delete for (@oldmaps);
768 # find filters for MR holds
769 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
771 # find all the potential copies
772 if ($hold->hold_type eq 'M') {
775 metabib::record_descriptor
777 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
778 ( $types ? (item_type => [split '', $types]) : () ),
779 ( $formats ? (item_form => [split '', $formats]) : () ),
780 ( $lang ? (item_lang => $lang) : () ),
784 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
785 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
787 for my $cn ( @{ $rtree->call_numbers } ) {
789 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
792 } elsif ($hold->hold_type eq 'T') {
794 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
795 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
798 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
802 for my $cn ( @{ $rtree->call_numbers } ) {
804 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
806 } elsif ($hold->hold_type eq 'V') {
808 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
809 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
812 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
814 } elsif ($hold->hold_type eq 'C') {
816 $all_copies = [asset::copy->retrieve($hold->target)];
820 @$all_copies = grep { isTrue($_->status->holdable) &&
821 isTrue($_->location->holdable) &&
822 isTrue($_->holdable) &&
826 # let 'em know we're still working
827 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
829 # if we have no copies ...
830 if (!ref $all_copies || !@$all_copies) {
831 $log->info("\tNo copies available for targeting at all!\n");
832 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
834 $hold->update( { prev_check_time => 'today' } );
835 $self->method_lookup('open-ils.storage.transaction.commit')->run;
839 my $copy_count = @$all_copies;
841 # map the potentials, so that we can pick up checkins
842 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
843 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
845 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
848 for my $c (@$all_copies) {
850 next if ($c->id == $hold->current_copy);
853 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
855 # target of another hold
856 next if (action::hold_request
858 { current_copy => $c->id,
859 fulfillment_time => undef,
860 cancel_time => undef,
865 # we passed all three, keep it
866 push @good_copies, $c if ($c);
867 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
870 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
872 my $old_best = $hold->current_copy;
873 $hold->update({ current_copy => undef }) if ($old_best);
875 if (!scalar(@good_copies)) {
876 $log->info("\tNo (non-current) copies eligible to fill the hold.");
879 grep { $old_best eq $_ } @$all_copies &&
880 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
882 # the old copy is still available
883 $log->debug("\tPushing current_copy back onto the targeting list");
884 push @good_copies, $old_best;
886 # oops, old copy is not available
887 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
888 $hold->update( { prev_check_time => 'today' } );
889 $self->method_lookup('open-ils.storage.transaction.commit')->run;
890 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
895 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
900 $_->circ_lib == $hold->pickup_lib
904 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
906 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
907 my $best = choose_nearest_copy($hold, $prox_list);
908 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
911 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
912 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
914 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
916 $best = choose_nearest_copy($hold, $prox_list);
919 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
921 # hold wasn't fulfilled, record the fact
923 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
924 action::unfulfilled_hold_list->create(
925 { hold => ''.$hold->id,
926 current_copy => ''.$old_best->id,
927 circ_lib => ''.$old_best->circ_lib,
932 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
933 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
935 $hold->update( { prev_check_time => 'now' } );
936 $log->info( "\tThere were no targetable copies for the hold" );
939 $self->method_lookup('open-ils.storage.transaction.commit')->run;
940 $log->info("\tProcessing of hold ".$hold->id." complete.");
944 old_target => ($old_best ? $old_best->id : undef),
945 eligible_copies => $copy_count,
946 target => ($best ? $best->id : undef) };
951 $log->error("Processing of hold failed: $e");
952 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
953 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
960 __PACKAGE__->register_method(
961 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
963 method => 'new_hold_copy_targeter',
968 my %cache = (titles => {}, cns => {});
969 sub hold_copy_targeter {
972 my $check_expire = shift;
973 my $one_hold = shift;
975 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
976 $self->{user_filter}->connect;
977 $self->{client} = $client;
980 $check_expire ||= '12h';
981 $check_expire = interval_to_seconds( $check_expire );
983 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
986 my $expire_threshold = sprintf(
987 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
988 $year, $mon, $mday, $hour, $min, $sec
992 $statuses ||= [ config::copy_status->search(holdable => 't') ];
994 $locations ||= [ asset::copy_location->search(holdable => 't') ];
998 %cache = (titles => {}, cns => {});
1002 $holds = [ action::hold_request->search(id => $one_hold) ];
1004 $holds = [ action::hold_request->search_where(
1005 { capture_time => undef,
1006 prev_check_time => { '<=' => $expire_threshold },
1008 { order_by => 'request_time,prev_check_time' } ) ];
1009 push @$holds, action::hold_request->search_where(
1010 { capture_time => undef,
1011 prev_check_time => undef,
1013 { order_by => 'request_time' } );
1015 } catch Error with {
1017 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1020 for my $hold (@$holds) {
1022 #action::hold_request->db_Main->begin_work;
1023 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1024 $client->respond("Cleaning up after previous transaction\n");
1025 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1027 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1028 $client->respond("Processing hold ".$hold->id."...\n");
1032 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1033 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1035 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1036 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1038 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1039 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1041 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1043 unless (ref $copies || !@$copies) {
1044 $client->respond("\tNo copies available for targeting at all!\n");
1048 for my $c (@$copies) {
1049 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1050 push @good_copies, $c if ($c);
1053 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1055 my $old_best = $hold->current_copy;
1056 $hold->update({ current_copy => undef });
1058 if (!scalar(@good_copies)) {
1059 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1060 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1061 $client->respond("\tPushing current_copy back onto the targeting list\n");
1062 push @good_copies, asset::copy->retrieve( $old_best );
1064 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1070 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1071 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1073 my $best = choose_nearest_copy($hold, $prox_list);
1076 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1077 $best = choose_nearest_copy($hold, $prox_list);
1081 # hold wasn't fulfilled, record the fact
1083 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1084 action::unfulfilled_hold_list->create(
1085 { hold => ''.$hold->id,
1086 current_copy => ''.$old_best->id,
1087 circ_lib => ''.$old_best->circ_lib,
1092 $hold->update( { current_copy => ''.$best->id } );
1093 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1096 $hold->update( { prev_check_time => 'now' } );
1097 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1099 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1100 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1102 #action::hold_request->dbi_commit;
1106 $log->error("Processing of hold failed: $e");
1107 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1108 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1109 #action::hold_request->dbi_rollback;
1113 $self->{user_filter}->disconnect;
1114 $self->{user_filter}->finish;
1115 delete $$self{user_filter};
1118 __PACKAGE__->register_method(
1119 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1122 method => 'hold_copy_targeter',
1126 sub copy_hold_capture {
1131 if (!defined($cps)) {
1133 $cps = [ asset::copy->search( id => $hold->target ) ];
1134 } catch Error with {
1136 die "Could not retrieve initial volume list:\n\n$e\n";
1140 my @copies = grep { $_->holdable } @$cps;
1142 for (my $i = 0; $i < @$cps; $i++) {
1143 next unless $$cps[$i];
1145 my $cn = $cache{cns}{$copies[$i]->call_number};
1146 my $rec = $cache{titles}{$cn->record};
1147 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1148 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1149 $copies[$i] = undef if (
1151 !$self->{user_filter}->request(
1152 'open-ils.circ.permit_hold',
1153 $hold->to_fieldmapper, do {
1154 my $cp_fm = $copies[$i]->to_fieldmapper;
1155 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1156 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1157 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1160 { title => $rec->to_fieldmapper,
1161 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1162 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1165 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1168 @copies = grep { $_ } @copies;
1170 my $count = @copies;
1172 return unless ($count);
1174 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1177 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1178 for my $c (@copies) {
1179 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1181 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1187 sub choose_nearest_copy {
1189 my $prox_list = shift;
1191 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1192 next unless (ref $$prox_list[$p]);
1194 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1195 next unless (@capturable);
1197 my $rand = int(rand(scalar(@capturable)));
1198 while (my ($c) = splice(@capturable,$rand)) {
1199 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1200 { title => $c->call_number->record->to_fieldmapper,
1201 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1202 patron => $hold->usr->to_fieldmapper,
1203 copy => $c->to_fieldmapper,
1204 requestor => $hold->requestor->to_fieldmapper,
1205 request_lib => $hold->request_lib->to_fieldmapper,
1208 last unless(@capturable);
1209 $rand = int(rand(scalar(@capturable)));
1217 sub create_prox_list {
1223 for my $cp (@$copies) {
1224 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1225 next unless (defined($prox));
1226 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1227 push @{$prox_list[$prox]}, $cp;
1232 sub volume_hold_capture {
1237 if (!defined($vols)) {
1239 $vols = [ asset::call_number->search( id => $hold->target ) ];
1240 $cache{cns}{$_->id} = $_ for (@$vols);
1241 } catch Error with {
1243 die "Could not retrieve initial volume list:\n\n$e\n";
1247 my @v_ids = map { $_->id } @$vols;
1251 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1253 } catch Error with {
1255 warn "Could not retrieve copy list:\n\n$e\n";
1258 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1261 sub title_hold_capture {
1266 if (!defined($titles)) {
1268 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1269 $cache{titles}{$_->id} = $_ for (@$titles);
1270 } catch Error with {
1272 die "Could not retrieve initial title list:\n\n$e\n";
1276 my @t_ids = map { $_->id } @$titles;
1279 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1281 } catch Error with {
1283 warn "Could not retrieve volume list:\n\n$e\n";
1286 $cache{cns}{$_->id} = $_ for (@$cn_list);
1288 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1291 sub metarecord_hold_capture {
1297 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1299 } catch Error with {
1301 die "Could not retrieve initial title list:\n\n$e\n";
1305 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1307 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1309 } catch Error with {
1311 die "Could not retrieve format-pruned title list:\n\n$e\n";
1315 $cache{titles}{$_->id} = $_ for (@$titles);
1316 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);