1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::EX qw/:try/;
6 use OpenILS::Utils::Fieldmapper;
8 use DateTime::Format::ISO8601;
10 my $parser = DateTime::Format::ISO8601->new;
11 my $log = 'OpenSRF::Utils::Logger';
16 my $grace = shift || '';
18 my $c_t = action::circulation->table;
20 $grace = " - ($grace * (fine_interval))" if ($grace);
25 WHERE stop_fines IS NULL
26 AND due_date < ( CURRENT_TIMESTAMP $grace)
29 my $sth = action::circulation->db_Main->prepare_cached($sql);
32 $client->respond( $_->to_fieldmapper ) for ( map { action::circulation->construct($_) } $sth->fetchall_hash );
37 __PACKAGE__->register_method(
38 api_name => 'open-ils.storage.action.circulation.overdue',
41 method => 'grab_overdue',
50 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $pl,$cp);
52 FROM action.hold_request h
53 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
54 WHERE h.pickup_lib = ?
55 AND hm.target_copy = ?
56 AND h.capture_time IS NULL
57 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.request_time
62 __PACKAGE__->register_method(
63 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
65 method => 'nearest_hold',
68 sub next_resp_group_id {
72 # XXX This is not replication safe!!!
74 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
75 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
79 __PACKAGE__->register_method(
80 api_name => 'open-ils.storage.action.survey_response.next_group_id',
82 method => 'next_resp_group_id',
85 sub patron_circ_summary {
90 return undef unless ($id);
91 my $c_table = action::circulation->table;
92 my $b_table = money::billing->table;
94 my $select = <<" SQL";
95 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
97 LEFT OUTER JOIN $b_table b ON (c.id = b.xact)
99 AND c.xact_finish IS NULL
100 AND c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
103 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
105 __PACKAGE__->register_method(
106 api_name => 'open-ils.storage.action.circulation.patron_summary',
108 method => 'patron_circ_summary',
111 #XXX Fix stored proc calls
112 sub find_local_surveys {
117 return undef unless ($ou);
118 my $s_table = action::survey->table;
120 my $select = <<" SQL";
123 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
124 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
127 my $sth = action::survey->db_Main->prepare_cached($select);
130 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
134 __PACKAGE__->register_method(
135 api_name => 'open-ils.storage.action.survey.all',
138 method => 'find_local_surveys',
141 #XXX Fix stored proc calls
142 sub find_opac_surveys {
147 return undef unless ($ou);
148 my $s_table = action::survey->table;
150 my $select = <<" SQL";
153 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
154 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
158 my $sth = action::survey->db_Main->prepare_cached($select);
161 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
165 __PACKAGE__->register_method(
166 api_name => 'open-ils.storage.action.survey.opac',
169 method => 'find_opac_surveys',
172 sub find_optional_surveys {
177 return undef unless ($ou);
178 my $s_table = action::survey->table;
180 my $select = <<" SQL";
183 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
184 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
185 AND s.required IS FALSE;
188 my $sth = action::survey->db_Main->prepare_cached($select);
191 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
195 __PACKAGE__->register_method(
196 api_name => 'open-ils.storage.action.survey.optional',
199 method => 'find_optional_surveys',
202 sub find_required_surveys {
207 return undef unless ($ou);
208 my $s_table = action::survey->table;
210 my $select = <<" SQL";
213 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
214 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
215 AND s.required IS TRUE;
218 my $sth = action::survey->db_Main->prepare_cached($select);
221 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
225 __PACKAGE__->register_method(
226 api_name => 'open-ils.storage.action.survey.required',
229 method => 'find_required_surveys',
232 sub find_usr_summary_surveys {
237 return undef unless ($ou);
238 my $s_table = action::survey->table;
240 my $select = <<" SQL";
243 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
244 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
245 AND s.usr_summary IS TRUE;
248 my $sth = action::survey->db_Main->prepare_cached($select);
251 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
255 __PACKAGE__->register_method(
256 api_name => 'open-ils.storage.action.survey.usr_summary',
259 method => 'find_usr_summary_surveys',
273 $self->method_lookup(
274 'open-ils.storage.direct.action.circulation.search_where'
275 )->run( { id => $circ, stop_fines => undef } );
277 push @circs, $self->method_lookup('open-ils.storage.action.circulation.overdue')->run( $grace );
283 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
285 my $due = $due_dt->epoch;
287 my $fine_interval = interval_to_seconds( $c->fine_interval );
289 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
290 my $tz_offset_s = 0;;
291 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
292 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
295 $due -= ($due % $fine_interval) + $tz_offset_s;
296 $now -= ($now % $fine_interval) + $tz_offset_s;
300 "ARG! Overdue circulation ".$c->id.
301 " for item ".$c->target_copy.
302 " (user ".$c->usr.").\n".
303 "\tItem was due on or before: ".localtime($due)."\n");
305 my ($fine) = $self->method_lookup('open-ils.storage.direct.money.billing.search')->run(
306 { xact => $c->id, voided => 'f' },
307 { order_by => 'billing_ts DESC', limit => '1' }
312 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
315 $last_fine += $fine_interval * $grace;
318 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
319 unless($pending_fine_count) {
320 $client->respond( "\tNo fines to create. " );
321 if ($grace && $now < $due + $fine_interval * $grace) {
322 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
324 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
329 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
331 for my $bill (1 .. $pending_fine_count) {
333 my ($total) = $self->method_lookup('open-ils.storage.direct.money.billable_transaction_summary.retrieve')->run( $c->id );
335 if ($total && $total->balance_owed > $c->max_fine) {
336 $c->stop_fines('MAXFINES');
337 $self->method_lookup('open-ils.storage.direct.action.circulation.update')->run( $c );
339 "\tMaximum fine level of ".$c->max_fine.
340 " reached for this circulation.\n".
341 "\tNo more fines will be generated.\n" );
345 my $billing = new Fieldmapper::money::billing;
346 $billing->xact( $c->id );
347 $billing->note( "Overdue Fine" );
348 $billing->amount( $c->recuring_fine );
350 $billing->billing_ts(
351 DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
355 "\t\tCreating fine of ".$billing->amount." for period starting ".
357 $parser->parse_datetime(
358 clense_ISO8601( $billing->billing_ts )
362 $self->method_lookup('open-ils.storage.direct.money.billing.create')->run( $billing );
366 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
370 __PACKAGE__->register_method(
371 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
374 method => 'generate_fines',
382 my %cache = (titles => {}, cns => {});
383 sub hold_copy_targeter {
386 my $check_expire = shift;
387 my $one_hold = shift;
389 $user_filter ||= $self->method_lookup('open-ils.circ.permit_hold');
392 $check_expire ||= '12h';
393 $check_expire = interval_to_seconds( $check_expire );
395 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time - $check_expire);
398 my $expire_threshold = sprintf(
399 '%s-%0.2d-%0.2dT%s:%0.2d:%0.s2-00',
400 $year, $mon, $mday, $hour, $min, $sec
403 $self->method_lookup( 'open-ils.storage.transaction.begin')->run($client);
405 ($statuses) = $self->method_lookup('open-ils.storage.direct.config.copy_status.search.holdable.atomic')->run('t');
407 ($locations) = $self->method_lookup('open-ils.storage.direct.asset.copy_location.search.holdable.atomic')->run('t');
411 %cache = (titles => {}, cns => {});
415 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search.atomic')
416 ->run(id => $one_hold);
418 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search_where.atomic')
420 { capture_time => undef,
421 prev_check_time => { '<=' => $expire_threshold },
423 { order_by => 'request_time,prev_check_time' } );
424 push @$holds, $self->method_lookup('open-ils.storage.direct.action.hold_request.search')
426 { capture_time => undef,
427 prev_check_time => undef },
428 { order_by => 'request_time' } );
432 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
435 for my $hold (@$holds) {
439 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
440 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
441 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
442 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
444 $client->respond("Processing hold ".$hold->id."...\n");
445 unless (ref $copies) {
446 $client->respond("\tNo copies available for targeting!\n");
451 for my $c (@$copies) {
452 next if ( grep {$c->id == $hold->current_copy} @good_copies);
453 push @good_copies, $c if ($c);
456 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
458 my $old_best = $hold->current_copy;
459 $hold->clear_current_copy;
461 if (!scalar(@good_copies)) {
462 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
463 $client->respond("\tPushing current_copy back onto the targeting list\n");
464 push @good_copies, $self->method_lookup('open-ils.storage.direct.asset.copy.retrieve')->run( $old_best );
466 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT!\n");
472 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
473 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
475 my $best = $self->choose_nearest_copy($hold, $prox_list);
478 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
479 $best = $self->choose_nearest_copy($hold, $prox_list);
483 # hold wasn't fulfilled, record the fact
485 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
486 my $ufh = new Fieldmapper::action::unfulfilled_hold_list;
487 $ufh->hold( $hold->id );
488 $ufh->current_copy( $old_best->id );
489 $ufh->circ_lib( $old_best->circ_lib );
490 $self->method_lookup('open-ils.storage.direct.action.unfulfilled_hold_list.create')->run( $ufh );
494 $hold->current_copy( $best->id );
495 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
498 $hold->prev_check_time( 'now' );
499 my ($r) = $self->method_lookup('open-ils.storage.direct.action.hold_request.update')->run( $hold );
501 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
502 $self->method_lookup('open-ils.storage.transaction.commit')->run;
506 $client->respond("\tProcessing of hold ".$hold->id." failed!.\n\t\t$e\n");
507 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
512 __PACKAGE__->register_method(
513 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
516 method => 'hold_copy_targeter',
521 sub copy_hold_capture {
526 if (!defined($cps)) {
528 ($cps) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.id.atomic')
529 ->run( $hold->target );
533 die "Could not retrieve initial volume list:\n\n$e\n";
537 my @copies = grep { $_->holdable == 1 and $_->ref == 0 } @$cps;
539 for (my $i = 0; $i < @copies; $i++) {
540 next unless $copies[$i];
542 my $cn = $cache{cns}{$copies[$i]->call_number};
543 my $rec = $cache{titles}{$cn->record};
544 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
545 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
546 $copies[$i] = undef if (
548 !($user_filter->run( $hold, $copies[$i], { title => $rec, call_number => $cn } ))[0]
552 @copies = grep { defined $_ } @copies;
556 return unless ($count);
558 my @old_maps = $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.search.hold')->run( $hold->id );
560 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.delete')->run(@old_maps );
563 for my $c (@copies) {
564 my $m = new Fieldmapper::action::hold_copy_map;
565 $m->hold( $hold->id );
566 $m->target_copy( $c->id );
571 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.create')->run( @maps );
577 sub choose_nearest_copy {
580 my $prox_list = shift;
582 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
583 next unless (ref $$prox_list[$p]);
584 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
585 next unless (@capturable);
586 return $capturable[rand(scalar(@capturable))];
590 sub create_prox_list {
596 for my $cp (@$copies) {
597 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
598 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
599 push @{$prox_list[$prox]}, $cp;
604 sub volume_hold_capture {
609 if (!defined($vols)) {
611 ($vols) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.id.atomic')->run( $hold->target );
613 $cache{cns}{$_->id} = $_ for (@$vols);
617 die "Could not retrieve initial volume list:\n\n$e\n";
621 my @v_ids = map { $_->id } @$vols;
625 ($cp_list) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.call_number.atomic')->run( \@v_ids );
629 warn "Could not retrieve copy list:\n\n$e\n";
632 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
635 sub title_hold_capture {
640 if (!defined($titles)) {
642 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( $hold->target );
644 $cache{titles}{$_->id} = $_ for (@$titles);
648 die "Could not retrieve initial title list:\n\n$e\n";
652 my @t_ids = map { $_->id } @$titles;
655 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
659 warn "Could not retrieve volume list:\n\n$e\n";
662 $cache{cns}{$_->id} = $_ for (@$cn_list);
664 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
667 sub metarecord_hold_capture {
673 ($titles) = $self->method_lookup('open-ils.storage.ordered.metabib.metarecord.records.atomic')->run( $hold->target );
677 die "Could not retrieve initial title list:\n\n$e\n";
681 my @recs = map {$_->record}
682 $self->method_lookup('open-ils.storage.direct.metabib.record_descriptor.search')
683 ->run( record => $titles, item_type => [split '', $hold->holdable_formats] );
686 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( \@recs );
690 die "Could not retrieve format-pruned title list:\n\n$e\n";
694 $cache{titles}{$_->id} = $_ for (@$titles);
696 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);