1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
5 use OpenSRF::Utils::Logger qw/:level/;
6 use OpenSRF::Utils qw/:datetime/;
7 use OpenSRF::Utils::JSON;
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::PermitHold;
13 use DateTime::Format::ISO8601;
14 use OpenILS::Utils::Penalty;
16 use OpenILS::Application::Circ::CircCommon;
20 return 1 if ($v == 1);
21 return 1 if ($v =~ /^t/io);
22 return 1 if ($v =~ /^y/io);
26 my $parser = DateTime::Format::ISO8601->new;
27 my $log = 'OpenSRF::Utils::Logger';
29 sub open_noncat_circs {
34 my $a = action::non_cataloged_circulation->table;
35 my $c = config::non_cataloged_type->table;
40 JOIN $c c ON (a.item_type = c.id)
41 WHERE a.circ_time + c.circ_duration > current_timestamp
45 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
47 __PACKAGE__->register_method(
48 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
49 method => 'open_noncat_circs',
55 sub ou_hold_requests {
60 my $h_table = action::hold_request->table;
61 my $c_table = asset::copy->table;
62 my $o_table = actor::org_unit->table;
67 JOIN $c_table cp ON (cp.id = h.current_copy)
68 JOIN $o_table ou ON (ou.id = cp.circ_lib)
70 AND h.capture_time IS NULL
71 AND h.cancel_time IS NULL
72 AND (h.expire_time IS NULL OR h.expire_time > NOW())
73 ORDER BY h.request_time
76 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
79 $client->respond($_) for (
82 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
86 } @{ $sth->fetchall_arrayref }
90 __PACKAGE__->register_method(
91 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
95 method => 'ou_hold_requests',
100 my $upper_interval = shift || '1 millennium';
103 my $c_t = action::circulation->table;
108 WHERE stop_fines IS NULL
109 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
110 AND fine_interval < ?::INTERVAL
113 my $sth = action::circulation->db_Main->prepare_cached($sql);
114 $sth->execute($upper_interval);
116 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
118 $c_t = booking::reservation->table;
122 WHERE return_time IS NULL
123 AND end_time < ( CURRENT_TIMESTAMP )
124 AND fine_interval IS NOT NULL
125 AND cancel_time IS NULL
128 $sth = action::circulation->db_Main->prepare_cached($sql);
131 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
136 sub complete_reshelving {
141 local $OpenILS::Application::Storage::WRITE = 1;
143 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
144 unless (interval_to_seconds( $window ));
146 my $setting = actor::org_unit_setting->table;
147 my $circ = action::circulation->table;
148 my $cp = asset::copy->table;
149 my $atc = action::transit_copy->table;
156 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
158 JOIN $circ circ ON (circ.target_copy = cp.id)
159 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
160 LEFT JOIN $setting setting
161 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
162 WHERE circ.checkin_time IS NOT NULL
166 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
167 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
169 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
170 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
176 LEFT JOIN $setting setting
177 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
178 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
181 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
184 my $sth = action::circulation->db_Main->prepare_cached($sql);
185 $sth->execute($window, $window, $window);
190 __PACKAGE__->register_method(
191 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
194 method => 'complete_reshelving',
197 sub mark_longoverdue {
202 local $OpenILS::Application::Storage::WRITE = 1;
204 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
205 unless (interval_to_seconds( $window ));
207 my $setting = actor::org_unit_setting->table;
208 my $circ = action::circulation->table;
212 SET stop_fines = 'LONGOVERDUE',
213 stop_fines_time = now()
217 LEFT JOIN $setting setting
218 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
219 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
220 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
224 my $sth = action::circulation->db_Main->prepare_cached($sql);
225 $sth->execute($window);
230 __PACKAGE__->register_method(
231 api_name => 'open-ils.storage.action.circulation.long_overdue',
234 method => 'mark_longoverdue',
237 sub auto_thaw_frozen_holds {
241 local $OpenILS::Application::Storage::WRITE = 1;
243 my $holds = action::hold_request->table;
245 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
247 my $sth = action::hold_request->db_Main->prepare_cached($sql);
253 __PACKAGE__->register_method(
254 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
258 method => 'auto_thaw_frozen_holds',
265 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
267 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
272 __PACKAGE__->register_method(
273 api_name => 'open-ils.storage.action.circulation.overdue',
276 method => 'grab_overdue',
278 Return list of overdue circulations and reservations to be used for fine generation.
279 Despite the name, this is not a generic method for retrieving all overdue loans,
280 as it excludes loans that have already hit the maximum fine limit.
283 __PACKAGE__->register_method(
284 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
287 method => 'grab_overdue',
295 my $limit = int(shift()) || 10;
296 my $age = shift() || '0 seconds';
299 local $OpenILS::Application::Storage::WRITE = 1;
301 my $holdsort = isTrue($fifo) ?
302 "pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.request_time, h.selection_depth DESC, p.prox " :
303 "p.prox, pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
305 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
307 FROM action.hold_request h
308 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
309 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
310 JOIN actor.usr au ON (au.id = h.usr)
311 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
312 WHERE hm.target_copy = ?
313 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
314 AND h.capture_time IS NULL
315 AND h.cancel_time IS NULL
316 AND (h.expire_time IS NULL OR h.expire_time > NOW())
317 AND h.frozen IS FALSE
322 $client->respond( $_ ) for ( @$ids );
325 __PACKAGE__->register_method(
326 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
329 method => 'nearest_hold',
332 sub targetable_holds {
335 my $check_expire = shift;
337 $check_expire ||= '12h';
339 local $OpenILS::Application::Storage::WRITE = 1;
341 # json_query can *almost* represent this query, but can't
342 # handle the CASE statement or the interval arithmetic
343 my $query = <<" SQL";
344 SELECT ahr.id, mmsm.metarecord
345 FROM action.hold_request ahr
346 JOIN reporter.hold_request_record USING (id)
347 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
348 WHERE capture_time IS NULL
349 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
350 AND fulfillment_time IS NULL
351 AND cancel_time IS NULL
353 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
355 my $sth = action::hold_request->db_Main->prepare_cached($query);
356 $sth->execute($check_expire);
358 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
362 __PACKAGE__->register_method(
363 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
366 method => 'targetable_holds',
368 Returns ordered list of hold request and metarecord IDs
369 for all hold requests that are available for initial targeting
371 @param check interval
372 @return list of pairs of hold request and metarecord IDs
376 sub next_resp_group_id {
380 # XXX This is not replication safe!!!
382 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
383 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
387 __PACKAGE__->register_method(
388 api_name => 'open-ils.storage.action.survey_response.next_group_id',
390 method => 'next_resp_group_id',
393 sub patron_circ_summary {
398 return undef unless ($id);
399 my $c_table = action::circulation->table;
400 my $b_table = money::billing->table;
402 $log->debug("Retrieving patron summary for id $id", DEBUG);
404 my $select = <<" SQL";
405 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
407 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
409 AND c.xact_finish IS NULL
411 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
412 OR c.stop_fines IS NULL
416 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
418 __PACKAGE__->register_method(
419 api_name => 'open-ils.storage.action.circulation.patron_summary',
421 method => 'patron_circ_summary',
424 #XXX Fix stored proc calls
425 sub find_local_surveys {
430 return undef unless ($ou);
431 my $s_table = action::survey->table;
433 my $select = <<" SQL";
436 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
437 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
440 my $sth = action::survey->db_Main->prepare_cached($select);
443 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
447 __PACKAGE__->register_method(
448 api_name => 'open-ils.storage.action.survey.all',
451 method => 'find_local_surveys',
454 #XXX Fix stored proc calls
455 sub find_opac_surveys {
460 return undef unless ($ou);
461 my $s_table = action::survey->table;
463 my $select = <<" SQL";
466 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
467 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
471 my $sth = action::survey->db_Main->prepare_cached($select);
474 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
478 __PACKAGE__->register_method(
479 api_name => 'open-ils.storage.action.survey.opac',
482 method => 'find_opac_surveys',
489 my $limit = shift || 10;
490 my $offset = shift || 0;
492 return undef unless ($ou);
493 my $h_table = action::hold_request->table;
494 my $a_table = asset::copy->table;
495 my $ord_table = asset::copy_location_order->table;
497 my $idlist = 1 if ($self->api_name =~/id_list/o);
498 my $count = 1 if ($self->api_name =~/count$/o);
500 my $status_filter = '';
501 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
503 my $select = <<" SQL";
506 JOIN $a_table a ON (h.current_copy = a.id)
507 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
509 AND h.capture_time IS NULL
510 AND h.cancel_time IS NULL
511 AND (h.expire_time IS NULL OR h.expire_time > NOW())
513 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
522 JOIN $a_table a ON (h.current_copy = a.id)
524 AND h.capture_time IS NULL
525 AND h.cancel_time IS NULL
526 AND (h.expire_time IS NULL OR h.expire_time > NOW())
531 my $sth = action::survey->db_Main->prepare_cached($select);
535 $client->respond( $sth->fetchall_arrayref()->[0][0] );
537 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
539 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
544 __PACKAGE__->register_method(
545 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
549 "Returns a count of holds for a specific library's pull list.",
550 [ [org_unit => "The library's org id", "number"] ],
551 ['A count of holds for the stated library to pull ', 'number']
553 method => 'hold_pull_list',
555 __PACKAGE__->register_method(
556 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
560 "Returns a status filtered count of holds for a specific library's pull list.",
561 [ [org_unit => "The library's org id", "number"] ],
562 ['A status filtered count of holds for the stated library to pull ', 'number']
564 method => 'hold_pull_list',
566 __PACKAGE__->register_method(
567 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
571 "Returns the hold ids for a specific library's pull list.",
572 [ [org_unit => "The library's org id", "number"],
573 [limit => 'An optional page size, defaults to 10', 'number'],
574 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
576 ['A list of holds for the stated library to pull for', 'array']
578 method => 'hold_pull_list',
580 __PACKAGE__->register_method(
581 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
585 "Returns the holds for a specific library's pull list.",
586 [ [org_unit => "The library's org id", "number"],
587 [limit => 'An optional page size, defaults to 10', 'number'],
588 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
590 ['A list of holds for the stated library to pull for', 'array']
592 method => 'hold_pull_list',
594 __PACKAGE__->register_method(
595 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
599 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
600 [ [org_unit => "The library's org id", "number"],
601 [limit => 'An optional page size, defaults to 10', 'number'],
602 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
604 ['A list of holds for the stated library to pull for', 'array']
606 method => 'hold_pull_list',
608 __PACKAGE__->register_method(
609 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
613 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
614 [ [org_unit => "The library's org id", "number"],
615 [limit => 'An optional page size, defaults to 10', 'number'],
616 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
618 ['A list of holds for the stated library to pull for', 'array']
620 method => 'hold_pull_list',
623 sub find_optional_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.required IS FALSE;
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.optional',
650 method => 'find_optional_surveys',
653 sub find_required_surveys {
658 return undef unless ($ou);
659 my $s_table = action::survey->table;
661 my $select = <<" SQL";
664 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
665 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
666 AND s.required IS TRUE;
669 my $sth = action::survey->db_Main->prepare_cached($select);
672 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
676 __PACKAGE__->register_method(
677 api_name => 'open-ils.storage.action.survey.required',
680 method => 'find_required_surveys',
683 sub find_usr_summary_surveys {
688 return undef unless ($ou);
689 my $s_table = action::survey->table;
691 my $select = <<" SQL";
694 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
695 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
696 AND s.usr_summary IS TRUE;
699 my $sth = action::survey->db_Main->prepare_cached($select);
702 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
706 __PACKAGE__->register_method(
707 api_name => 'open-ils.storage.action.survey.usr_summary',
710 method => 'find_usr_summary_surveys',
713 sub seconds_to_interval_hash {
714 my $interval = shift;
715 my $limit = shift || 's';
716 $limit =~ s/^(.)/$1/o;
720 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
721 my ($year, $month, $week, $day, $hour, $minute, $second) =
722 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
724 if ($y = int($interval / (60 * 60 * 24 * 365))) {
726 $ym = $interval % (60 * 60 * 24 * 365);
730 return %output if ($limit eq 'y');
732 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
733 $output{$month} = $M;
734 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
738 return %output if ($limit eq 'M');
740 if ($w = int($Mm / 604800)) {
746 return %output if ($limit eq 'w');
748 if ($d = int($wm / 86400)) {
754 return %output if ($limit eq 'd');
756 if ($h = int($dm / 3600)) {
762 return %output if ($limit eq 'h');
764 if ($m = int($hm / 60)) {
765 $output{$minute} = $m;
770 return %output if ($limit eq 'm');
773 $output{$second} = $s;
775 $output{$second} = 0 unless (keys %output);
785 my $overbill = shift;
787 local $OpenILS::Application::Storage::WRITE = 1;
792 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
793 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
795 push @circs, overdue_circs();
798 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
800 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
804 $ctype =~ s/^.+::(\w+)$/$1/;
806 my $due_date_method = 'due_date';
807 my $target_copy_method = 'target_copy';
808 my $circ_lib_method = 'circ_lib';
809 my $recurring_fine_method = 'recurring_fine';
810 my $is_reservation = 0;
811 if ($ctype eq 'reservation') {
813 $due_date_method = 'end_time';
814 $target_copy_method = 'current_resource';
815 $circ_lib_method = 'pickup_lib';
816 $recurring_fine_method = 'fine_amount';
817 next unless ($c->fine_interval);
819 #TODO: reservation grace periods
820 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
823 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
824 $log->debug("Cleaning up after previous transaction\n");
825 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
827 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
829 sprintf("Processing %s %d...",
830 ($is_reservation ? "reservation" : "circ"), $c->id
835 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
837 my $due = $due_dt->epoch;
840 my $fine_interval = $c->fine_interval;
841 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
842 $fine_interval = interval_to_seconds( $fine_interval );
844 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
845 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
846 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
850 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
852 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
853 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
856 $due -= ($due % $fine_interval) + $tz_offset_s;
857 $now -= ($now % $fine_interval) + $tz_offset_s;
861 "ARG! Overdue $ctype ".$c->id.
862 " for item ".$c->$target_copy_method.
863 " (user ".$c->usr.").\n".
864 "\tItem was due on or before: ".localtime($due)."\n");
866 my @fines = money::billing->search_where(
869 billing_ts => { '>' => $c->$due_date_method } },
870 { order_by => 'billing_ts DESC'}
874 my $fine = $fines[$f_idx] if (@fines);
876 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
879 my $current_fine_total = 0;
880 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
884 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
885 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
887 $log->info( "Potential first billing for circ ".$c->id );
890 $grace_period = OpenILS::Application::Circ::CircCommon->extend_grace_period($c->$circ_lib_method->to_fieldmapper->id,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
893 next if ($last_fine > $now);
894 # Generate fines for each past interval, including the one we are inside
895 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
897 if ( $last_fine == $due # we have no fines yet
898 && $grace_period # and we have a grace period
899 && $now < $due + $grace_period # and some date math says were are within the grace period
901 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
902 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
906 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
907 next unless ($pending_fine_count);
909 my $recurring_fine = int($c->$recurring_fine_method * 100);
910 my $max_fine = int($c->max_fine * 100);
912 my ($latest_billing_ts, $latest_amount) = ('',0);
913 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
915 if ($current_fine_total >= $max_fine) {
916 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
918 "\tMaximum fine level of ".$c->max_fine.
919 " reached for this $ctype.\n".
920 "\tNo more fines will be generated.\n" );
924 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
925 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
926 my $current_bill_count = $bill;
927 while ( $current_bill_count ) {
928 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
929 $current_bill_count--;
932 my $dow = $billing_ts->day_of_week_0();
933 my $dow_open = "dow_${dow}_open";
934 my $dow_close = "dow_${dow}_close";
936 if (my $h = $hoo{$c->$circ_lib_method}) {
937 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
940 my $timestamptz = $billing_ts->strftime('%FT%T%z');
941 my @cl = actor::org_unit::closed_date->search_where(
942 { close_start => { '<=' => $timestamptz },
943 close_end => { '>=' => $timestamptz },
944 org_unit => $c->$circ_lib_method }
948 $current_fine_total += $recurring_fine;
949 $latest_amount += $recurring_fine;
950 $latest_billing_ts = $timestamptz;
952 money::billing->create(
954 note => "System Generated Overdue Fine",
955 billing_type => "Overdue materials",
957 amount => sprintf('%0.2f', $recurring_fine/100),
958 billing_ts => $timestamptz,
964 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
965 if ($latest_billing_ts and $latest_amount);
967 $self->method_lookup('open-ils.storage.transaction.commit')->run;
971 # Caluclate penalties inline
972 OpenILS::Utils::Penalty->calculate_penalties(
973 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
977 # Calculate penalties with an aysnc call to the penalty server. This approach
978 # may lead to duplicate penalties since multiple penalty processes for a
979 # given user may be running at the same time. Leave this here for reference
980 # in case we later find that asyc calls are needed in some environments.
982 'open-ils.penalty.patron_penalty.calculate',
983 { patronid => ''.$c->usr,
984 context_org => ''.$c->$circ_lib_method,
993 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
994 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
995 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
996 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1000 __PACKAGE__->register_method(
1001 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1004 method => 'generate_fines',
1009 sub new_hold_copy_targeter {
1012 my $check_expire = shift;
1013 my $one_hold = shift;
1014 my $find_copy = shift;
1016 local $OpenILS::Application::Storage::WRITE = 1;
1018 $self->{target_weight} = {};
1019 $self->{max_loops} = {};
1025 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1026 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
1027 } elsif ( $check_expire ) {
1029 # what's the retarget time threashold?
1031 $check_expire ||= '12h';
1032 $check_expire = interval_to_seconds( $check_expire );
1034 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1037 my $expire_threshold = sprintf(
1038 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1039 $year, $mon, $mday, $hour, $min, $sec
1042 # find all the holds holds needing retargeting
1043 $holds = [ action::hold_request->search_where(
1044 { capture_time => undef,
1045 fulfillment_time => undef,
1046 cancel_time => undef,
1048 prev_check_time => { '<=' => $expire_threshold },
1050 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1052 # find all the holds holds needing first time targeting
1053 push @$holds, action::hold_request->search(
1054 capture_time => undef,
1055 fulfillment_time => undef,
1056 prev_check_time => undef,
1058 cancel_time => undef,
1059 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1062 # find all the holds holds needing first time targeting ONLY
1063 $holds = [ action::hold_request->search(
1064 capture_time => undef,
1065 fulfillment_time => undef,
1066 prev_check_time => undef,
1067 cancel_time => undef,
1069 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1071 } catch Error with {
1073 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1076 my @closed = actor::org_unit::closed_date->search_where(
1077 { close_start => { '<=', 'now' },
1078 close_end => { '>=', 'now' } }
1081 if ($check_expire) {
1083 # $check_expire, if it exists, was already converted to seconds
1084 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1088 my $next_check_time = sprintf(
1089 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1090 $year, $mon, $mday, $hour, $min, $sec
1094 my @closed_at_next = actor::org_unit::closed_date->search_where(
1095 { close_start => { '<=', $next_check_time },
1096 close_end => { '>=', $next_check_time } }
1100 for my $c_at_n (@closed_at_next) {
1101 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1102 push @new_closed, $c_at_n;
1105 @closed = @new_closed;
1109 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1111 for my $hold (@$holds) {
1113 #start a transaction if needed
1114 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1115 $log->debug("Cleaning up after previous transaction\n");
1116 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1118 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1119 $log->info("Processing hold ".$hold->id."...\n");
1121 #first, re-fetch the hold, to make sure it's not captured already
1122 $hold->remove_from_object_index();
1123 $hold = action::hold_request->retrieve( $hold->id );
1125 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1127 # remove old auto-targeting maps
1128 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1129 $_->delete for (@oldmaps);
1131 if ($hold->expire_time) {
1132 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1133 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1135 # cancel cause = un-targeted expiration
1136 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1137 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1139 # tell A/T the hold was cancelled
1140 my $fm_hold = $hold->to_fieldmapper;
1141 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1142 $ses->request('open-ils.trigger.event.autocreate',
1143 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1149 my $all_copies = [];
1151 # find filters for MR holds
1152 my ($types, $formats, $lang);
1153 if (defined($hold->holdable_formats)) {
1154 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1157 # find all the potential copies
1158 if ($hold->hold_type eq 'M') {
1161 metabib::record_descriptor
1165 isTrue($_->deleted) ? () : ($_->id)
1166 } metabib::metarecord->retrieve($hold->target)->source_records
1168 ( $types ? (item_type => [split '', $types]) : () ),
1169 ( $formats ? (item_form => [split '', $formats]) : () ),
1170 ( $lang ? (item_lang => $lang) : () ),
1174 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1175 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1177 for my $cn ( @{ $rtree->call_numbers } ) {
1179 asset::copy->search_where(
1180 { id => [map {$_->id} @{ $cn->copies }],
1182 ) if ($cn && @{ $cn->copies });
1185 } elsif ($hold->hold_type eq 'T') {
1187 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1188 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1191 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1195 for my $cn ( @{ $rtree->call_numbers } ) {
1197 asset::copy->search_where(
1198 { id => [map {$_->id} @{ $cn->copies }],
1200 ) if ($cn && @{ $cn->copies });
1202 } elsif ($hold->hold_type eq 'V') {
1204 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1205 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1208 asset::copy->search_where(
1209 { id => [map {$_->id} @{ $vtree->copies }],
1211 ) if ($vtree && @{ $vtree->copies });
1213 } elsif ($hold->hold_type eq 'P') {
1214 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1216 asset::copy->search_where(
1217 { id => [map {$_->target_copy} @part_maps],
1222 } elsif ($hold->hold_type eq 'I') {
1224 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1225 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1228 asset::copy->search_where(
1229 { id => [map {$_->unit->id} @{ $itree->items }],
1231 ) if ($itree && @{ $itree->items });
1233 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1234 my $_cp = asset::copy->retrieve($hold->target);
1235 push @$all_copies, $_cp if $_cp;
1239 @$all_copies = grep { isTrue($_->status->holdable) &&
1240 isTrue($_->location->holdable) &&
1241 isTrue($_->holdable) &&
1242 !isTrue($_->deleted) &&
1243 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1244 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1247 # let 'em know we're still working
1248 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1250 # if we have no copies ...
1251 if (!ref $all_copies || !@$all_copies) {
1252 $log->info("\tNo copies available for targeting at all!\n");
1253 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1255 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1256 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1260 my $copy_count = @$all_copies;
1261 my $found_copy = undef;
1262 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1264 # map the potentials, so that we can pick up checkins
1265 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1266 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1267 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1268 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1270 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1273 for my $c (@$all_copies) {
1275 next if ($c->id eq $hold->current_copy);
1277 # circ lib is closed
1278 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1280 # target of another hold
1281 next if (action::hold_request
1283 { current_copy => $c->id,
1284 fulfillment_time => undef,
1285 cancel_time => undef,
1290 # we passed all three, keep it
1291 push @good_copies, $c if ($c);
1292 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1295 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1297 my $old_best = $hold->current_copy;
1298 $hold->update({ current_copy => undef }) if ($old_best);
1300 if (!scalar(@good_copies)) {
1301 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1302 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1303 # the old copy is still available
1304 $log->debug("\tPushing current_copy back onto the targeting list");
1305 push @good_copies, $old_best;
1307 # oops, old copy is not available
1308 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1309 $hold->update( { prev_check_time => 'today' } );
1310 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1311 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1316 my $pu_lib = ''.$hold->pickup_lib;
1322 ''.$_->circ_lib eq $pu_lib &&
1323 ( $_->status == 0 || $_->status == 7 )
1327 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1328 # $all_copies is now a list of copies not at the pickup library
1330 my $best = choose_nearest_copy($hold, $prox_list);
1331 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1334 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1336 $self->{max_loops}{$pu_lib} = $actor->request(
1337 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1340 if (defined($self->{max_loops}{$pu_lib})) {
1341 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1343 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1344 my $circ_lib_list = [keys %circ_lib_map];
1346 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1348 # Grab the "biggest" loop for this hold so far
1349 my $current_loop = $cstore->request(
1350 'open-ils.cstore.json_query',
1352 select => { aufhmxl => ['max'] },
1354 where => { hold => $hold->id}
1358 $current_loop = $current_loop->{max} if ($current_loop);
1359 $current_loop ||= 1;
1361 my $exclude_list = $cstore->request(
1362 'open-ils.cstore.json_query.atomic',
1364 select => { aufhol => ['circ_lib'] },
1366 where => { hold => $hold->id}
1371 if ($exclude_list && @$exclude_list) {
1372 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1373 # check to see if we've used up every library in the potentials list
1374 for my $l ( @$circ_lib_list ) {
1376 for my $ex ( @$exclude_list ) {
1382 push(@keepers, $l) if ($keep);
1385 @keepers = @$circ_lib_list;
1388 $current_loop++ if (!@keepers);
1390 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1391 # We haven't exceeded max_loops yet
1393 for my $cp ( @$all_copies ) {
1394 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1397 $all_copies = [@keeper_copies];
1399 # We have, and should remove potentials and cancel the hold
1400 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1401 $_->delete for (@oldmaps);
1403 # cancel cause = un-targeted expiration
1404 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1405 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1407 # tell A/T the hold was cancelled
1408 my $fm_hold = $hold->to_fieldmapper;
1409 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1410 $ses->request('open-ils.trigger.event.autocreate',
1411 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1417 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1419 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1421 $best = choose_nearest_copy($hold, $prox_list);
1424 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1426 # hold wasn't fulfilled, record the fact
1428 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1429 action::unfulfilled_hold_list->create(
1430 { hold => ''.$hold->id,
1431 current_copy => ''.$old_best->id,
1432 circ_lib => ''.$old_best->circ_lib,
1437 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1438 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1441 !action::hold_request
1443 { current_copy => $old_best->id,
1444 fulfillment_time => undef,
1445 cancel_time => undef,
1449 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1450 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1452 $hold->update( { prev_check_time => 'now' } );
1453 $log->info( "\tThere were no targetable copies for the hold" );
1454 process_recall($actor, $log, $hold, \@good_copies);
1457 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1458 $log->info("\tProcessing of hold ".$hold->id." complete.");
1461 { hold => $hold->id,
1462 old_target => ($old_best ? $old_best->id : undef),
1463 eligible_copies => $copy_count,
1464 target => ($best ? $best->id : undef),
1465 found_copy => $found_copy };
1470 $log->error("Processing of hold failed: $e");
1471 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1472 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1479 __PACKAGE__->register_method(
1480 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1482 method => 'new_hold_copy_targeter',
1485 sub process_recall {
1486 my ($actor, $log, $hold, $good_copies) = @_;
1488 # Bail early if we don't have required settings to avoid spurious requests
1489 my ($recall_threshold, $return_interval, $fine_rules);
1491 my $rv = $actor->request(
1492 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1496 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1499 $recall_threshold = $rv->{value};
1501 $rv = $actor->request(
1502 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1506 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1509 $return_interval = $rv->{value};
1511 $rv = $actor->request(
1512 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1516 $fine_rules = $rv->{value};
1519 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1521 # We want checked out copies (status = 1) at the hold pickup lib
1522 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1524 my @copy_ids = map { $_->id } @$all_copies;
1526 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1528 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1530 # Iterate over the checked-out copies to find a copy with a
1531 # loan period longer than the recall threshold:
1532 my $circs = [ action::circulation->search_where(
1533 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1534 { order_by => 'due_date ASC' }
1537 # If we have a candidate copy, then:
1538 if (scalar(@$circs)) {
1539 my $circ = $circs->[0];
1540 $log->info("Recalling circ ID : " . $circ->id);
1542 # Give the user a new due date of either a full recall threshold,
1543 # or the return interval, whichever is further in the future
1544 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1545 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1546 $return_date = $threshold_date;
1549 my $update_fields = {
1550 due_date => $return_date,
1551 renewal_remaining => 0,
1554 # If the OU hasn't defined new fine rules for recalls, keep them
1557 $log->info("Apply recall fine rules: $fine_rules");
1558 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1559 $update_fields->{recurring_fine} = $rules->[0];
1560 $update_fields->{fine_interval} = $rules->[1];
1561 $update_fields->{max_fine} = $rules->[2];
1564 # Adjust circ for current user
1565 $circ->update($update_fields);
1567 # Create trigger event for notifying current user
1568 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1569 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1572 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1575 sub reservation_targeter {
1578 my $one_reservation = shift;
1580 local $OpenILS::Application::Storage::WRITE = 1;
1585 if ($one_reservation) {
1586 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1587 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1590 # find all the reservations needing targeting
1592 booking::reservation->search_where(
1593 { current_resource => undef,
1594 cancel_time => undef,
1595 start_time => { '>' => 'now' }
1597 { order_by => 'start_time' }
1601 } catch Error with {
1603 die "Could not retrieve reservation requests:\n\n$e\n";
1607 for my $bresv (@$reservations) {
1609 #start a transaction if needed
1610 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1611 $log->debug("Cleaning up after previous transaction\n");
1612 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1614 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1615 $log->info("Processing reservation ".$bresv->id."...\n");
1617 #first, re-fetch the hold, to make sure it's not captured already
1618 $bresv->remove_from_object_index();
1619 $bresv = booking::reservation->retrieve( $bresv->id );
1621 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1623 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1624 if (DateTime->compare($end_time, DateTime->now) < 0) {
1626 # cancel cause = un-targeted expiration
1627 $bresv->update( { cancel_time => 'now' } );
1628 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1630 # tell A/T the reservation was cancelled
1631 my $fm_bresv = $bresv->to_fieldmapper;
1632 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1633 $ses->request('open-ils.trigger.event.autocreate',
1634 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1639 my $possible_resources;
1641 # find all the potential resources
1642 if (!$bresv->target_resource) {
1643 my $filter = { type => $bresv->target_resource_type };
1644 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1646 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1648 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1649 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1650 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1652 $possible_resources = $bresv->target_resource;
1655 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1656 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1659 my @good_resources = ();
1661 for my $res (@$all_resources) {
1662 unless (isTrue($res->type->catalog_item)) {
1663 push @good_resources, $res;
1667 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1670 push @good_resources, $res;
1674 # At this point, if we're just targeting one specific
1675 # resource, just succeed. We don't care about its present
1677 if ($bresv->target_resource) {
1678 push @good_resources, $res;
1682 if ($copy->status->id == 0 || $copy->status->id == 7) {
1683 push @good_resources, $res;
1687 if ($copy->status->id == 1) {
1688 my $circs = [ action::circulation->search_where(
1689 {target_copy => $copy->id, checkin_time => undef },
1690 { order_by => 'id DESC' }
1694 my $due_date = $circs->[0]->due_date;
1695 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1696 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1697 if (DateTime->compare($start_time, $due_date) < 0) {
1698 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1702 push @good_resources, $res;
1708 push @good_resources, $res if (isTrue($copy->status->holdable));
1711 # let 'em know we're still working
1712 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1714 # if we have no copies ...
1715 if (!@good_resources) {
1716 $log->info("\tNo resources available for targeting at all!\n");
1717 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1720 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1724 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1730 $_->owner == $bresv->pickup_lib
1734 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1735 # $all_copies is now a list of copies not at the pickup library
1737 my $best = shift @good_resources;
1738 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1741 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1745 sort { $a->[0] <=> $b->[0] }
1747 [ actor::org_unit_proximity->search_where(
1748 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1754 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1756 $best = shift @$prox_list
1760 $bresv->update( { current_resource => ''.$best->id } );
1761 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1764 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1765 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1768 { reservation => $bresv->id,
1769 current_resource => ($best ? $best->id : undef) };
1774 $log->error("Processing of bresv failed: $e");
1775 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1776 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1783 __PACKAGE__->register_method(
1784 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1786 method => 'reservation_targeter',
1791 my %cache = (titles => {}, cns => {});
1793 sub copy_hold_capture {
1798 if (!defined($cps)) {
1800 $cps = [ asset::copy->search( id => $hold->target ) ];
1801 } catch Error with {
1803 die "Could not retrieve initial volume list:\n\n$e\n";
1807 my @copies = grep { $_->holdable } @$cps;
1809 for (my $i = 0; $i < @$cps; $i++) {
1810 next unless $$cps[$i];
1812 my $cn = $cache{cns}{$copies[$i]->call_number};
1813 my $rec = $cache{titles}{$cn->record};
1814 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1815 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1816 $copies[$i] = undef if (
1818 !$self->{user_filter}->request(
1819 'open-ils.circ.permit_hold',
1820 $hold->to_fieldmapper, do {
1821 my $cp_fm = $copies[$i]->to_fieldmapper;
1822 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1823 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1824 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1827 { title => $rec->to_fieldmapper,
1828 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1829 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1832 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1835 @copies = grep { $_ } @copies;
1837 my $count = @copies;
1839 return unless ($count);
1841 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1844 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1845 for my $c (@copies) {
1846 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1848 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1854 sub choose_nearest_copy {
1856 my $prox_list = shift;
1858 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1859 next unless (ref $$prox_list[$p]);
1861 my @capturable = @{ $$prox_list[$p] };
1862 next unless (@capturable);
1864 my $rand = int(rand(scalar(@capturable)));
1866 while (my ($c) = splice(@capturable, $rand, 1)) {
1867 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1868 { title => $c->call_number->record->to_fieldmapper,
1869 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1870 patron => $hold->usr->to_fieldmapper,
1871 copy => $c->to_fieldmapper,
1872 requestor => $hold->requestor->to_fieldmapper,
1873 request_lib => $hold->request_lib->to_fieldmapper,
1874 pickup_lib => $hold->pickup_lib->id,
1880 last unless(@capturable);
1881 $rand = int(rand(scalar(@capturable)));
1886 sub create_prox_list {
1891 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1894 for my $cp (@$copies) {
1895 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1896 next unless (defined($prox));
1898 my $copy_circ_lib = ''.$cp->circ_lib;
1899 # Fetch the weighting value for hold targeting, defaulting to 1
1900 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1901 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1903 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1904 $self->{target_weight}{$copy_circ_lib} ||= 1;
1906 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1907 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1908 push @{$prox_list[$prox]}, $cp;
1914 sub volume_hold_capture {
1919 if (!defined($vols)) {
1921 $vols = [ asset::call_number->search( id => $hold->target ) ];
1922 $cache{cns}{$_->id} = $_ for (@$vols);
1923 } catch Error with {
1925 die "Could not retrieve initial volume list:\n\n$e\n";
1929 my @v_ids = map { $_->id } @$vols;
1933 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1935 } catch Error with {
1937 warn "Could not retrieve copy list:\n\n$e\n";
1940 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1943 sub title_hold_capture {
1948 if (!defined($titles)) {
1950 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1951 $cache{titles}{$_->id} = $_ for (@$titles);
1952 } catch Error with {
1954 die "Could not retrieve initial title list:\n\n$e\n";
1958 my @t_ids = map { $_->id } @$titles;
1961 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1963 } catch Error with {
1965 warn "Could not retrieve volume list:\n\n$e\n";
1968 $cache{cns}{$_->id} = $_ for (@$cn_list);
1970 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1973 sub metarecord_hold_capture {
1979 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1981 } catch Error with {
1983 die "Could not retrieve initial title list:\n\n$e\n";
1987 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1989 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1991 } catch Error with {
1993 die "Could not retrieve format-pruned title list:\n\n$e\n";
1997 $cache{titles}{$_->id} = $_ for (@$titles);
1998 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);