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',
44 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',
96 my $upper_interval = shift || '1 millennium';
98 my $c_t = action::circulation->table;
100 if ($grace && $grace =~ /^\d+$/o) {
101 $grace = " - ($grace * (fine_interval))";
109 WHERE stop_fines IS NULL
110 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 AND fine_interval < ?::INTERVAL
114 my $sth = action::circulation->db_Main->prepare_cached($sql);
115 $sth->execute($upper_interval);
117 my @circs = map { action::circulation->construct($_) } $sth->fetchall_hash;
119 $c_t = booking::reservation->table;
123 WHERE return_time IS NULL
124 AND end_time < ( CURRENT_TIMESTAMP $grace)
125 AND fine_interval IS NOT NULL
126 AND cancel_time IS NULL
129 $sth = action::circulation->db_Main->prepare_cached($sql);
132 push @circs, map { booking::reservation->construct($_) } $sth->fetchall_hash;
137 sub complete_reshelving {
142 local $OpenILS::Application::Storage::WRITE = 1;
144 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
145 unless (interval_to_seconds( $window ));
147 my $setting = actor::org_unit_setting->table;
148 my $circ = action::circulation->table;
149 my $cp = asset::copy->table;
150 my $atc = action::transit_copy->table;
157 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
159 JOIN $circ circ ON (circ.target_copy = cp.id)
160 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
161 LEFT JOIN $setting setting
162 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
163 WHERE circ.checkin_time IS NOT NULL
167 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
168 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
170 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
171 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
177 LEFT JOIN $setting setting
178 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
179 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
182 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
185 my $sth = action::circulation->db_Main->prepare_cached($sql);
186 $sth->execute($window, $window, $window);
191 __PACKAGE__->register_method(
192 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
195 method => 'complete_reshelving',
198 sub mark_longoverdue {
203 local $OpenILS::Application::Storage::WRITE = 1;
205 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
206 unless (interval_to_seconds( $window ));
208 my $setting = actor::org_unit_setting->table;
209 my $circ = action::circulation->table;
213 SET stop_fines = 'LONGOVERDUE',
214 stop_fines_time = now()
218 LEFT JOIN $setting setting
219 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
220 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
221 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
225 my $sth = action::circulation->db_Main->prepare_cached($sql);
226 $sth->execute($window);
231 __PACKAGE__->register_method(
232 api_name => 'open-ils.storage.action.circulation.long_overdue',
235 method => 'mark_longoverdue',
238 sub auto_thaw_frozen_holds {
242 local $OpenILS::Application::Storage::WRITE = 1;
244 my $holds = action::hold_request->table;
246 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
248 my $sth = action::hold_request->db_Main->prepare_cached($sql);
254 __PACKAGE__->register_method(
255 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
259 method => 'auto_thaw_frozen_holds',
265 my $grace = shift || '';
267 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
272 __PACKAGE__->register_method(
273 api_name => 'open-ils.storage.action.circulation.overdue',
276 method => 'grab_overdue',
284 my $limit = int(shift()) || 10;
285 my $age = shift() || '0 seconds';
288 my $holdsort = isTrue($fifo) ?
289 "CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.request_time, h.selection_depth DESC, p.prox " :
290 "p.prox, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
292 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
294 FROM action.hold_request h
295 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
296 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
297 WHERE hm.target_copy = ?
298 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
299 AND h.capture_time IS NULL
300 AND h.cancel_time IS NULL
301 AND (h.expire_time IS NULL OR h.expire_time > NOW())
302 AND h.frozen IS FALSE
307 $client->respond( $_ ) for ( @$ids );
310 __PACKAGE__->register_method(
311 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
314 method => 'nearest_hold',
317 sub next_resp_group_id {
321 # XXX This is not replication safe!!!
323 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
324 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
328 __PACKAGE__->register_method(
329 api_name => 'open-ils.storage.action.survey_response.next_group_id',
331 method => 'next_resp_group_id',
334 sub patron_circ_summary {
339 return undef unless ($id);
340 my $c_table = action::circulation->table;
341 my $b_table = money::billing->table;
343 $log->debug("Retrieving patron summary for id $id", DEBUG);
345 my $select = <<" SQL";
346 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
348 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
350 AND c.xact_finish IS NULL
352 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
353 OR c.stop_fines IS NULL
357 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
359 __PACKAGE__->register_method(
360 api_name => 'open-ils.storage.action.circulation.patron_summary',
362 method => 'patron_circ_summary',
365 #XXX Fix stored proc calls
366 sub find_local_surveys {
371 return undef unless ($ou);
372 my $s_table = action::survey->table;
374 my $select = <<" SQL";
377 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
378 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
381 my $sth = action::survey->db_Main->prepare_cached($select);
384 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
388 __PACKAGE__->register_method(
389 api_name => 'open-ils.storage.action.survey.all',
392 method => 'find_local_surveys',
395 #XXX Fix stored proc calls
396 sub find_opac_surveys {
401 return undef unless ($ou);
402 my $s_table = action::survey->table;
404 my $select = <<" SQL";
407 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
408 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
412 my $sth = action::survey->db_Main->prepare_cached($select);
415 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
419 __PACKAGE__->register_method(
420 api_name => 'open-ils.storage.action.survey.opac',
423 method => 'find_opac_surveys',
430 my $limit = shift || 10;
431 my $offset = shift || 0;
433 return undef unless ($ou);
434 my $h_table = action::hold_request->table;
435 my $a_table = asset::copy->table;
436 my $ord_table = asset::copy_location_order->table;
438 my $idlist = 1 if ($self->api_name =~/id_list/o);
439 my $count = 1 if ($self->api_name =~/count$/o);
441 my $status_filter = '';
442 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
444 my $select = <<" SQL";
447 JOIN $a_table a ON (h.current_copy = a.id)
448 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
450 AND h.capture_time IS NULL
451 AND h.cancel_time IS NULL
452 AND (h.expire_time IS NULL OR h.expire_time > NOW())
454 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
463 JOIN $a_table a ON (h.current_copy = a.id)
465 AND h.capture_time IS NULL
466 AND h.cancel_time IS NULL
467 AND (h.expire_time IS NULL OR h.expire_time > NOW())
472 my $sth = action::survey->db_Main->prepare_cached($select);
476 $client->respond( $sth->fetchall_arrayref()->[0][0] );
478 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
480 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
485 __PACKAGE__->register_method(
486 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
490 "Returns a count of holds for a specific library's pull list.",
491 [ [org_unit => "The library's org id", "number"] ],
492 ['A count of holds for the stated library to pull ', 'number']
494 method => 'hold_pull_list',
496 __PACKAGE__->register_method(
497 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
501 "Returns a status filtered count of holds for a specific library's pull list.",
502 [ [org_unit => "The library's org id", "number"] ],
503 ['A status filtered count of holds for the stated library to pull ', 'number']
505 method => 'hold_pull_list',
507 __PACKAGE__->register_method(
508 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
512 "Returns the hold ids for a specific library's pull list.",
513 [ [org_unit => "The library's org id", "number"],
514 [limit => 'An optional page size, defaults to 10', 'number'],
515 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
517 ['A list of holds for the stated library to pull for', 'array']
519 method => 'hold_pull_list',
521 __PACKAGE__->register_method(
522 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
526 "Returns the holds for a specific library's pull list.",
527 [ [org_unit => "The library's org id", "number"],
528 [limit => 'An optional page size, defaults to 10', 'number'],
529 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
531 ['A list of holds for the stated library to pull for', 'array']
533 method => 'hold_pull_list',
535 __PACKAGE__->register_method(
536 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
540 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
541 [ [org_unit => "The library's org id", "number"],
542 [limit => 'An optional page size, defaults to 10', 'number'],
543 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
545 ['A list of holds for the stated library to pull for', 'array']
547 method => 'hold_pull_list',
549 __PACKAGE__->register_method(
550 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
554 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
555 [ [org_unit => "The library's org id", "number"],
556 [limit => 'An optional page size, defaults to 10', 'number'],
557 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
559 ['A list of holds for the stated library to pull for', 'array']
561 method => 'hold_pull_list',
564 sub find_optional_surveys {
569 return undef unless ($ou);
570 my $s_table = action::survey->table;
572 my $select = <<" SQL";
575 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
576 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
577 AND s.required IS FALSE;
580 my $sth = action::survey->db_Main->prepare_cached($select);
583 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
587 __PACKAGE__->register_method(
588 api_name => 'open-ils.storage.action.survey.optional',
591 method => 'find_optional_surveys',
594 sub find_required_surveys {
599 return undef unless ($ou);
600 my $s_table = action::survey->table;
602 my $select = <<" SQL";
605 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
606 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
607 AND s.required IS TRUE;
610 my $sth = action::survey->db_Main->prepare_cached($select);
613 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
617 __PACKAGE__->register_method(
618 api_name => 'open-ils.storage.action.survey.required',
621 method => 'find_required_surveys',
624 sub find_usr_summary_surveys {
629 return undef unless ($ou);
630 my $s_table = action::survey->table;
632 my $select = <<" SQL";
635 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
636 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
637 AND s.usr_summary IS TRUE;
640 my $sth = action::survey->db_Main->prepare_cached($select);
643 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
647 __PACKAGE__->register_method(
648 api_name => 'open-ils.storage.action.survey.usr_summary',
651 method => 'find_usr_summary_surveys',
654 sub seconds_to_interval_hash {
655 my $interval = shift;
656 my $limit = shift || 's';
657 $limit =~ s/^(.)/$1/o;
661 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
662 my ($year, $month, $week, $day, $hour, $minute, $second) =
663 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
665 if ($y = int($interval / (60 * 60 * 24 * 365))) {
667 $ym = $interval % (60 * 60 * 24 * 365);
671 return %output if ($limit eq 'y');
673 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
674 $output{$month} = $M;
675 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
679 return %output if ($limit eq 'M');
681 if ($w = int($Mm / 604800)) {
687 return %output if ($limit eq 'w');
689 if ($d = int($wm / 86400)) {
695 return %output if ($limit eq 'd');
697 if ($h = int($dm / 3600)) {
703 return %output if ($limit eq 'h');
705 if ($m = int($hm / 60)) {
706 $output{$minute} = $m;
711 return %output if ($limit eq 'm');
714 $output{$second} = $s;
716 $output{$second} = 0 unless (keys %output);
727 my $overbill = shift;
729 local $OpenILS::Application::Storage::WRITE = 1;
734 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
735 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
737 push @circs, overdue_circs($grace);
740 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
742 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
746 $ctype =~ s/^.+::(\w+)$/$1/;
748 my $due_date_method = 'due_date';
749 my $target_copy_method = 'target_copy';
750 my $circ_lib_method = 'circ_lib';
751 my $recurring_fine_method = 'recurring_fine';
752 my $is_reservation = 0;
753 if ($ctype eq 'reservation') {
755 $due_date_method = 'end_time';
756 $target_copy_method = 'current_resource';
757 $circ_lib_method = 'pickup_lib';
758 $recurring_fine_method = 'fine_amount';
759 next unless ($c->fine_interval);
763 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
764 $log->debug("Cleaning up after previous transaction\n");
765 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
767 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
769 sprintf("Processing %s %d...",
770 ($is_reservation ? "reservation" : "circ"), $c->id
775 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
777 my $due = $due_dt->epoch;
780 my $fine_interval = $c->fine_interval;
781 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
782 $fine_interval = interval_to_seconds( $fine_interval );
784 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
786 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
787 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
790 $due -= ($due % $fine_interval) + $tz_offset_s;
791 $now -= ($now % $fine_interval) + $tz_offset_s;
795 "ARG! Overdue $ctype ".$c->id.
796 " for item ".$c->$target_copy_method.
797 " (user ".$c->usr.").\n".
798 "\tItem was due on or before: ".localtime($due)."\n");
800 my @fines = money::billing->search_where(
803 billing_ts => { '>' => $c->$due_date_method } },
804 { order_by => 'billing_ts DESC'}
808 my $fine = $fines[$f_idx] if (@fines);
810 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
813 my $current_fine_total = 0;
814 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
818 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
819 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
821 $log->info( "Potential first billing for circ ".$c->id );
825 if (my $h = $hoo{$c->$circ_lib_method}) {
827 $log->info( "Circ lib has an hours-of-operation entry" );
828 # find the day after the due date...
829 $due_dt = $due_dt->add( days => 1 );
831 # get the day of the week for that day...
832 my $dow = $due_dt->day_of_week_0;
833 my $dow_open = "dow_${dow}_open";
834 my $dow_close = "dow_${dow}_close";
837 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
838 # if the circ lib is closed, add a day to the grace period...
841 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
842 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
844 $due_dt = $due_dt->add( days => 1 );
845 $dow = $due_dt->day_of_week_0;
846 $dow_open = "dow_${dow}_open";
847 $dow_close = "dow_${dow}_close";
851 # and check for up to a week
852 last if ($count > 6);
858 next if ($last_fine > $now);
859 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
861 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
862 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
864 if ( $last_fine == $due # we have no fines yet
865 && $grace # and we have a grace period
866 && $pending_fine_count <= $grace # and we seem to be inside that period
867 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
869 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
870 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
874 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
875 next unless ($pending_fine_count);
877 my $recurring_fine = int($c->$recurring_fine_method * 100);
878 my $max_fine = int($c->max_fine * 100);
880 my ($latest_billing_ts, $latest_amount) = ('',0);
881 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
883 if ($current_fine_total >= $max_fine) {
884 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
886 "\tMaximum fine level of ".$c->max_fine.
887 " reached for this $ctype.\n".
888 "\tNo more fines will be generated.\n" );
892 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
893 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
894 my $current_bill_count = $bill;
895 while ( $current_bill_count ) {
896 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
897 $current_bill_count--;
900 my $dow = $billing_ts->day_of_week_0();
901 my $dow_open = "dow_${dow}_open";
902 my $dow_close = "dow_${dow}_close";
904 if (my $h = $hoo{$c->$circ_lib_method}) {
905 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
908 my $timestamptz = $billing_ts->strftime('%FT%T%z');
909 my @cl = actor::org_unit::closed_date->search_where(
910 { close_start => { '<=' => $timestamptz },
911 close_end => { '>=' => $timestamptz },
912 org_unit => $c->$circ_lib_method }
916 $current_fine_total += $recurring_fine;
917 $latest_amount += $recurring_fine;
918 $latest_billing_ts = $timestamptz;
920 money::billing->create(
922 note => "System Generated Overdue Fine",
923 billing_type => "Overdue materials",
925 amount => sprintf('%0.2f', $recurring_fine/100),
926 billing_ts => $timestamptz,
932 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
933 if ($latest_billing_ts and $latest_amount);
935 $self->method_lookup('open-ils.storage.transaction.commit')->run;
939 # Caluclate penalties inline
940 OpenILS::Utils::Penalty->calculate_penalties(
941 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
945 # Calculate penalties with an aysnc call to the penalty server. This approach
946 # may lead to duplicate penalties since multiple penalty processes for a
947 # given user may be running at the same time. Leave this here for reference
948 # in case we later find that asyc calls are needed in some environments.
950 'open-ils.penalty.patron_penalty.calculate',
951 { patronid => ''.$c->usr,
952 context_org => ''.$c->$circ_lib_method,
961 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
962 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
963 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
964 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
968 __PACKAGE__->register_method(
969 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
972 method => 'generate_fines',
977 sub new_hold_copy_targeter {
980 my $check_expire = shift;
981 my $one_hold = shift;
983 local $OpenILS::Application::Storage::WRITE = 1;
985 $self->{target_weight} = {};
986 $self->{max_loops} = {};
992 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
993 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
994 } elsif ( $check_expire ) {
996 # what's the retarget time threashold?
998 $check_expire ||= '12h';
999 $check_expire = interval_to_seconds( $check_expire );
1001 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1004 my $expire_threshold = sprintf(
1005 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1006 $year, $mon, $mday, $hour, $min, $sec
1009 # find all the holds holds needing retargeting
1010 $holds = [ action::hold_request->search_where(
1011 { capture_time => undef,
1012 fulfillment_time => undef,
1013 cancel_time => undef,
1015 prev_check_time => { '<=' => $expire_threshold },
1017 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1019 # find all the holds holds needing first time targeting
1020 push @$holds, action::hold_request->search(
1021 capture_time => undef,
1022 fulfillment_time => undef,
1023 prev_check_time => undef,
1025 cancel_time => undef,
1026 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1029 # find all the holds holds needing first time targeting ONLY
1030 $holds = [ action::hold_request->search(
1031 capture_time => undef,
1032 fulfillment_time => undef,
1033 prev_check_time => undef,
1034 cancel_time => undef,
1036 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1038 } catch Error with {
1040 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1043 my @closed = actor::org_unit::closed_date->search_where(
1044 { close_start => { '<=', 'now' },
1045 close_end => { '>=', 'now' } }
1048 if ($check_expire) {
1050 # $check_expire, if it exists, was already converted to seconds
1051 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1055 my $next_check_time = sprintf(
1056 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1057 $year, $mon, $mday, $hour, $min, $sec
1061 my @closed_at_next = actor::org_unit::closed_date->search_where(
1062 { close_start => { '<=', $next_check_time },
1063 close_end => { '>=', $next_check_time } }
1067 for my $c_at_n (@closed_at_next) {
1068 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1069 push @new_closed, $c_at_n;
1072 @closed = @new_closed;
1076 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1078 for my $hold (@$holds) {
1080 #start a transaction if needed
1081 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1082 $log->debug("Cleaning up after previous transaction\n");
1083 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1085 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1086 $log->info("Processing hold ".$hold->id."...\n");
1088 #first, re-fetch the hold, to make sure it's not captured already
1089 $hold->remove_from_object_index();
1090 $hold = action::hold_request->retrieve( $hold->id );
1092 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1094 # remove old auto-targeting maps
1095 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1096 $_->delete for (@oldmaps);
1098 if ($hold->expire_time) {
1099 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1100 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1102 # cancel cause = un-targeted expiration
1103 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1104 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1106 # tell A/T the hold was cancelled
1107 my $fm_hold = $hold->to_fieldmapper;
1108 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1109 $ses->request('open-ils.trigger.event.autocreate',
1110 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1116 my $all_copies = [];
1118 # find filters for MR holds
1119 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1121 # find all the potential copies
1122 if ($hold->hold_type eq 'M') {
1125 metabib::record_descriptor
1129 isTrue($_->deleted) ? () : ($_->id)
1130 } metabib::metarecord->retrieve($hold->target)->source_records
1132 ( $types ? (item_type => [split '', $types]) : () ),
1133 ( $formats ? (item_form => [split '', $formats]) : () ),
1134 ( $lang ? (item_lang => $lang) : () ),
1138 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1139 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1141 for my $cn ( @{ $rtree->call_numbers } ) {
1143 asset::copy->search_where(
1144 { id => [map {$_->id} @{ $cn->copies }],
1146 ) if ($cn && @{ $cn->copies });
1149 } elsif ($hold->hold_type eq 'T') {
1151 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1152 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1155 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1159 for my $cn ( @{ $rtree->call_numbers } ) {
1161 asset::copy->search_where(
1162 { id => [map {$_->id} @{ $cn->copies }],
1164 ) if ($cn && @{ $cn->copies });
1166 } elsif ($hold->hold_type eq 'V') {
1168 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1169 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1172 asset::copy->search_where(
1173 { id => [map {$_->id} @{ $vtree->copies }],
1175 ) if ($vtree && @{ $vtree->copies });
1177 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1178 my $_cp = asset::copy->retrieve($hold->target);
1179 push @$all_copies, $_cp if $_cp;
1183 @$all_copies = grep { isTrue($_->status->holdable) &&
1184 isTrue($_->location->holdable) &&
1185 isTrue($_->holdable) &&
1186 !isTrue($_->deleted) &&
1187 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1190 # let 'em know we're still working
1191 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1193 # if we have no copies ...
1194 if (!ref $all_copies || !@$all_copies) {
1195 $log->info("\tNo copies available for targeting at all!\n");
1196 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1198 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1199 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1203 my $copy_count = @$all_copies;
1205 # map the potentials, so that we can pick up checkins
1206 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1207 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1208 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1209 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1211 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1214 for my $c (@$all_copies) {
1216 next if ($c->id eq $hold->current_copy);
1218 # circ lib is closed
1219 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1221 # target of another hold
1222 next if (action::hold_request
1224 { current_copy => $c->id,
1225 fulfillment_time => undef,
1226 cancel_time => undef,
1231 # we passed all three, keep it
1232 push @good_copies, $c if ($c);
1233 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1236 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1238 my $old_best = $hold->current_copy;
1239 $hold->update({ current_copy => undef }) if ($old_best);
1241 if (!scalar(@good_copies)) {
1242 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1243 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1244 # the old copy is still available
1245 $log->debug("\tPushing current_copy back onto the targeting list");
1246 push @good_copies, $old_best;
1248 # oops, old copy is not available
1249 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1250 $hold->update( { prev_check_time => 'today' } );
1251 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1252 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1257 my $pu_lib = ''.$hold->pickup_lib;
1263 ''.$_->circ_lib eq $pu_lib
1267 $all_copies = [grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1268 # $all_copies is now a list of copies not at the pickup library
1270 my $best = choose_nearest_copy($hold, $prox_list);
1271 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1274 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1276 $self->{max_loops}{$pu_lib} = $actor->request(
1277 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1280 if (defined($self->{max_loops}{$pu_lib})) {
1281 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1283 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1284 my $circ_lib_list = [keys %circ_lib_map];
1286 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1288 # Grab the "biggest" loop for this hold so far
1289 my $current_loop = $cstore->request(
1290 'open-ils.cstore.json_query',
1292 select => { aufhmxl => ['max'] },
1294 where => { hold => $hold->id}
1298 $current_loop = $current_loop->{max} if ($current_loop);
1299 $current_loop ||= 1;
1301 my $exclude_list = $cstore->request(
1302 'open-ils.cstore.json_query.atomic',
1304 select => { aufhol => ['circ_lib'] },
1306 where => { hold => $hold->id}
1311 if ($exclude_list && @$exclude_list) {
1312 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1313 # check to see if we've used up every library in the potentials list
1314 for my $l ( @$circ_lib_list ) {
1316 for my $ex ( @$exclude_list ) {
1322 push(@keepers, $l) if ($keep);
1325 @keepers = @$circ_lib_list;
1328 $current_loop++ if (!@keepers);
1330 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} <= $current_loop) {
1331 # We haven't exceeded max_loops yet
1333 for my $cp ( @$all_copies ) {
1334 push(@keeper_copies, $cp) if ( grep { $_ eq ''.$cp->circ_lib } @keepers );
1336 $all_copies = [@keeper_copies];
1338 # We have, and should remove potentials and cancel the hold
1339 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1340 $_->delete for (@oldmaps);
1342 # cancel cause = un-targeted expiration
1343 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1344 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1346 # tell A/T the hold was cancelled
1347 my $fm_hold = $hold->to_fieldmapper;
1348 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1349 $ses->request('open-ils.trigger.event.autocreate',
1350 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1356 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1358 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1360 $best = choose_nearest_copy($hold, $prox_list);
1363 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1365 # hold wasn't fulfilled, record the fact
1367 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1368 action::unfulfilled_hold_list->create(
1369 { hold => ''.$hold->id,
1370 current_copy => ''.$old_best->id,
1371 circ_lib => ''.$old_best->circ_lib,
1376 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1377 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1380 action::hold_request
1382 { current_copy => $old_best->id,
1383 fulfillment_time => undef,
1384 cancel_time => undef,
1388 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1389 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1391 $hold->update( { prev_check_time => 'now' } );
1392 $log->info( "\tThere were no targetable copies for the hold" );
1395 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1396 $log->info("\tProcessing of hold ".$hold->id." complete.");
1399 { hold => $hold->id,
1400 old_target => ($old_best ? $old_best->id : undef),
1401 eligible_copies => $copy_count,
1402 target => ($best ? $best->id : undef) };
1407 $log->error("Processing of hold failed: $e");
1408 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1409 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1416 __PACKAGE__->register_method(
1417 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1419 method => 'new_hold_copy_targeter',
1422 sub reservation_targeter {
1425 my $one_reservation = shift;
1427 local $OpenILS::Application::Storage::WRITE = 1;
1432 if ($one_reservation) {
1433 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1434 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1437 # find all the reservations needing targeting
1439 booking::reservation->search_where(
1440 { current_resource => undef,
1441 cancel_time => undef,
1442 start_time => { '>' => 'now' }
1444 { order_by => 'start_time' }
1448 } catch Error with {
1450 die "Could not retrieve reservation requests:\n\n$e\n";
1454 for my $bresv (@$reservations) {
1456 #start a transaction if needed
1457 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1458 $log->debug("Cleaning up after previous transaction\n");
1459 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1461 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1462 $log->info("Processing reservation ".$bresv->id."...\n");
1464 #first, re-fetch the hold, to make sure it's not captured already
1465 $bresv->remove_from_object_index();
1466 $bresv = booking::reservation->retrieve( $bresv->id );
1468 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1470 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1471 if (DateTime->compare($end_time, DateTime->now) < 0) {
1473 # cancel cause = un-targeted expiration
1474 $bresv->update( { cancel_time => 'now' } );
1475 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1477 # tell A/T the reservation was cancelled
1478 my $fm_bresv = $bresv->to_fieldmapper;
1479 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1480 $ses->request('open-ils.trigger.event.autocreate',
1481 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1486 my $possible_resources;
1488 # find all the potential resources
1489 if (!$bresv->target_resource) {
1490 my $filter = { type => $bresv->target_resource_type };
1491 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1493 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1495 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1496 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1497 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1499 $possible_resources = $bresv->target_resource;
1502 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1503 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1506 my @good_resources = ();
1508 for my $res (@$all_resources) {
1509 unless (isTrue($res->type->catalog_item)) {
1510 push @good_resources, $res;
1514 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1517 push @good_resources, $res;
1521 if ($copy->status->id == 0 || $copy->status->id == 7) {
1522 push @good_resources, $res;
1526 if ($copy->status->id == 1) {
1527 my $circs = [ action::circulation->search_where(
1528 {target_copy => $copy->id, checkin_time => undef },
1529 { order_by => 'id DESC' }
1533 my $due_date = $circs->[0]->due_date;
1534 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1535 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1536 if (DateTime->compare($start_time, $due_date) < 0) {
1537 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1541 push @good_resources, $res;
1547 push @good_resources, $res if (isTrue($copy->status->holdable));
1550 # let 'em know we're still working
1551 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1553 # if we have no copies ...
1554 if (!@good_resources) {
1555 $log->info("\tNo resources available for targeting at all!\n");
1556 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1559 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1563 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1569 $_->owner == $bresv->pickup_lib
1573 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1574 # $all_copies is now a list of copies not at the pickup library
1576 my $best = shift @good_resources;
1577 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1580 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1584 sort { $a->[0] <=> $b->[0] }
1586 [ actor::org_unit_proximity->search_where(
1587 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1593 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1595 $best = shift @$prox_list
1599 $bresv->update( { current_resource => ''.$best->id } );
1600 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1603 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1604 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1607 { reservation => $bresv->id,
1608 current_resource => ($best ? $best->id : undef) };
1613 $log->error("Processing of bresv failed: $e");
1614 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1615 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1622 __PACKAGE__->register_method(
1623 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1625 method => 'reservation_targeter',
1630 my %cache = (titles => {}, cns => {});
1631 sub hold_copy_targeter {
1634 my $check_expire = shift;
1635 my $one_hold = shift;
1637 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1638 $self->{user_filter}->connect;
1639 $self->{client} = $client;
1642 $check_expire ||= '12h';
1643 $check_expire = interval_to_seconds( $check_expire );
1645 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1648 my $expire_threshold = sprintf(
1649 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1650 $year, $mon, $mday, $hour, $min, $sec
1654 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1656 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1660 %cache = (titles => {}, cns => {});
1664 $holds = [ action::hold_request->search(id => $one_hold) ];
1666 $holds = [ action::hold_request->search_where(
1667 { capture_time => undef,
1668 prev_check_time => { '<=' => $expire_threshold },
1670 { order_by => 'request_time,prev_check_time' } ) ];
1671 push @$holds, action::hold_request->search_where(
1672 { capture_time => undef,
1673 prev_check_time => undef,
1675 { order_by => 'request_time' } );
1677 } catch Error with {
1679 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1682 for my $hold (@$holds) {
1684 #action::hold_request->db_Main->begin_work;
1685 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1686 $client->respond("Cleaning up after previous transaction\n");
1687 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1689 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1690 $client->respond("Processing hold ".$hold->id."...\n");
1694 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1695 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1697 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1698 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1700 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1701 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1703 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1705 unless (ref $copies || !@$copies) {
1706 $client->respond("\tNo copies available for targeting at all!\n");
1710 for my $c (@$copies) {
1711 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1712 push @good_copies, $c if ($c);
1715 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1717 my $old_best = $hold->current_copy;
1718 $hold->update({ current_copy => undef });
1720 if (!scalar(@good_copies)) {
1721 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1722 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1723 $client->respond("\tPushing current_copy back onto the targeting list\n");
1724 push @good_copies, asset::copy->retrieve( $old_best );
1726 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1732 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1733 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1735 my $best = choose_nearest_copy($hold, $prox_list);
1738 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1739 $best = choose_nearest_copy($hold, $prox_list);
1743 # hold wasn't fulfilled, record the fact
1745 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1746 action::unfulfilled_hold_list->create(
1747 { hold => ''.$hold->id,
1748 current_copy => ''.$old_best->id,
1749 circ_lib => ''.$old_best->circ_lib,
1754 $hold->update( { current_copy => ''.$best->id } );
1755 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1758 $hold->update( { prev_check_time => 'now' } );
1759 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1761 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1762 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1764 #action::hold_request->dbi_commit;
1768 $log->error("Processing of hold failed: $e");
1769 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1770 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1771 #action::hold_request->dbi_rollback;
1775 $self->{user_filter}->disconnect;
1776 $self->{user_filter}->finish;
1777 delete $$self{user_filter};
1780 #__PACKAGE__->register_method(
1781 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1784 # method => 'hold_copy_targeter',
1788 sub copy_hold_capture {
1793 if (!defined($cps)) {
1795 $cps = [ asset::copy->search( id => $hold->target ) ];
1796 } catch Error with {
1798 die "Could not retrieve initial volume list:\n\n$e\n";
1802 my @copies = grep { $_->holdable } @$cps;
1804 for (my $i = 0; $i < @$cps; $i++) {
1805 next unless $$cps[$i];
1807 my $cn = $cache{cns}{$copies[$i]->call_number};
1808 my $rec = $cache{titles}{$cn->record};
1809 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1810 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1811 $copies[$i] = undef if (
1813 !$self->{user_filter}->request(
1814 'open-ils.circ.permit_hold',
1815 $hold->to_fieldmapper, do {
1816 my $cp_fm = $copies[$i]->to_fieldmapper;
1817 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1818 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1819 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1822 { title => $rec->to_fieldmapper,
1823 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1824 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1827 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1830 @copies = grep { $_ } @copies;
1832 my $count = @copies;
1834 return unless ($count);
1836 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1839 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1840 for my $c (@copies) {
1841 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1843 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1849 sub choose_nearest_copy {
1851 my $prox_list = shift;
1853 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1854 next unless (ref $$prox_list[$p]);
1856 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1857 next unless (@capturable);
1859 my $rand = int(rand(scalar(@capturable)));
1860 while (my ($c) = splice(@capturable,$rand)) {
1861 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1862 { title => $c->call_number->record->to_fieldmapper,
1863 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1864 patron => $hold->usr->to_fieldmapper,
1865 copy => $c->to_fieldmapper,
1866 requestor => $hold->requestor->to_fieldmapper,
1867 request_lib => $hold->request_lib->to_fieldmapper,
1868 pickup_lib => $hold->pickup_lib->id,
1872 last unless(@capturable);
1873 $rand = int(rand(scalar(@capturable)));
1878 sub create_prox_list {
1883 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1886 for my $cp (@$copies) {
1887 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1888 next unless (defined($prox));
1890 # Fetch the weighting value for hold targeting, defaulting to 1
1891 $self->{target_weight}{$lib} ||= $actor->request(
1892 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1894 $self->{target_weight}{$lib} = $self->{target_weight}{$lib}{value} if (ref $self->{target_weight}{$lib});
1895 $self->{target_weight}{$lib} ||= 1;
1897 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1898 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1899 push @{$prox_list[$prox]}, $cp;
1905 sub volume_hold_capture {
1910 if (!defined($vols)) {
1912 $vols = [ asset::call_number->search( id => $hold->target ) ];
1913 $cache{cns}{$_->id} = $_ for (@$vols);
1914 } catch Error with {
1916 die "Could not retrieve initial volume list:\n\n$e\n";
1920 my @v_ids = map { $_->id } @$vols;
1924 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1926 } catch Error with {
1928 warn "Could not retrieve copy list:\n\n$e\n";
1931 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1934 sub title_hold_capture {
1939 if (!defined($titles)) {
1941 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1942 $cache{titles}{$_->id} = $_ for (@$titles);
1943 } catch Error with {
1945 die "Could not retrieve initial title list:\n\n$e\n";
1949 my @t_ids = map { $_->id } @$titles;
1952 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1954 } catch Error with {
1956 warn "Could not retrieve volume list:\n\n$e\n";
1959 $cache{cns}{$_->id} = $_ for (@$cn_list);
1961 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1964 sub metarecord_hold_capture {
1970 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1972 } catch Error with {
1974 die "Could not retrieve initial title list:\n\n$e\n";
1978 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1980 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1982 } catch Error with {
1984 die "Could not retrieve format-pruned title list:\n\n$e\n";
1988 $cache{titles}{$_->id} = $_ for (@$titles);
1989 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);