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;
11 use OpenILS::Utils::Penalty;
15 return 1 if ($v == 1);
16 return 1 if ($v =~ /^t/io);
17 return 1 if ($v =~ /^y/io);
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
24 sub open_noncat_circs {
29 my $a = action::non_cataloged_circulation->table;
30 my $c = config::non_cataloged_type->table;
35 JOIN $c c ON (a.item_type = c.id)
36 WHERE a.circ_time + c.circ_duration > current_timestamp
40 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
42 __PACKAGE__->register_method(
43 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
46 method => 'open_noncat_circs',
50 sub ou_hold_requests {
55 my $h_table = action::hold_request->table;
56 my $c_table = asset::copy->table;
57 my $o_table = actor::org_unit->table;
62 JOIN $c_table cp ON (cp.id = h.current_copy)
63 JOIN $o_table ou ON (ou.id = cp.circ_lib)
65 AND h.capture_time IS NULL
66 AND h.cancel_time IS NULL
67 AND (h.expire_time IS NULL OR h.expire_time > NOW())
68 ORDER BY h.request_time
71 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
74 $client->respond($_) for (
77 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
81 } @{ $sth->fetchall_arrayref }
85 __PACKAGE__->register_method(
86 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
90 method => 'ou_hold_requests',
97 my $c_t = action::circulation->table;
100 $grace = " - ($grace * (fine_interval))";
108 WHERE stop_fines IS NULL
109 AND due_date < ( CURRENT_TIMESTAMP $grace)
112 my $sth = action::circulation->db_Main->prepare_cached($sql);
115 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
119 sub complete_reshelving {
124 local $OpenILS::Application::Storage::WRITE = 1;
126 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
127 unless (interval_to_seconds( $window ));
129 my $setting = actor::org_unit_setting->table;
130 my $circ = action::circulation->table;
131 my $cp = asset::copy->table;
138 FROM (SELECT cp.id, MAX(circ.checkin_time)
140 JOIN $circ circ ON (circ.target_copy = cp.id)
141 LEFT JOIN $setting setting
142 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
143 WHERE circ.checkin_time IS NOT NULL
146 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL)
151 LEFT JOIN $setting setting
152 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
153 LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
155 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
159 my $sth = action::circulation->db_Main->prepare_cached($sql);
160 $sth->execute($window, $window);
165 __PACKAGE__->register_method(
166 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
169 method => 'complete_reshelving',
172 sub mark_longoverdue {
177 local $OpenILS::Application::Storage::WRITE = 1;
179 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
180 unless (interval_to_seconds( $window ));
182 my $setting = actor::org_unit_setting->table;
183 my $circ = action::circulation->table;
187 SET stop_fines = 'LONGOVERDUE',
188 stop_fines_time = now()
192 LEFT JOIN $setting setting
193 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
194 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
195 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
199 my $sth = action::circulation->db_Main->prepare_cached($sql);
200 $sth->execute($window);
205 __PACKAGE__->register_method(
206 api_name => 'open-ils.storage.action.circulation.long_overdue',
209 method => 'mark_longoverdue',
212 sub auto_thaw_frozen_holds {
216 local $OpenILS::Application::Storage::WRITE = 1;
218 my $holds = action::hold_request->table;
220 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
222 my $sth = action::hold_request->db_Main->prepare_cached($sql);
228 __PACKAGE__->register_method(
229 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
233 method => 'auto_thaw_frozen_holds',
239 my $grace = shift || '';
241 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
246 __PACKAGE__->register_method(
247 api_name => 'open-ils.storage.action.circulation.overdue',
250 method => 'grab_overdue',
258 my $limit = int(shift()) || 10;
259 my $age = shift() || '0 seconds';
261 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
263 FROM action.hold_request h
264 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
265 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
266 WHERE hm.target_copy = ?
267 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
268 AND h.capture_time IS NULL
269 AND h.cancel_time IS NULL
270 AND (h.expire_time IS NULL OR h.expire_time > NOW())
271 AND h.frozen IS FALSE
274 h.selection_depth DESC,
279 $client->respond( $_ ) for ( @$ids );
282 __PACKAGE__->register_method(
283 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
286 method => 'nearest_hold',
289 sub next_resp_group_id {
293 # XXX This is not replication safe!!!
295 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
296 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
300 __PACKAGE__->register_method(
301 api_name => 'open-ils.storage.action.survey_response.next_group_id',
303 method => 'next_resp_group_id',
306 sub patron_circ_summary {
311 return undef unless ($id);
312 my $c_table = action::circulation->table;
313 my $b_table = money::billing->table;
315 $log->debug("Retrieving patron summary for id $id", DEBUG);
317 my $select = <<" SQL";
318 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
320 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
322 AND c.xact_finish IS NULL
324 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
325 OR c.stop_fines IS NULL
329 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
331 __PACKAGE__->register_method(
332 api_name => 'open-ils.storage.action.circulation.patron_summary',
334 method => 'patron_circ_summary',
337 #XXX Fix stored proc calls
338 sub find_local_surveys {
343 return undef unless ($ou);
344 my $s_table = action::survey->table;
346 my $select = <<" SQL";
349 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
350 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
353 my $sth = action::survey->db_Main->prepare_cached($select);
356 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
360 __PACKAGE__->register_method(
361 api_name => 'open-ils.storage.action.survey.all',
364 method => 'find_local_surveys',
367 #XXX Fix stored proc calls
368 sub find_opac_surveys {
373 return undef unless ($ou);
374 my $s_table = action::survey->table;
376 my $select = <<" SQL";
379 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
380 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
384 my $sth = action::survey->db_Main->prepare_cached($select);
387 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
391 __PACKAGE__->register_method(
392 api_name => 'open-ils.storage.action.survey.opac',
395 method => 'find_opac_surveys',
402 my $limit = shift || 10;
403 my $offset = shift || 0;
405 return undef unless ($ou);
406 my $h_table = action::hold_request->table;
407 my $a_table = asset::copy->table;
409 my $idlist = 1 if ($self->api_name =~/id_list/o);
411 my $status_filter = '';
412 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
414 my $select = <<" SQL";
417 JOIN $a_table a ON (h.current_copy = a.id)
419 AND h.capture_time IS NULL
420 AND h.cancel_time IS NULL
421 AND (h.expire_time IS NULL OR h.expire_time > NOW())
423 ORDER BY h.request_time ASC
428 my $sth = action::survey->db_Main->prepare_cached($select);
432 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
434 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
439 __PACKAGE__->register_method(
440 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
444 "Returns the hold ids for a specific library's pull list.",
445 [ [org_unit => "The library's org id", "number"],
446 [limit => 'An optional page size, defaults to 10', 'number'],
447 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
449 ['A list of holds for the stated library to pull for', 'array']
451 method => 'hold_pull_list',
453 __PACKAGE__->register_method(
454 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
458 "Returns the holds for a specific library's pull list.",
459 [ [org_unit => "The library's org id", "number"],
460 [limit => 'An optional page size, defaults to 10', 'number'],
461 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
463 ['A list of holds for the stated library to pull for', 'array']
465 method => 'hold_pull_list',
467 __PACKAGE__->register_method(
468 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
472 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
473 [ [org_unit => "The library's org id", "number"],
474 [limit => 'An optional page size, defaults to 10', 'number'],
475 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
477 ['A list of holds for the stated library to pull for', 'array']
479 method => 'hold_pull_list',
481 __PACKAGE__->register_method(
482 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
486 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
487 [ [org_unit => "The library's org id", "number"],
488 [limit => 'An optional page size, defaults to 10', 'number'],
489 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
491 ['A list of holds for the stated library to pull for', 'array']
493 method => 'hold_pull_list',
496 sub find_optional_surveys {
501 return undef unless ($ou);
502 my $s_table = action::survey->table;
504 my $select = <<" SQL";
507 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
508 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
509 AND s.required IS FALSE;
512 my $sth = action::survey->db_Main->prepare_cached($select);
515 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
519 __PACKAGE__->register_method(
520 api_name => 'open-ils.storage.action.survey.optional',
523 method => 'find_optional_surveys',
526 sub find_required_surveys {
531 return undef unless ($ou);
532 my $s_table = action::survey->table;
534 my $select = <<" SQL";
537 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
538 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
539 AND s.required IS TRUE;
542 my $sth = action::survey->db_Main->prepare_cached($select);
545 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
549 __PACKAGE__->register_method(
550 api_name => 'open-ils.storage.action.survey.required',
553 method => 'find_required_surveys',
556 sub find_usr_summary_surveys {
561 return undef unless ($ou);
562 my $s_table = action::survey->table;
564 my $select = <<" SQL";
567 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
568 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
569 AND s.usr_summary IS TRUE;
572 my $sth = action::survey->db_Main->prepare_cached($select);
575 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
579 __PACKAGE__->register_method(
580 api_name => 'open-ils.storage.action.survey.usr_summary',
583 method => 'find_usr_summary_surveys',
592 my $overbill = shift;
594 local $OpenILS::Application::Storage::WRITE = 1;
598 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
600 push @circs, overdue_circs($grace);
603 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
605 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
609 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
610 $log->debug("Cleaning up after previous transaction\n");
611 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
613 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
614 $log->info("Processing circ ".$c->id."...\n");
617 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
619 my $due = $due_dt->epoch;
622 my $fine_interval = $c->fine_interval;
623 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
624 $fine_interval = interval_to_seconds( $fine_interval );
626 if ( $fine_interval >= interval_to_seconds('1d') ) {
628 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
629 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
632 $due -= ($due % $fine_interval) + $tz_offset_s;
633 $now -= ($now % $fine_interval) + $tz_offset_s;
637 "ARG! Overdue circulation ".$c->id.
638 " for item ".$c->target_copy.
639 " (user ".$c->usr.").\n".
640 "\tItem was due on or before: ".localtime($due)."\n");
642 my @fines = money::billing->search_where(
645 billing_ts => { '>' => $c->due_date } },
646 { order_by => 'billing_ts DESC'}
650 my $fine = $fines[$f_idx] if (@fines);
652 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
655 my $current_fine_total = 0;
656 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
660 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
661 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
663 $log->info( "Potential first billing for circ ".$c->id );
667 if (my $h = $hoo{$c->circ_lib}) {
669 $log->info( "Circ lib has an hours-of-operation entry" );
670 # find the day after the due date...
671 $due_dt = $due_dt->add( days => 1 );
673 # get the day of the week for that day...
674 my $dow = $due_dt->day_of_week_0;
675 my $dow_open = "dow_${dow}_open";
676 my $dow_close = "dow_${dow}_close";
679 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
680 # if the circ lib is closed, add a day to the grace period...
683 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
684 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
686 $due_dt = $due_dt->add( days => 1 );
687 $dow = $due_dt->day_of_week_0;
688 $dow_open = "dow_${dow}_open";
689 $dow_close = "dow_${dow}_close";
693 # and check for up to a week
694 last if ($count > 6);
701 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
702 if ($pending_fine_count < 1 + $grace) {
703 $client->respond( "\tNo fines to create. " );
704 if ($grace && $now < $due + $fine_interval * $grace) {
705 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
706 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
708 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
713 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
715 my $recuring_fine = int($c->recuring_fine * 100);
716 my $max_fine = int($c->max_fine * 100);
718 my ($latest_billing_ts, $latest_amount) = ('',0);
719 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
721 if ($current_fine_total >= $max_fine) {
722 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
724 "\tMaximum fine level of ".$c->max_fine.
725 " reached for this circulation.\n".
726 "\tNo more fines will be generated.\n" );
730 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
732 my $dow = $billing_ts->day_of_week_0();
733 my $dow_open = "dow_${dow}_open";
734 my $dow_close = "dow_${dow}_close";
736 if (my $h = $hoo{$c->circ_lib}) {
737 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
740 my $timestamptz = $billing_ts->strftime('%FT%T%z');
741 my @cl = actor::org_unit::closed_date->search_where(
742 { close_start => { '<=' => $timestamptz },
743 close_end => { '>=' => $timestamptz },
744 org_unit => $c->circ_lib }
748 $current_fine_total += $recuring_fine;
749 $latest_amount += $recuring_fine;
750 $latest_billing_ts = $timestamptz;
752 money::billing->create(
754 note => "System Generated Overdue Fine",
755 billing_type => "Overdue materials",
757 amount => sprintf('%0.2f', $recuring_fine/100),
758 billing_ts => $timestamptz,
764 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
765 if ($latest_billing_ts and $latest_amount);
767 $self->method_lookup('open-ils.storage.transaction.commit')->run;
769 if(0) { # caluclate penalties inline. Needs to be tested.
770 OpenILS::Utils::Penalty->calculate_penalties(
771 undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
776 'open-ils.penalty.patron_penalty.calculate',
777 { patron => $c->usr->to_fieldmapper,
786 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
787 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
788 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
789 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
793 __PACKAGE__->register_method(
794 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
797 method => 'generate_fines',
802 sub new_hold_copy_targeter {
805 my $check_expire = shift;
806 my $one_hold = shift;
808 local $OpenILS::Application::Storage::WRITE = 1;
814 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
815 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
816 } elsif ( $check_expire ) {
818 # what's the retarget time threashold?
820 $check_expire ||= '12h';
821 $check_expire = interval_to_seconds( $check_expire );
823 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
826 my $expire_threshold = sprintf(
827 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
828 $year, $mon, $mday, $hour, $min, $sec
831 # find all the holds holds needing retargeting
832 $holds = [ action::hold_request->search_where(
833 { capture_time => undef,
834 fulfillment_time => undef,
835 cancel_time => undef,
837 prev_check_time => { '<=' => $expire_threshold },
839 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
841 # find all the holds holds needing first time targeting
842 push @$holds, action::hold_request->search(
843 capture_time => undef,
844 fulfillment_time => undef,
845 prev_check_time => undef,
847 cancel_time => undef,
848 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
851 # find all the holds holds needing first time targeting ONLY
852 $holds = [ action::hold_request->search(
853 capture_time => undef,
854 fulfillment_time => undef,
855 prev_check_time => undef,
856 cancel_time => undef,
858 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
862 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
865 my @closed = actor::org_unit::closed_date->search_where(
866 { close_start => { '<=', 'now' },
867 close_end => { '>=', 'now' } }
873 for my $hold (@$holds) {
875 #start a transaction if needed
876 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
877 $log->debug("Cleaning up after previous transaction\n");
878 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
880 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
881 $log->info("Processing hold ".$hold->id."...\n");
883 #first, re-fetch the hold, to make sure it's not captured already
884 $hold->remove_from_object_index();
885 $hold = action::hold_request->retrieve( $hold->id );
887 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
889 # remove old auto-targeting maps
890 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
891 $_->delete for (@oldmaps);
893 if ($hold->expire_time) {
894 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
895 $hold->update( { cancel_cause => 1, cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
896 $self->method_lookup('open-ils.storage.transaction.commit')->run;
902 # find filters for MR holds
903 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
905 # find all the potential copies
906 if ($hold->hold_type eq 'M') {
909 metabib::record_descriptor
913 isTrue($_->deleted) ? () : ($_->id)
914 } metabib::metarecord->retrieve($hold->target)->source_records
916 ( $types ? (item_type => [split '', $types]) : () ),
917 ( $formats ? (item_form => [split '', $formats]) : () ),
918 ( $lang ? (item_lang => $lang) : () ),
922 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
923 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
925 for my $cn ( @{ $rtree->call_numbers } ) {
927 asset::copy->search_where(
928 { id => [map {$_->id} @{ $cn->copies }],
930 ) if ($cn && @{ $cn->copies });
933 } elsif ($hold->hold_type eq 'T') {
935 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
936 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
939 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
943 for my $cn ( @{ $rtree->call_numbers } ) {
945 asset::copy->search_where(
946 { id => [map {$_->id} @{ $cn->copies }],
948 ) if ($cn && @{ $cn->copies });
950 } elsif ($hold->hold_type eq 'V') {
952 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
953 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
956 asset::copy->search_where(
957 { id => [map {$_->id} @{ $vtree->copies }],
959 ) if ($vtree && @{ $vtree->copies });
961 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
962 my $_cp = asset::copy->retrieve($hold->target);
963 push @$all_copies, $_cp if $_cp;
967 @$all_copies = grep { isTrue($_->status->holdable) &&
968 isTrue($_->location->holdable) &&
969 isTrue($_->holdable) &&
973 # let 'em know we're still working
974 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
976 # if we have no copies ...
977 if (!ref $all_copies || !@$all_copies) {
978 $log->info("\tNo copies available for targeting at all!\n");
979 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
981 $hold->update( { prev_check_time => 'today', current_copy => undef } );
982 $self->method_lookup('open-ils.storage.transaction.commit')->run;
986 my $copy_count = @$all_copies;
988 # map the potentials, so that we can pick up checkins
989 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
990 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
992 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
995 for my $c (@$all_copies) {
997 next if ($c->id eq $hold->current_copy);
1000 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1002 # target of another hold
1003 next if (action::hold_request
1005 { current_copy => $c->id,
1006 fulfillment_time => undef,
1007 cancel_time => undef,
1012 # we passed all three, keep it
1013 push @good_copies, $c if ($c);
1014 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1017 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1019 my $old_best = $hold->current_copy;
1020 $hold->update({ current_copy => undef }) if ($old_best);
1022 if (!scalar(@good_copies)) {
1023 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1024 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1025 # the old copy is still available
1026 $log->debug("\tPushing current_copy back onto the targeting list");
1027 push @good_copies, $old_best;
1029 # oops, old copy is not available
1030 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1031 $hold->update( { prev_check_time => 'today' } );
1032 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1033 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1038 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1043 $_->circ_lib == $hold->pickup_lib
1047 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1049 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1050 my $best = choose_nearest_copy($hold, $prox_list);
1051 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1054 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1055 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1057 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1059 $best = choose_nearest_copy($hold, $prox_list);
1062 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1064 # hold wasn't fulfilled, record the fact
1066 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1067 action::unfulfilled_hold_list->create(
1068 { hold => ''.$hold->id,
1069 current_copy => ''.$old_best->id,
1070 circ_lib => ''.$old_best->circ_lib,
1075 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1076 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1079 action::hold_request
1081 { current_copy => $old_best->id,
1082 fulfillment_time => undef,
1083 cancel_time => undef,
1087 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1088 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1090 $hold->update( { prev_check_time => 'now' } );
1091 $log->info( "\tThere were no targetable copies for the hold" );
1094 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1095 $log->info("\tProcessing of hold ".$hold->id." complete.");
1098 { hold => $hold->id,
1099 old_target => ($old_best ? $old_best->id : undef),
1100 eligible_copies => $copy_count,
1101 target => ($best ? $best->id : undef) };
1106 $log->error("Processing of hold failed: $e");
1107 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1108 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1115 __PACKAGE__->register_method(
1116 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1118 method => 'new_hold_copy_targeter',
1123 my %cache = (titles => {}, cns => {});
1124 sub hold_copy_targeter {
1127 my $check_expire = shift;
1128 my $one_hold = shift;
1130 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1131 $self->{user_filter}->connect;
1132 $self->{client} = $client;
1135 $check_expire ||= '12h';
1136 $check_expire = interval_to_seconds( $check_expire );
1138 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1141 my $expire_threshold = sprintf(
1142 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1143 $year, $mon, $mday, $hour, $min, $sec
1147 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1149 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1153 %cache = (titles => {}, cns => {});
1157 $holds = [ action::hold_request->search(id => $one_hold) ];
1159 $holds = [ action::hold_request->search_where(
1160 { capture_time => undef,
1161 prev_check_time => { '<=' => $expire_threshold },
1163 { order_by => 'request_time,prev_check_time' } ) ];
1164 push @$holds, action::hold_request->search_where(
1165 { capture_time => undef,
1166 prev_check_time => undef,
1168 { order_by => 'request_time' } );
1170 } catch Error with {
1172 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1175 for my $hold (@$holds) {
1177 #action::hold_request->db_Main->begin_work;
1178 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1179 $client->respond("Cleaning up after previous transaction\n");
1180 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1182 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1183 $client->respond("Processing hold ".$hold->id."...\n");
1187 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1188 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1190 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1191 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1193 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1194 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1196 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1198 unless (ref $copies || !@$copies) {
1199 $client->respond("\tNo copies available for targeting at all!\n");
1203 for my $c (@$copies) {
1204 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1205 push @good_copies, $c if ($c);
1208 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1210 my $old_best = $hold->current_copy;
1211 $hold->update({ current_copy => undef });
1213 if (!scalar(@good_copies)) {
1214 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1215 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1216 $client->respond("\tPushing current_copy back onto the targeting list\n");
1217 push @good_copies, asset::copy->retrieve( $old_best );
1219 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1225 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1226 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1228 my $best = choose_nearest_copy($hold, $prox_list);
1231 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1232 $best = choose_nearest_copy($hold, $prox_list);
1236 # hold wasn't fulfilled, record the fact
1238 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1239 action::unfulfilled_hold_list->create(
1240 { hold => ''.$hold->id,
1241 current_copy => ''.$old_best->id,
1242 circ_lib => ''.$old_best->circ_lib,
1247 $hold->update( { current_copy => ''.$best->id } );
1248 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1251 $hold->update( { prev_check_time => 'now' } );
1252 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1254 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1255 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1257 #action::hold_request->dbi_commit;
1261 $log->error("Processing of hold failed: $e");
1262 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1263 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1264 #action::hold_request->dbi_rollback;
1268 $self->{user_filter}->disconnect;
1269 $self->{user_filter}->finish;
1270 delete $$self{user_filter};
1273 __PACKAGE__->register_method(
1274 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1277 method => 'hold_copy_targeter',
1281 sub copy_hold_capture {
1286 if (!defined($cps)) {
1288 $cps = [ asset::copy->search( id => $hold->target ) ];
1289 } catch Error with {
1291 die "Could not retrieve initial volume list:\n\n$e\n";
1295 my @copies = grep { $_->holdable } @$cps;
1297 for (my $i = 0; $i < @$cps; $i++) {
1298 next unless $$cps[$i];
1300 my $cn = $cache{cns}{$copies[$i]->call_number};
1301 my $rec = $cache{titles}{$cn->record};
1302 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1303 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1304 $copies[$i] = undef if (
1306 !$self->{user_filter}->request(
1307 'open-ils.circ.permit_hold',
1308 $hold->to_fieldmapper, do {
1309 my $cp_fm = $copies[$i]->to_fieldmapper;
1310 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1311 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1312 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1315 { title => $rec->to_fieldmapper,
1316 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1317 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1320 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1323 @copies = grep { $_ } @copies;
1325 my $count = @copies;
1327 return unless ($count);
1329 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1332 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1333 for my $c (@copies) {
1334 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1336 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1342 sub choose_nearest_copy {
1344 my $prox_list = shift;
1346 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1347 next unless (ref $$prox_list[$p]);
1349 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1350 next unless (@capturable);
1352 my $rand = int(rand(scalar(@capturable)));
1353 while (my ($c) = splice(@capturable,$rand)) {
1354 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1355 { title => $c->call_number->record->to_fieldmapper,
1356 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1357 patron => $hold->usr->to_fieldmapper,
1358 copy => $c->to_fieldmapper,
1359 requestor => $hold->requestor->to_fieldmapper,
1360 request_lib => $hold->request_lib->to_fieldmapper,
1361 pickup_lib => $hold->pickup_lib->id,
1365 last unless(@capturable);
1366 $rand = int(rand(scalar(@capturable)));
1371 sub create_prox_list {
1377 for my $cp (@$copies) {
1378 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1379 next unless (defined($prox));
1380 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1381 push @{$prox_list[$prox]}, $cp;
1386 sub volume_hold_capture {
1391 if (!defined($vols)) {
1393 $vols = [ asset::call_number->search( id => $hold->target ) ];
1394 $cache{cns}{$_->id} = $_ for (@$vols);
1395 } catch Error with {
1397 die "Could not retrieve initial volume list:\n\n$e\n";
1401 my @v_ids = map { $_->id } @$vols;
1405 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1407 } catch Error with {
1409 warn "Could not retrieve copy list:\n\n$e\n";
1412 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1415 sub title_hold_capture {
1420 if (!defined($titles)) {
1422 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1423 $cache{titles}{$_->id} = $_ for (@$titles);
1424 } catch Error with {
1426 die "Could not retrieve initial title list:\n\n$e\n";
1430 my @t_ids = map { $_->id } @$titles;
1433 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1435 } catch Error with {
1437 warn "Could not retrieve volume list:\n\n$e\n";
1440 $cache{cns}{$_->id} = $_ for (@$cn_list);
1442 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1445 sub metarecord_hold_capture {
1451 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1453 } catch Error with {
1455 die "Could not retrieve initial title list:\n\n$e\n";
1459 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1461 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1463 } catch Error with {
1465 die "Could not retrieve format-pruned title list:\n\n$e\n";
1469 $cache{titles}{$_->id} = $_ for (@$titles);
1470 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);