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',
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';
287 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
289 FROM action.hold_request h
290 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
291 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
292 WHERE hm.target_copy = ?
293 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
294 AND h.capture_time IS NULL
295 AND h.cancel_time IS NULL
296 AND (h.expire_time IS NULL OR h.expire_time > NOW())
297 AND h.frozen IS FALSE
300 CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
301 h.selection_depth DESC,
306 $client->respond( $_ ) for ( @$ids );
309 __PACKAGE__->register_method(
310 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
313 method => 'nearest_hold',
316 sub next_resp_group_id {
320 # XXX This is not replication safe!!!
322 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
323 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
327 __PACKAGE__->register_method(
328 api_name => 'open-ils.storage.action.survey_response.next_group_id',
330 method => 'next_resp_group_id',
333 sub patron_circ_summary {
338 return undef unless ($id);
339 my $c_table = action::circulation->table;
340 my $b_table = money::billing->table;
342 $log->debug("Retrieving patron summary for id $id", DEBUG);
344 my $select = <<" SQL";
345 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
347 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
349 AND c.xact_finish IS NULL
351 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
352 OR c.stop_fines IS NULL
356 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
358 __PACKAGE__->register_method(
359 api_name => 'open-ils.storage.action.circulation.patron_summary',
361 method => 'patron_circ_summary',
364 #XXX Fix stored proc calls
365 sub find_local_surveys {
370 return undef unless ($ou);
371 my $s_table = action::survey->table;
373 my $select = <<" SQL";
376 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
377 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
380 my $sth = action::survey->db_Main->prepare_cached($select);
383 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
387 __PACKAGE__->register_method(
388 api_name => 'open-ils.storage.action.survey.all',
391 method => 'find_local_surveys',
394 #XXX Fix stored proc calls
395 sub find_opac_surveys {
400 return undef unless ($ou);
401 my $s_table = action::survey->table;
403 my $select = <<" SQL";
406 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
407 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
411 my $sth = action::survey->db_Main->prepare_cached($select);
414 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
418 __PACKAGE__->register_method(
419 api_name => 'open-ils.storage.action.survey.opac',
422 method => 'find_opac_surveys',
429 my $limit = shift || 10;
430 my $offset = shift || 0;
432 return undef unless ($ou);
433 my $h_table = action::hold_request->table;
434 my $a_table = asset::copy->table;
435 my $ord_table = asset::copy_location_order->table;
437 my $idlist = 1 if ($self->api_name =~/id_list/o);
438 my $count = 1 if ($self->api_name =~/count$/o);
440 my $status_filter = '';
441 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
443 my $select = <<" SQL";
446 JOIN $a_table a ON (h.current_copy = a.id)
447 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
449 AND h.capture_time IS NULL
450 AND h.cancel_time IS NULL
451 AND (h.expire_time IS NULL OR h.expire_time > NOW())
453 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
462 JOIN $a_table a ON (h.current_copy = a.id)
464 AND h.capture_time IS NULL
465 AND h.cancel_time IS NULL
466 AND (h.expire_time IS NULL OR h.expire_time > NOW())
471 my $sth = action::survey->db_Main->prepare_cached($select);
475 $client->respond( $sth->fetchall_arrayref()->[0][0] );
477 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
479 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
484 __PACKAGE__->register_method(
485 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
489 "Returns a count of holds for a specific library's pull list.",
490 [ [org_unit => "The library's org id", "number"] ],
491 ['A count of holds for the stated library to pull ', 'number']
493 method => 'hold_pull_list',
495 __PACKAGE__->register_method(
496 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
500 "Returns a status filtered count of holds for a specific library's pull list.",
501 [ [org_unit => "The library's org id", "number"] ],
502 ['A status filtered count of holds for the stated library to pull ', 'number']
504 method => 'hold_pull_list',
506 __PACKAGE__->register_method(
507 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
511 "Returns the hold ids for a specific library's pull list.",
512 [ [org_unit => "The library's org id", "number"],
513 [limit => 'An optional page size, defaults to 10', 'number'],
514 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
516 ['A list of holds for the stated library to pull for', 'array']
518 method => 'hold_pull_list',
520 __PACKAGE__->register_method(
521 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
525 "Returns the holds for a specific library's pull list.",
526 [ [org_unit => "The library's org id", "number"],
527 [limit => 'An optional page size, defaults to 10', 'number'],
528 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
530 ['A list of holds for the stated library to pull for', 'array']
532 method => 'hold_pull_list',
534 __PACKAGE__->register_method(
535 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
539 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
540 [ [org_unit => "The library's org id", "number"],
541 [limit => 'An optional page size, defaults to 10', 'number'],
542 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
544 ['A list of holds for the stated library to pull for', 'array']
546 method => 'hold_pull_list',
548 __PACKAGE__->register_method(
549 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
553 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
554 [ [org_unit => "The library's org id", "number"],
555 [limit => 'An optional page size, defaults to 10', 'number'],
556 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
558 ['A list of holds for the stated library to pull for', 'array']
560 method => 'hold_pull_list',
563 sub find_optional_surveys {
568 return undef unless ($ou);
569 my $s_table = action::survey->table;
571 my $select = <<" SQL";
574 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
575 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
576 AND s.required IS FALSE;
579 my $sth = action::survey->db_Main->prepare_cached($select);
582 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
586 __PACKAGE__->register_method(
587 api_name => 'open-ils.storage.action.survey.optional',
590 method => 'find_optional_surveys',
593 sub find_required_surveys {
598 return undef unless ($ou);
599 my $s_table = action::survey->table;
601 my $select = <<" SQL";
604 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
605 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
606 AND s.required IS TRUE;
609 my $sth = action::survey->db_Main->prepare_cached($select);
612 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
616 __PACKAGE__->register_method(
617 api_name => 'open-ils.storage.action.survey.required',
620 method => 'find_required_surveys',
623 sub find_usr_summary_surveys {
628 return undef unless ($ou);
629 my $s_table = action::survey->table;
631 my $select = <<" SQL";
634 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
635 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
636 AND s.usr_summary IS TRUE;
639 my $sth = action::survey->db_Main->prepare_cached($select);
642 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
646 __PACKAGE__->register_method(
647 api_name => 'open-ils.storage.action.survey.usr_summary',
650 method => 'find_usr_summary_surveys',
653 sub seconds_to_interval_hash {
654 my $interval = shift;
655 my $limit = shift || 's';
656 $limit =~ s/^(.)/$1/o;
660 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
661 my ($year, $month, $week, $day, $hour, $minute, $second) =
662 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
664 if ($y = int($interval / (60 * 60 * 24 * 365))) {
666 $ym = $interval % (60 * 60 * 24 * 365);
670 return %output if ($limit eq 'y');
672 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
673 $output{$month} = $M;
674 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
678 return %output if ($limit eq 'M');
680 if ($w = int($Mm / 604800)) {
686 return %output if ($limit eq 'w');
688 if ($d = int($wm / 86400)) {
694 return %output if ($limit eq 'd');
696 if ($h = int($dm / 3600)) {
702 return %output if ($limit eq 'h');
704 if ($m = int($hm / 60)) {
705 $output{$minute} = $m;
710 return %output if ($limit eq 'm');
713 $output{$second} = $s;
715 $output{$second} = 0 unless (keys %output);
726 my $overbill = shift;
728 local $OpenILS::Application::Storage::WRITE = 1;
733 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
734 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
736 push @circs, overdue_circs($grace);
739 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
741 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
745 $ctype =~ s/^.*([^:]+)$/$1/o;
747 my $due_date_method = 'due_date';
748 my $target_copy_method = 'target_copy';
749 my $circ_lib_method = 'circ_lib';
750 my $recurring_fine_method = 'recurring_fine';
751 my $is_reservation = 0;
752 if ($ctype eq 'reservation') {
754 $due_date_method = 'end_time';
755 $target_copy_method = 'current_resource';
756 $circ_lib_method = 'pickup_lib';
757 $recurring_fine_method = 'fine_amount';
758 next unless ($c->fine_interval);
762 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
763 $log->debug("Cleaning up after previous transaction\n");
764 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
766 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
767 $log->info("Processing circ ".$c->id."...\n");
770 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
772 my $due = $due_dt->epoch;
775 my $fine_interval = $c->fine_interval;
776 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
777 $fine_interval = interval_to_seconds( $fine_interval );
779 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
781 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
782 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
785 $due -= ($due % $fine_interval) + $tz_offset_s;
786 $now -= ($now % $fine_interval) + $tz_offset_s;
790 "ARG! Overdue $ctype ".$c->id.
791 " for item ".$c->$target_copy_method.
792 " (user ".$c->usr.").\n".
793 "\tItem was due on or before: ".localtime($due)."\n");
795 my @fines = money::billing->search_where(
798 billing_ts => { '>' => $c->$due_date_method } },
799 { order_by => 'billing_ts DESC'}
803 my $fine = $fines[$f_idx] if (@fines);
805 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
808 my $current_fine_total = 0;
809 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
813 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
814 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
816 $log->info( "Potential first billing for circ ".$c->id );
820 if (my $h = $hoo{$c->$circ_lib_method}) {
822 $log->info( "Circ lib has an hours-of-operation entry" );
823 # find the day after the due date...
824 $due_dt = $due_dt->add( days => 1 );
826 # get the day of the week for that day...
827 my $dow = $due_dt->day_of_week_0;
828 my $dow_open = "dow_${dow}_open";
829 my $dow_close = "dow_${dow}_close";
832 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
833 # if the circ lib is closed, add a day to the grace period...
836 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
837 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
839 $due_dt = $due_dt->add( days => 1 );
840 $dow = $due_dt->day_of_week_0;
841 $dow_open = "dow_${dow}_open";
842 $dow_close = "dow_${dow}_close";
846 # and check for up to a week
847 last if ($count > 6);
853 next if ($last_fine > $now);
854 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
856 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
857 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
859 if ( $last_fine == $due # we have no fines yet
860 && $grace # and we have a grace period
861 && $pending_fine_count <= $grace # and we seem to be inside that period
862 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
864 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
865 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
869 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
870 next unless ($pending_fine_count);
872 my $recurring_fine = int($c->$recurring_fine_method * 100);
873 my $max_fine = int($c->max_fine * 100);
875 my ($latest_billing_ts, $latest_amount) = ('',0);
876 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
878 if ($current_fine_total >= $max_fine) {
879 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
881 "\tMaximum fine level of ".$c->max_fine.
882 " reached for this $ctype.\n".
883 "\tNo more fines will be generated.\n" );
887 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
888 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
889 my $current_bill_count = $bill;
890 while ( $current_bill_count ) {
891 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
892 $current_bill_count--;
895 my $dow = $billing_ts->day_of_week_0();
896 my $dow_open = "dow_${dow}_open";
897 my $dow_close = "dow_${dow}_close";
899 if (my $h = $hoo{$c->$circ_lib_method}) {
900 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
903 my $timestamptz = $billing_ts->strftime('%FT%T%z');
904 my @cl = actor::org_unit::closed_date->search_where(
905 { close_start => { '<=' => $timestamptz },
906 close_end => { '>=' => $timestamptz },
907 org_unit => $c->$circ_lib_method }
911 $current_fine_total += $recurring_fine;
912 $latest_amount += $recurring_fine;
913 $latest_billing_ts = $timestamptz;
915 money::billing->create(
917 note => "System Generated Overdue Fine",
918 billing_type => "Overdue materials",
920 amount => sprintf('%0.2f', $recurring_fine/100),
921 billing_ts => $timestamptz,
927 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
928 if ($latest_billing_ts and $latest_amount);
930 $self->method_lookup('open-ils.storage.transaction.commit')->run;
934 # Caluclate penalties inline
935 OpenILS::Utils::Penalty->calculate_penalties(
936 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
940 # Calculate penalties with an aysnc call to the penalty server. This approach
941 # may lead to duplicate penalties since multiple penalty processes for a
942 # given user may be running at the same time. Leave this here for reference
943 # in case we later find that asyc calls are needed in some environments.
945 'open-ils.penalty.patron_penalty.calculate',
946 { patronid => ''.$c->usr,
947 context_org => ''.$c->$circ_lib_method,
956 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
957 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
958 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
959 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
963 __PACKAGE__->register_method(
964 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
967 method => 'generate_fines',
972 sub new_hold_copy_targeter {
975 my $check_expire = shift;
976 my $one_hold = shift;
978 local $OpenILS::Application::Storage::WRITE = 1;
980 $self->{target_weight} = {};
986 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
987 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
988 } elsif ( $check_expire ) {
990 # what's the retarget time threashold?
992 $check_expire ||= '12h';
993 $check_expire = interval_to_seconds( $check_expire );
995 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
998 my $expire_threshold = sprintf(
999 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1000 $year, $mon, $mday, $hour, $min, $sec
1003 # find all the holds holds needing retargeting
1004 $holds = [ action::hold_request->search_where(
1005 { capture_time => undef,
1006 fulfillment_time => undef,
1007 cancel_time => undef,
1009 prev_check_time => { '<=' => $expire_threshold },
1011 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1013 # find all the holds holds needing first time targeting
1014 push @$holds, action::hold_request->search(
1015 capture_time => undef,
1016 fulfillment_time => undef,
1017 prev_check_time => undef,
1019 cancel_time => undef,
1020 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1023 # find all the holds holds needing first time targeting ONLY
1024 $holds = [ action::hold_request->search(
1025 capture_time => undef,
1026 fulfillment_time => undef,
1027 prev_check_time => undef,
1028 cancel_time => undef,
1030 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1032 } catch Error with {
1034 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1037 my @closed = actor::org_unit::closed_date->search_where(
1038 { close_start => { '<=', 'now' },
1039 close_end => { '>=', 'now' } }
1042 if ($check_expire) {
1044 # $check_expire, if it exists, was already converted to seconds
1045 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1049 my $next_check_time = sprintf(
1050 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1051 $year, $mon, $mday, $hour, $min, $sec
1055 my @closed_at_next = actor::org_unit::closed_date->search_where(
1056 { close_start => { '<=', $next_check_time },
1057 close_end => { '>=', $next_check_time } }
1061 for my $c_at_n (@closed_at_next) {
1062 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1063 push @new_closed, $c_at_n;
1066 @closed = @new_closed;
1070 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1072 for my $hold (@$holds) {
1074 #start a transaction if needed
1075 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1076 $log->debug("Cleaning up after previous transaction\n");
1077 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1079 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1080 $log->info("Processing hold ".$hold->id."...\n");
1082 #first, re-fetch the hold, to make sure it's not captured already
1083 $hold->remove_from_object_index();
1084 $hold = action::hold_request->retrieve( $hold->id );
1086 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1088 # remove old auto-targeting maps
1089 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1090 $_->delete for (@oldmaps);
1092 if ($hold->expire_time) {
1093 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1094 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1096 # cancel cause = un-targeted expiration
1097 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1098 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1100 # tell A/T the hold was cancelled
1101 my $fm_hold = $hold->to_fieldmapper;
1102 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1103 $ses->request('open-ils.trigger.event.autocreate',
1104 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1110 my $all_copies = [];
1112 # find filters for MR holds
1113 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1115 # find all the potential copies
1116 if ($hold->hold_type eq 'M') {
1119 metabib::record_descriptor
1123 isTrue($_->deleted) ? () : ($_->id)
1124 } metabib::metarecord->retrieve($hold->target)->source_records
1126 ( $types ? (item_type => [split '', $types]) : () ),
1127 ( $formats ? (item_form => [split '', $formats]) : () ),
1128 ( $lang ? (item_lang => $lang) : () ),
1132 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1133 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1135 for my $cn ( @{ $rtree->call_numbers } ) {
1137 asset::copy->search_where(
1138 { id => [map {$_->id} @{ $cn->copies }],
1140 ) if ($cn && @{ $cn->copies });
1143 } elsif ($hold->hold_type eq 'T') {
1145 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1146 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1149 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1153 for my $cn ( @{ $rtree->call_numbers } ) {
1155 asset::copy->search_where(
1156 { id => [map {$_->id} @{ $cn->copies }],
1158 ) if ($cn && @{ $cn->copies });
1160 } elsif ($hold->hold_type eq 'V') {
1162 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1163 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1166 asset::copy->search_where(
1167 { id => [map {$_->id} @{ $vtree->copies }],
1169 ) if ($vtree && @{ $vtree->copies });
1171 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1172 my $_cp = asset::copy->retrieve($hold->target);
1173 push @$all_copies, $_cp if $_cp;
1177 @$all_copies = grep { isTrue($_->status->holdable) &&
1178 isTrue($_->location->holdable) &&
1179 isTrue($_->holdable) &&
1180 !isTrue($_->deleted) &&
1181 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1184 # let 'em know we're still working
1185 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1187 # if we have no copies ...
1188 if (!ref $all_copies || !@$all_copies) {
1189 $log->info("\tNo copies available for targeting at all!\n");
1190 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1192 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1193 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1197 my $copy_count = @$all_copies;
1199 # map the potentials, so that we can pick up checkins
1200 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1201 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1202 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1203 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1205 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1208 for my $c (@$all_copies) {
1210 next if ($c->id eq $hold->current_copy);
1212 # circ lib is closed
1213 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1215 # target of another hold
1216 next if (action::hold_request
1218 { current_copy => $c->id,
1219 fulfillment_time => undef,
1220 cancel_time => undef,
1225 # we passed all three, keep it
1226 push @good_copies, $c if ($c);
1227 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1230 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1232 my $old_best = $hold->current_copy;
1233 $hold->update({ current_copy => undef }) if ($old_best);
1235 if (!scalar(@good_copies)) {
1236 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1237 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1238 # the old copy is still available
1239 $log->debug("\tPushing current_copy back onto the targeting list");
1240 push @good_copies, $old_best;
1242 # oops, old copy is not available
1243 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1244 $hold->update( { prev_check_time => 'today' } );
1245 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1246 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1255 $_->circ_lib == $hold->pickup_lib
1259 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1260 # $all_copies is now a list of copies not at the pickup library
1262 my $best = choose_nearest_copy($hold, $prox_list);
1263 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1266 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1268 my $max_loops = $actor->request(
1269 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1272 if (defined($max_loops)) {
1273 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1274 my $circ_lib_list = [keys %circ_lib_map];
1276 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1278 # Grab the "biggest" loop for this hold so far
1279 my $current_loop = $cstore->request(
1280 'open-ils.cstore.json_query',
1282 select => { aufhmxl => ['max'] },
1284 where => { hold => $hold->id}
1288 $current_loop = $current_loop->{max} if ($current_loop);
1289 $current_loop ||= 1;
1291 my $exclude_list = $cstore->request(
1292 'open-ils.cstore.json_query.atomic',
1294 select => { aufhol => [circ_lib] },
1296 where => { hold => $hold->id}
1301 if ($exclude_list && @$exclude_list) {
1302 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1303 # check to see if we've used up every library in the potentials list
1304 for my $l ( @$circ_lib_list ) {
1306 for my $ex ( @$exclude_list ) {
1312 push(@keepers, $l) if ($keep);
1315 @keepers = @$circ_lib_list;
1318 $current_loop++ if (!@keepers);
1320 if ($max_loops && $max_loops <= $current_loop) {
1321 # We haven't exceeded max_loops yet
1323 for my $cp ( @$all_copies ) {
1324 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1327 # We have, and should remove potentials and cancel the hold
1328 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1329 $_->delete for (@oldmaps);
1331 # cancel cause = un-targeted expiration
1332 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1333 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1335 # tell A/T the hold was cancelled
1336 my $fm_hold = $hold->to_fieldmapper;
1337 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1338 $ses->request('open-ils.trigger.event.autocreate',
1339 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1345 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1347 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1349 $best = choose_nearest_copy($hold, $prox_list);
1352 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1354 # hold wasn't fulfilled, record the fact
1356 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1357 action::unfulfilled_hold_list->create(
1358 { hold => ''.$hold->id,
1359 current_copy => ''.$old_best->id,
1360 circ_lib => ''.$old_best->circ_lib,
1365 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1366 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1369 action::hold_request
1371 { current_copy => $old_best->id,
1372 fulfillment_time => undef,
1373 cancel_time => undef,
1377 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1378 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1380 $hold->update( { prev_check_time => 'now' } );
1381 $log->info( "\tThere were no targetable copies for the hold" );
1384 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1385 $log->info("\tProcessing of hold ".$hold->id." complete.");
1388 { hold => $hold->id,
1389 old_target => ($old_best ? $old_best->id : undef),
1390 eligible_copies => $copy_count,
1391 target => ($best ? $best->id : undef) };
1396 $log->error("Processing of hold failed: $e");
1397 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1398 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1405 __PACKAGE__->register_method(
1406 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1408 method => 'new_hold_copy_targeter',
1411 sub reservation_targeter {
1414 my $one_reservation = shift;
1416 local $OpenILS::Application::Storage::WRITE = 1;
1421 if ($one_reservation) {
1422 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1423 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1426 # find all the reservations needing targeting
1428 booking::reservation->search_where(
1429 { current_resource => undef,
1430 cancel_time => undef,
1431 start_time => { '>' => 'now' }
1433 { order_by => 'start_time' }
1437 } catch Error with {
1439 die "Could not retrieve reservation requests:\n\n$e\n";
1443 for my $bresv (@$reservations) {
1445 #start a transaction if needed
1446 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1447 $log->debug("Cleaning up after previous transaction\n");
1448 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1450 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1451 $log->info("Processing reservation ".$bresv->id."...\n");
1453 #first, re-fetch the hold, to make sure it's not captured already
1454 $bresv->remove_from_object_index();
1455 $bresv = booking::reservation->retrieve( $bresv->id );
1457 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1459 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1460 if (DateTime->compare($end_time, DateTime->now) < 0) {
1462 # cancel cause = un-targeted expiration
1463 $bresv->update( { cancel_time => 'now' } );
1464 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1466 # tell A/T the reservation was cancelled
1467 my $fm_bresv = $bresv->to_fieldmapper;
1468 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1469 $ses->request('open-ils.trigger.event.autocreate',
1470 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1475 my $possible_resources;
1477 # find all the potential resources
1478 if (!$bresv->target_resource) {
1479 my $filter = { type => $bresv->target_resource_type };
1480 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1482 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1484 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1485 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1486 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1488 $possible_resources = $bresv->target_resource;
1491 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1492 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1495 my @good_resources = ();
1496 for my $res (@$all_resources) {
1497 unless (isTrue($res->type->catalog_item)) {
1498 push @good_resources, $res;
1502 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1505 push @good_resources, $res;
1509 if ($copy->status->id == 0 || $copy->status->id == 7) {
1510 push @good_resources, $res;
1514 if ($copy->status->id == 1) {
1515 my $circs = action::circulation->search_where(
1516 {target_copy => $copy->id, checkin_time => undef },
1517 { order_by => 'id DESC' }
1521 my $due_date = $circs->[0]->due_date;
1522 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1523 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1524 next if (DateTime->compare($start_time, $due_date) < 0);
1525 push @good_resources, $res;
1531 push @good_resources, $res if (isTrue($copy->status->holdable));
1534 # let 'em know we're still working
1535 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1537 # if we have no copies ...
1538 if (!@good_resources) {
1539 $log->info("\tNo resources available for targeting at all!\n");
1540 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1542 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1546 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1552 $_->owner == $bresv->pickup_lib
1556 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1557 # $all_copies is now a list of copies not at the pickup library
1559 my $best = shift @good_resources;
1560 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1563 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1567 sort { $a->[0] <=> $b->[0] }
1569 [ actor::org_unit_proximity->search_where(
1570 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1576 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1578 $best = shift @$prox_list
1582 $bresv->update( { current_resource => ''.$best->id } );
1583 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1586 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1587 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1590 { reservation => $bresv->id,
1591 current_resource => ($best ? $best->id : undef) };
1596 $log->error("Processing of bresv failed: $e");
1597 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1598 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1605 __PACKAGE__->register_method(
1606 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1608 method => 'reservation_targeter',
1613 my %cache = (titles => {}, cns => {});
1614 sub hold_copy_targeter {
1617 my $check_expire = shift;
1618 my $one_hold = shift;
1620 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1621 $self->{user_filter}->connect;
1622 $self->{client} = $client;
1625 $check_expire ||= '12h';
1626 $check_expire = interval_to_seconds( $check_expire );
1628 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1631 my $expire_threshold = sprintf(
1632 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1633 $year, $mon, $mday, $hour, $min, $sec
1637 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1639 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1643 %cache = (titles => {}, cns => {});
1647 $holds = [ action::hold_request->search(id => $one_hold) ];
1649 $holds = [ action::hold_request->search_where(
1650 { capture_time => undef,
1651 prev_check_time => { '<=' => $expire_threshold },
1653 { order_by => 'request_time,prev_check_time' } ) ];
1654 push @$holds, action::hold_request->search_where(
1655 { capture_time => undef,
1656 prev_check_time => undef,
1658 { order_by => 'request_time' } );
1660 } catch Error with {
1662 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1665 for my $hold (@$holds) {
1667 #action::hold_request->db_Main->begin_work;
1668 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1669 $client->respond("Cleaning up after previous transaction\n");
1670 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1672 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1673 $client->respond("Processing hold ".$hold->id."...\n");
1677 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1678 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1680 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1681 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1683 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1684 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1686 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1688 unless (ref $copies || !@$copies) {
1689 $client->respond("\tNo copies available for targeting at all!\n");
1693 for my $c (@$copies) {
1694 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1695 push @good_copies, $c if ($c);
1698 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1700 my $old_best = $hold->current_copy;
1701 $hold->update({ current_copy => undef });
1703 if (!scalar(@good_copies)) {
1704 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1705 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1706 $client->respond("\tPushing current_copy back onto the targeting list\n");
1707 push @good_copies, asset::copy->retrieve( $old_best );
1709 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1715 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1716 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1718 my $best = choose_nearest_copy($hold, $prox_list);
1721 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1722 $best = choose_nearest_copy($hold, $prox_list);
1726 # hold wasn't fulfilled, record the fact
1728 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1729 action::unfulfilled_hold_list->create(
1730 { hold => ''.$hold->id,
1731 current_copy => ''.$old_best->id,
1732 circ_lib => ''.$old_best->circ_lib,
1737 $hold->update( { current_copy => ''.$best->id } );
1738 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1741 $hold->update( { prev_check_time => 'now' } );
1742 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1744 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1745 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1747 #action::hold_request->dbi_commit;
1751 $log->error("Processing of hold failed: $e");
1752 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1753 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1754 #action::hold_request->dbi_rollback;
1758 $self->{user_filter}->disconnect;
1759 $self->{user_filter}->finish;
1760 delete $$self{user_filter};
1763 #__PACKAGE__->register_method(
1764 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1767 # method => 'hold_copy_targeter',
1771 sub copy_hold_capture {
1776 if (!defined($cps)) {
1778 $cps = [ asset::copy->search( id => $hold->target ) ];
1779 } catch Error with {
1781 die "Could not retrieve initial volume list:\n\n$e\n";
1785 my @copies = grep { $_->holdable } @$cps;
1787 for (my $i = 0; $i < @$cps; $i++) {
1788 next unless $$cps[$i];
1790 my $cn = $cache{cns}{$copies[$i]->call_number};
1791 my $rec = $cache{titles}{$cn->record};
1792 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1793 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1794 $copies[$i] = undef if (
1796 !$self->{user_filter}->request(
1797 'open-ils.circ.permit_hold',
1798 $hold->to_fieldmapper, do {
1799 my $cp_fm = $copies[$i]->to_fieldmapper;
1800 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1801 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1802 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1805 { title => $rec->to_fieldmapper,
1806 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1807 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1810 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1813 @copies = grep { $_ } @copies;
1815 my $count = @copies;
1817 return unless ($count);
1819 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1822 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1823 for my $c (@copies) {
1824 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1826 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1832 sub choose_nearest_copy {
1834 my $prox_list = shift;
1836 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1837 next unless (ref $$prox_list[$p]);
1839 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1840 next unless (@capturable);
1842 my $rand = int(rand(scalar(@capturable)));
1843 while (my ($c) = splice(@capturable,$rand)) {
1844 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1845 { title => $c->call_number->record->to_fieldmapper,
1846 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1847 patron => $hold->usr->to_fieldmapper,
1848 copy => $c->to_fieldmapper,
1849 requestor => $hold->requestor->to_fieldmapper,
1850 request_lib => $hold->request_lib->to_fieldmapper,
1851 pickup_lib => $hold->pickup_lib->id,
1855 last unless(@capturable);
1856 $rand = int(rand(scalar(@capturable)));
1861 sub create_prox_list {
1866 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1869 for my $cp (@$copies) {
1870 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1871 next unless (defined($prox));
1873 # Fetch the weighting value for hold targeting, defaulting to 1
1874 $self->{target_weight}{$lib} ||= $actor->request(
1875 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1878 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1879 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1880 push @{$prox_list[$prox]}, $cp;
1886 sub volume_hold_capture {
1891 if (!defined($vols)) {
1893 $vols = [ asset::call_number->search( id => $hold->target ) ];
1894 $cache{cns}{$_->id} = $_ for (@$vols);
1895 } catch Error with {
1897 die "Could not retrieve initial volume list:\n\n$e\n";
1901 my @v_ids = map { $_->id } @$vols;
1905 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1907 } catch Error with {
1909 warn "Could not retrieve copy list:\n\n$e\n";
1912 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1915 sub title_hold_capture {
1920 if (!defined($titles)) {
1922 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1923 $cache{titles}{$_->id} = $_ for (@$titles);
1924 } catch Error with {
1926 die "Could not retrieve initial title list:\n\n$e\n";
1930 my @t_ids = map { $_->id } @$titles;
1933 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1935 } catch Error with {
1937 warn "Could not retrieve volume list:\n\n$e\n";
1940 $cache{cns}{$_->id} = $_ for (@$cn_list);
1942 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1945 sub metarecord_hold_capture {
1951 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1953 } catch Error with {
1955 die "Could not retrieve initial title list:\n\n$e\n";
1959 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1961 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1963 } catch Error with {
1965 die "Could not retrieve format-pruned title list:\n\n$e\n";
1969 $cache{titles}{$_->id} = $_ for (@$titles);
1970 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);