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)
142 my $sth = action::circulation->db_Main->prepare_cached($sql);
143 $sth->execute($window);
148 __PACKAGE__->register_method(
149 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
153 method => 'complete_reshelving',
159 my $grace = shift || '';
161 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
166 __PACKAGE__->register_method(
167 api_name => 'open-ils.storage.action.circulation.overdue',
170 method => 'grab_overdue',
178 my $limit = int(shift()) || 10;
180 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
182 FROM action.hold_request h
183 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
184 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
185 WHERE hm.target_copy = ?
187 AND h.capture_time IS NULL
188 AND h.cancel_time IS NULL
191 h.selection_depth DESC,
197 __PACKAGE__->register_method(
198 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
201 method => 'nearest_hold',
204 sub next_resp_group_id {
208 # XXX This is not replication safe!!!
210 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
211 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
215 __PACKAGE__->register_method(
216 api_name => 'open-ils.storage.action.survey_response.next_group_id',
218 method => 'next_resp_group_id',
221 sub patron_circ_summary {
226 return undef unless ($id);
227 my $c_table = action::circulation->table;
228 my $b_table = money::billing->table;
230 $log->debug("Retrieving patron summary for id $id", DEBUG);
232 my $select = <<" SQL";
233 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
235 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
237 AND c.xact_finish IS NULL
239 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
240 OR c.stop_fines IS NULL
244 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
246 __PACKAGE__->register_method(
247 api_name => 'open-ils.storage.action.circulation.patron_summary',
249 method => 'patron_circ_summary',
252 #XXX Fix stored proc calls
253 sub find_local_surveys {
258 return undef unless ($ou);
259 my $s_table = action::survey->table;
261 my $select = <<" SQL";
264 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
265 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
268 my $sth = action::survey->db_Main->prepare_cached($select);
271 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
275 __PACKAGE__->register_method(
276 api_name => 'open-ils.storage.action.survey.all',
279 method => 'find_local_surveys',
282 #XXX Fix stored proc calls
283 sub find_opac_surveys {
288 return undef unless ($ou);
289 my $s_table = action::survey->table;
291 my $select = <<" SQL";
294 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
295 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
299 my $sth = action::survey->db_Main->prepare_cached($select);
302 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
306 __PACKAGE__->register_method(
307 api_name => 'open-ils.storage.action.survey.opac',
310 method => 'find_opac_surveys',
317 my $limit = shift || 10;
318 my $offset = shift || 0;
320 return undef unless ($ou);
321 my $h_table = action::hold_request->table;
322 my $a_table = asset::copy->table;
324 my $idlist = 1 if ($self->api_name =~/id_list/o);
326 my $select = <<" SQL";
329 JOIN $a_table a ON (h.current_copy = a.id)
331 AND h.capture_time IS NULL
332 AND h.cancel_time IS NULL
333 ORDER BY h.request_time ASC
338 my $sth = action::survey->db_Main->prepare_cached($select);
342 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
344 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
349 __PACKAGE__->register_method(
350 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
354 "Returns the hold ids for a specific library's pull list.",
355 [ [org_unit => "The library's org id", "number"],
356 [limit => 'An optional page size, defaults to 10', 'number'],
357 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
359 ['A list of holds for the stated library to pull for', 'array']
361 method => 'hold_pull_list',
363 __PACKAGE__->register_method(
364 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
368 "Returns the holds for a specific library's pull list.",
369 [ [org_unit => "The library's org id", "number"],
370 [limit => 'An optional page size, defaults to 10', 'number'],
371 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
373 ['A list of holds for the stated library to pull for', 'array']
375 method => 'hold_pull_list',
378 sub find_optional_surveys {
383 return undef unless ($ou);
384 my $s_table = action::survey->table;
386 my $select = <<" SQL";
389 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
390 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
391 AND s.required IS FALSE;
394 my $sth = action::survey->db_Main->prepare_cached($select);
397 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
401 __PACKAGE__->register_method(
402 api_name => 'open-ils.storage.action.survey.optional',
405 method => 'find_optional_surveys',
408 sub find_required_surveys {
413 return undef unless ($ou);
414 my $s_table = action::survey->table;
416 my $select = <<" SQL";
419 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
420 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
421 AND s.required IS TRUE;
424 my $sth = action::survey->db_Main->prepare_cached($select);
427 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
431 __PACKAGE__->register_method(
432 api_name => 'open-ils.storage.action.survey.required',
435 method => 'find_required_surveys',
438 sub find_usr_summary_surveys {
443 return undef unless ($ou);
444 my $s_table = action::survey->table;
446 my $select = <<" SQL";
449 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
450 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
451 AND s.usr_summary IS TRUE;
454 my $sth = action::survey->db_Main->prepare_cached($select);
457 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
461 __PACKAGE__->register_method(
462 api_name => 'open-ils.storage.action.survey.usr_summary',
465 method => 'find_usr_summary_surveys',
474 my $overbill = shift;
476 local $OpenILS::Application::Storage::WRITE = 1;
480 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
482 push @circs, overdue_circs($grace);
485 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
487 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
491 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
492 $log->debug("Cleaning up after previous transaction\n");
493 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
495 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
496 $log->info("Processing circ ".$c->id."...\n");
499 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
501 my $due = $due_dt->epoch;
503 my $fine_interval = interval_to_seconds( $c->fine_interval );
505 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
507 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
508 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
511 $due -= ($due % $fine_interval) + $tz_offset_s;
512 $now -= ($now % $fine_interval) + $tz_offset_s;
516 "ARG! Overdue circulation ".$c->id.
517 " for item ".$c->target_copy.
518 " (user ".$c->usr.").\n".
519 "\tItem was due on or before: ".localtime($due)."\n");
521 my @fines = money::billing->search_where(
522 { xact => $c->id, billing_type => 'Overdue materials' },
523 { order_by => 'billing_ts DESC'}
527 my $fine = $fines[$f_idx] if (@fines);
529 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
532 my $current_fine_total = 0;
533 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
537 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
538 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
540 $log->info( "Potential first billing for circ ".$c->id );
544 if (my $h = $hoo{$c->circ_lib}) {
546 $log->info( "Circ lib has an hours-of-operation entry" );
547 # find the day after the due date...
548 $due_dt = $due_dt->add( days => 1 );
550 # get the day of the week for that day...
551 my $dow = $due_dt->day_of_week_0;
552 my $dow_open = "dow_${dow}_open";
553 my $dow_close = "dow_${dow}_close";
556 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
557 # if the circ lib is closed, add a day to the grace period...
560 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
561 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
563 $due_dt = $due_dt->add( days => 1 );
564 $dow = $due_dt->day_of_week_0;
565 $dow_open = "dow_${dow}_open";
566 $dow_close = "dow_${dow}_close";
570 # and check for up to a week
571 last if ($count > 6);
578 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
579 if ($pending_fine_count < 1 + $grace) {
580 $client->respond( "\tNo fines to create. " );
581 if ($grace && $now < $due + $fine_interval * $grace) {
582 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
583 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
585 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
590 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
592 my $recuring_fine = int($c->recuring_fine * 100);
593 my $max_fine = int($c->max_fine * 100);
595 my ($latest_billing_ts, $latest_amount) = ('',0);
596 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
598 if ($current_fine_total >= $max_fine) {
599 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
601 "\tMaximum fine level of ".$c->max_fine.
602 " reached for this circulation.\n".
603 "\tNo more fines will be generated.\n" );
607 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
609 my $dow = $billing_ts->day_of_week_0();
610 my $dow_open = "dow_${dow}_open";
611 my $dow_close = "dow_${dow}_close";
613 if (my $h = $hoo{$c->circ_lib}) {
614 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
617 my $timestamptz = $billing_ts->strftime('%FT%T%z');
618 my @cl = actor::org_unit::closed_date->search_where(
619 { close_start => { '<=' => $timestamptz },
620 close_end => { '>=' => $timestamptz },
621 org_unit => $c->circ_lib }
625 $current_fine_total += $recuring_fine;
626 $latest_amount += $recuring_fine;
627 $latest_billing_ts = $timestamptz;
629 money::billing->create(
631 note => "System Generated Overdue Fine",
632 billing_type => "Overdue materials",
633 amount => sprintf('%0.2f', $recuring_fine/100),
634 billing_ts => $timestamptz,
640 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
641 if ($latest_billing_ts and $latest_amount);
643 $self->method_lookup('open-ils.storage.transaction.commit')->run;
646 'open-ils.penalty.patron_penalty.calculate',
647 { patron => $c->usr->to_fieldmapper,
655 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
656 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
657 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
658 throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
662 __PACKAGE__->register_method(
663 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
666 method => 'generate_fines',
671 sub new_hold_copy_targeter {
674 my $check_expire = shift;
675 my $one_hold = shift;
677 local $OpenILS::Application::Storage::WRITE = 1;
683 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
684 } elsif ( $check_expire ) {
686 # what's the retarget time threashold?
688 $check_expire ||= '12h';
689 $check_expire = interval_to_seconds( $check_expire );
691 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
694 my $expire_threshold = sprintf(
695 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
696 $year, $mon, $mday, $hour, $min, $sec
699 # find all the holds holds needing retargeting
700 $holds = [ action::hold_request->search_where(
701 { capture_time => undef,
702 fulfillment_time => undef,
703 cancel_time => undef,
704 prev_check_time => { '<=' => $expire_threshold },
706 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
708 # find all the holds holds needing first time targeting
709 push @$holds, action::hold_request->search(
710 capture_time => undef,
711 fulfillment_time => undef,
712 prev_check_time => undef,
713 cancel_time => undef,
714 { order_by => 'selection_depth DESC, request_time' } );
717 # find all the holds holds needing first time targeting ONLY
718 $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' } ) ];
727 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
730 my @closed = actor::org_unit::closed_date->search_where(
731 { close_start => { '<=', 'today' },
732 close_end => { '>=', 'today' } }
738 for my $hold (@$holds) {
740 #first, re-fetch the hold, to make sure it's not captured already
741 $hold = action::hold_request->retrieve( $hold->id );
742 die "OK\n" if ($hold->capture_time);
744 #start a transaction if needed
745 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
746 $log->debug("Cleaning up after previous transaction\n");
747 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
749 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
750 $log->info("Processing hold ".$hold->id."...\n");
752 # remove old auto-targeting maps
753 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
754 $_->delete for (@oldmaps);
759 # find filters for MR holds
760 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
762 # find all the potential copies
763 if ($hold->hold_type eq 'M') {
766 metabib::record_descriptor
768 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
769 ( $types ? (item_type => [split '', $types]) : () ),
770 ( $formats ? (item_form => [split '', $formats]) : () ),
771 ( $lang ? (item_lang => $lang) : () ),
775 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
776 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
778 for my $cn ( @{ $rtree->call_numbers } ) {
780 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
783 } elsif ($hold->hold_type eq 'T') {
785 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
786 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
789 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
793 for my $cn ( @{ $rtree->call_numbers } ) {
795 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
797 } elsif ($hold->hold_type eq 'V') {
799 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
800 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
803 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
805 } elsif ($hold->hold_type eq 'C') {
807 $all_copies = [asset::copy->retrieve($hold->target)];
811 @$all_copies = grep { isTrue($_->status->holdable) &&
812 isTrue($_->location->holdable) &&
816 # let 'em know we're still working
817 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
819 # if we have no copies ...
820 if (!ref $all_copies || !@$all_copies) {
821 $log->info("\tNo copies available for targeting at all!\n");
822 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
824 $hold->update( { prev_check_time => 'today' } );
825 $self->method_lookup('open-ils.storage.transaction.commit')->run;
829 my $copy_count = @$all_copies;
831 # map the potentials, so that we can pick up checkins
832 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
833 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
835 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
838 for my $c (@$all_copies) {
840 next if ($c->id == $hold->current_copy);
843 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
845 # target of another hold
846 next if (action::hold_request
848 { current_copy => $c->id,
849 fulfillment_time => undef,
850 cancel_time => undef,
855 # we passed all three, keep it
856 push @good_copies, $c if ($c);
857 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
860 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
862 my $old_best = $hold->current_copy;
863 $hold->update({ current_copy => undef }) if ($old_best);
865 if (!scalar(@good_copies)) {
866 $log->info("\tNo (non-current) copies eligible to fill the hold.");
869 grep { $old_best eq $_ } @$all_copies &&
870 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
872 # the old copy is still available
873 $log->debug("\tPushing current_copy back onto the targeting list");
874 push @good_copies, $old_best;
876 # oops, old copy is not available
877 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
878 $hold->update( { prev_check_time => 'today' } );
879 $self->method_lookup('open-ils.storage.transaction.commit')->run;
880 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
885 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
890 $_->circ_lib == $hold->pickup_lib
894 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
896 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
897 my $best = choose_nearest_copy($hold, $prox_list);
898 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
901 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
902 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
904 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
906 $best = choose_nearest_copy($hold, $prox_list);
909 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
911 # hold wasn't fulfilled, record the fact
913 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
914 action::unfulfilled_hold_list->create(
915 { hold => ''.$hold->id,
916 current_copy => ''.$old_best->id,
917 circ_lib => ''.$old_best->circ_lib,
922 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
923 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
925 $hold->update( { prev_check_time => 'now' } );
926 $log->info( "\tThere were no targetable copies for the hold" );
929 $self->method_lookup('open-ils.storage.transaction.commit')->run;
930 $log->info("\tProcessing of hold ".$hold->id." complete.");
934 old_target => ($old_best ? $old_best->id : undef),
935 eligible_copies => $copy_count,
936 target => ($best ? $best->id : undef) };
941 $log->error("Processing of hold failed: $e");
942 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
943 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
950 __PACKAGE__->register_method(
951 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
953 method => 'new_hold_copy_targeter',
958 my %cache = (titles => {}, cns => {});
959 sub hold_copy_targeter {
962 my $check_expire = shift;
963 my $one_hold = shift;
965 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
966 $self->{user_filter}->connect;
967 $self->{client} = $client;
970 $check_expire ||= '12h';
971 $check_expire = interval_to_seconds( $check_expire );
973 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
976 my $expire_threshold = sprintf(
977 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
978 $year, $mon, $mday, $hour, $min, $sec
982 $statuses ||= [ config::copy_status->search(holdable => 't') ];
984 $locations ||= [ asset::copy_location->search(holdable => 't') ];
988 %cache = (titles => {}, cns => {});
992 $holds = [ action::hold_request->search(id => $one_hold) ];
994 $holds = [ action::hold_request->search_where(
995 { capture_time => undef,
996 prev_check_time => { '<=' => $expire_threshold },
998 { order_by => 'request_time,prev_check_time' } ) ];
999 push @$holds, action::hold_request->search_where(
1000 { capture_time => undef,
1001 prev_check_time => undef,
1003 { order_by => 'request_time' } );
1005 } catch Error with {
1007 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1010 for my $hold (@$holds) {
1012 #action::hold_request->db_Main->begin_work;
1013 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1014 $client->respond("Cleaning up after previous transaction\n");
1015 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1017 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1018 $client->respond("Processing hold ".$hold->id."...\n");
1022 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1023 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1025 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1026 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1028 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1029 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1031 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1033 unless (ref $copies || !@$copies) {
1034 $client->respond("\tNo copies available for targeting at all!\n");
1038 for my $c (@$copies) {
1039 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1040 push @good_copies, $c if ($c);
1043 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1045 my $old_best = $hold->current_copy;
1046 $hold->update({ current_copy => undef });
1048 if (!scalar(@good_copies)) {
1049 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1050 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1051 $client->respond("\tPushing current_copy back onto the targeting list\n");
1052 push @good_copies, asset::copy->retrieve( $old_best );
1054 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1060 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1061 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1063 my $best = choose_nearest_copy($hold, $prox_list);
1066 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1067 $best = choose_nearest_copy($hold, $prox_list);
1071 # hold wasn't fulfilled, record the fact
1073 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1074 action::unfulfilled_hold_list->create(
1075 { hold => ''.$hold->id,
1076 current_copy => ''.$old_best->id,
1077 circ_lib => ''.$old_best->circ_lib,
1082 $hold->update( { current_copy => ''.$best->id } );
1083 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1086 $hold->update( { prev_check_time => 'now' } );
1087 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1089 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1090 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1092 #action::hold_request->dbi_commit;
1096 $log->error("Processing of hold failed: $e");
1097 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1098 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1099 #action::hold_request->dbi_rollback;
1103 $self->{user_filter}->disconnect;
1104 $self->{user_filter}->finish;
1105 delete $$self{user_filter};
1108 __PACKAGE__->register_method(
1109 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1112 method => 'hold_copy_targeter',
1116 sub copy_hold_capture {
1121 if (!defined($cps)) {
1123 $cps = [ asset::copy->search( id => $hold->target ) ];
1124 } catch Error with {
1126 die "Could not retrieve initial volume list:\n\n$e\n";
1130 my @copies = grep { $_->holdable } @$cps;
1132 for (my $i = 0; $i < @$cps; $i++) {
1133 next unless $$cps[$i];
1135 my $cn = $cache{cns}{$copies[$i]->call_number};
1136 my $rec = $cache{titles}{$cn->record};
1137 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1138 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1139 $copies[$i] = undef if (
1141 !$self->{user_filter}->request(
1142 'open-ils.circ.permit_hold',
1143 $hold->to_fieldmapper, do {
1144 my $cp_fm = $copies[$i]->to_fieldmapper;
1145 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1146 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1147 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1150 { title => $rec->to_fieldmapper,
1151 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1152 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1155 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1158 @copies = grep { $_ } @copies;
1160 my $count = @copies;
1162 return unless ($count);
1164 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1167 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1168 for my $c (@copies) {
1169 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1171 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1177 sub choose_nearest_copy {
1179 my $prox_list = shift;
1181 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1182 next unless (ref $$prox_list[$p]);
1184 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1185 next unless (@capturable);
1187 my $rand = int(rand(scalar(@capturable)));
1188 while (my ($c) = splice(@capturable,$rand)) {
1189 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1190 { title => $c->call_number->record->to_fieldmapper,
1191 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1192 patron => $hold->usr->to_fieldmapper,
1193 copy => $c->to_fieldmapper,
1194 requestor => $hold->requestor->to_fieldmapper,
1195 request_lib => $hold->request_lib->to_fieldmapper,
1198 last unless(@capturable);
1199 $rand = int(rand(scalar(@capturable)));
1207 sub create_prox_list {
1213 for my $cp (@$copies) {
1214 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1215 next unless (defined($prox));
1216 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1217 push @{$prox_list[$prox]}, $cp;
1222 sub volume_hold_capture {
1227 if (!defined($vols)) {
1229 $vols = [ asset::call_number->search( id => $hold->target ) ];
1230 $cache{cns}{$_->id} = $_ for (@$vols);
1231 } catch Error with {
1233 die "Could not retrieve initial volume list:\n\n$e\n";
1237 my @v_ids = map { $_->id } @$vols;
1241 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1243 } catch Error with {
1245 warn "Could not retrieve copy list:\n\n$e\n";
1248 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1251 sub title_hold_capture {
1256 if (!defined($titles)) {
1258 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1259 $cache{titles}{$_->id} = $_ for (@$titles);
1260 } catch Error with {
1262 die "Could not retrieve initial title list:\n\n$e\n";
1266 my @t_ids = map { $_->id } @$titles;
1269 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1271 } catch Error with {
1273 warn "Could not retrieve volume list:\n\n$e\n";
1276 $cache{cns}{$_->id} = $_ for (@$cn_list);
1278 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1281 sub metarecord_hold_capture {
1287 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1289 } catch Error with {
1291 die "Could not retrieve initial title list:\n\n$e\n";
1295 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1297 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1299 } catch Error with {
1301 die "Could not retrieve format-pruned title list:\n\n$e\n";
1305 $cache{titles}{$_->id} = $_ for (@$titles);
1306 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);