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::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
9 use DateTime::Format::ISO8601;
11 my $parser = DateTime::Format::ISO8601->new;
12 my $log = 'OpenSRF::Utils::Logger';
17 my $grace = shift || '';
19 my $c_t = action::circulation->table;
21 $grace = " - ($grace * (fine_interval))" if ($grace);
26 WHERE stop_fines IS NULL
27 AND due_date < ( CURRENT_TIMESTAMP $grace)
30 my $sth = action::circulation->db_Main->prepare_cached($sql);
33 $client->respond( $_->to_fieldmapper ) for ( map { action::circulation->construct($_) } $sth->fetchall_hash );
38 __PACKAGE__->register_method(
39 api_name => 'open-ils.storage.action.circulation.overdue',
42 method => 'grab_overdue',
51 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $pl,$cp);
53 FROM action.hold_request h
54 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
55 WHERE h.pickup_lib = ?
56 AND hm.target_copy = ?
57 AND h.capture_time IS NULL
58 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.request_time
63 __PACKAGE__->register_method(
64 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
66 method => 'nearest_hold',
69 sub next_resp_group_id {
73 # XXX This is not replication safe!!!
75 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
76 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
80 __PACKAGE__->register_method(
81 api_name => 'open-ils.storage.action.survey_response.next_group_id',
83 method => 'next_resp_group_id',
86 sub patron_circ_summary {
91 return undef unless ($id);
92 my $c_table = action::circulation->table;
93 my $b_table = money::billing->table;
95 my $select = <<" SQL";
96 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
98 LEFT OUTER JOIN $b_table b ON (c.id = b.xact)
100 AND c.xact_finish IS NULL
101 AND c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
104 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
106 __PACKAGE__->register_method(
107 api_name => 'open-ils.storage.action.circulation.patron_summary',
109 method => 'patron_circ_summary',
112 #XXX Fix stored proc calls
113 sub find_local_surveys {
118 return undef unless ($ou);
119 my $s_table = action::survey->table;
121 my $select = <<" SQL";
124 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
125 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
128 my $sth = action::survey->db_Main->prepare_cached($select);
131 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
135 __PACKAGE__->register_method(
136 api_name => 'open-ils.storage.action.survey.all',
139 method => 'find_local_surveys',
142 #XXX Fix stored proc calls
143 sub find_opac_surveys {
148 return undef unless ($ou);
149 my $s_table = action::survey->table;
151 my $select = <<" SQL";
154 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
155 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
159 my $sth = action::survey->db_Main->prepare_cached($select);
162 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
166 __PACKAGE__->register_method(
167 api_name => 'open-ils.storage.action.survey.opac',
170 method => 'find_opac_surveys',
173 sub find_optional_surveys {
178 return undef unless ($ou);
179 my $s_table = action::survey->table;
181 my $select = <<" SQL";
184 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
185 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
186 AND s.required IS FALSE;
189 my $sth = action::survey->db_Main->prepare_cached($select);
192 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
196 __PACKAGE__->register_method(
197 api_name => 'open-ils.storage.action.survey.optional',
200 method => 'find_optional_surveys',
203 sub find_required_surveys {
208 return undef unless ($ou);
209 my $s_table = action::survey->table;
211 my $select = <<" SQL";
214 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
215 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
216 AND s.required IS TRUE;
219 my $sth = action::survey->db_Main->prepare_cached($select);
222 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
226 __PACKAGE__->register_method(
227 api_name => 'open-ils.storage.action.survey.required',
230 method => 'find_required_surveys',
233 sub find_usr_summary_surveys {
238 return undef unless ($ou);
239 my $s_table = action::survey->table;
241 my $select = <<" SQL";
244 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
245 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
246 AND s.usr_summary IS TRUE;
249 my $sth = action::survey->db_Main->prepare_cached($select);
252 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
256 __PACKAGE__->register_method(
257 api_name => 'open-ils.storage.action.survey.usr_summary',
260 method => 'find_usr_summary_surveys',
274 $self->method_lookup(
275 'open-ils.storage.direct.action.circulation.search_where'
276 )->run( { id => $circ, stop_fines => undef } );
278 push @circs, $self->method_lookup('open-ils.storage.action.circulation.overdue')->run( $grace );
284 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
286 my $due = $due_dt->epoch;
288 my $fine_interval = interval_to_seconds( $c->fine_interval );
290 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
291 my $tz_offset_s = 0;;
292 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
293 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
296 $due -= ($due % $fine_interval) + $tz_offset_s;
297 $now -= ($now % $fine_interval) + $tz_offset_s;
301 "ARG! Overdue circulation ".$c->id.
302 " for item ".$c->target_copy.
303 " (user ".$c->usr.").\n".
304 "\tItem was due on or before: ".localtime($due)."\n");
306 my ($fine) = $self->method_lookup('open-ils.storage.direct.money.billing.search')->run(
307 { xact => $c->id, voided => 'f' },
308 { order_by => 'billing_ts DESC', limit => '1' }
313 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
316 $last_fine += $fine_interval * $grace;
319 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
320 unless($pending_fine_count) {
321 $client->respond( "\tNo fines to create. " );
322 if ($grace && $now < $due + $fine_interval * $grace) {
323 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
325 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
330 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
332 for my $bill (1 .. $pending_fine_count) {
334 my ($total) = $self->method_lookup('open-ils.storage.direct.money.billable_transaction_summary.retrieve')->run( $c->id );
336 if ($total && $total->balance_owed > $c->max_fine) {
337 $c->stop_fines('MAXFINES');
338 $self->method_lookup('open-ils.storage.direct.action.circulation.update')->run( $c );
340 "\tMaximum fine level of ".$c->max_fine.
341 " reached for this circulation.\n".
342 "\tNo more fines will be generated.\n" );
346 my $billing = new Fieldmapper::money::billing;
347 $billing->xact( $c->id );
348 $billing->note( "Overdue Fine" );
349 $billing->amount( $c->recuring_fine );
351 $billing->billing_ts(
352 DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
356 "\t\tCreating fine of ".$billing->amount." for period starting ".
358 $parser->parse_datetime(
359 clense_ISO8601( $billing->billing_ts )
363 $self->method_lookup('open-ils.storage.direct.money.billing.create')->run( $billing );
367 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
371 __PACKAGE__->register_method(
372 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
375 method => 'generate_fines',
382 my %cache = (titles => {}, cns => {});
383 sub hold_copy_targeter {
386 my $check_expire = shift;
387 my $one_hold = shift;
389 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
390 $self->{user_filter}->connect;
393 $check_expire ||= '12h';
394 $check_expire = interval_to_seconds( $check_expire );
396 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
399 my $expire_threshold = sprintf(
400 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
401 $year, $mon, $mday, $hour, $min, $sec
404 $self->method_lookup( 'open-ils.storage.transaction.begin')->run($client);
406 ($statuses) = $self->method_lookup('open-ils.storage.direct.config.copy_status.search.holdable.atomic')->run('t');
408 ($locations) = $self->method_lookup('open-ils.storage.direct.asset.copy_location.search.holdable.atomic')->run('t');
412 %cache = (titles => {}, cns => {});
416 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search.atomic')
417 ->run(id => $one_hold);
419 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search_where.atomic')
421 { capture_time => undef,
422 prev_check_time => { '<=' => $expire_threshold },
424 { order_by => 'request_time,prev_check_time' } );
425 push @$holds, $self->method_lookup('open-ils.storage.direct.action.hold_request.search')
427 { capture_time => undef,
428 prev_check_time => undef },
429 { order_by => 'request_time' } );
433 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
436 for my $hold (@$holds) {
440 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
441 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
442 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
443 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
445 $client->respond("Processing hold ".$hold->id."...\n");
446 unless (ref $copies) {
447 $client->respond("\tNo copies available for targeting!\n");
452 for my $c (@$copies) {
453 next if ( grep {$c->id == $hold->current_copy} @good_copies);
454 push @good_copies, $c if ($c);
457 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
459 my $old_best = $hold->current_copy;
460 $hold->clear_current_copy;
462 if (!scalar(@good_copies)) {
463 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
464 $client->respond("\tPushing current_copy back onto the targeting list\n");
465 push @good_copies, $self->method_lookup('open-ils.storage.direct.asset.copy.retrieve')->run( $old_best );
467 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT!\n");
473 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
474 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
476 my $best = $self->choose_nearest_copy($hold, $prox_list);
479 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
480 $best = $self->choose_nearest_copy($hold, $prox_list);
484 # hold wasn't fulfilled, record the fact
486 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
487 my $ufh = new Fieldmapper::action::unfulfilled_hold_list;
488 $ufh->hold( $hold->id );
489 $ufh->current_copy( $old_best->id );
490 $ufh->circ_lib( $old_best->circ_lib );
491 $self->method_lookup('open-ils.storage.direct.action.unfulfilled_hold_list.create')->run( $ufh );
495 $hold->current_copy( $best->id );
496 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
499 $hold->prev_check_time( 'now' );
500 my ($r) = $self->method_lookup('open-ils.storage.direct.action.hold_request.update')->run( $hold );
502 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
503 $self->method_lookup('open-ils.storage.transaction.commit')->run;
507 $client->respond("\tProcessing of hold ".$hold->id." failed!.\n\t\t$e\n");
508 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
511 $self->{user_filter}->disconnect;
512 $self->{user_filter}->finish;
513 delete $$self{user_filter};
516 __PACKAGE__->register_method(
517 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
520 method => 'hold_copy_targeter',
525 sub copy_hold_capture {
530 if (!defined($cps)) {
532 ($cps) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.id.atomic')
533 ->run( $hold->target );
537 die "Could not retrieve initial volume list:\n\n$e\n";
541 my @copies = grep { $_->holdable == 1 and $_->ref == 0 } @$cps;
543 for (my $i = 0; $i < @copies; $i++) {
544 next unless $copies[$i];
546 my $cn = $cache{cns}{$copies[$i]->call_number};
547 my $rec = $cache{titles}{$cn->record};
548 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
549 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
550 $copies[$i] = undef if (
552 !$self->{user_filter}->request(
553 'open-ils.circ.permit_hold',
554 $hold => $copies[$i],
555 { title => $rec, call_number => $cn }
560 @copies = grep { defined $_ } @copies;
564 return unless ($count);
566 my @old_maps = $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.search.hold')->run( $hold->id );
568 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.delete')->run(@old_maps );
571 for my $c (@copies) {
572 my $m = new Fieldmapper::action::hold_copy_map;
573 $m->hold( $hold->id );
574 $m->target_copy( $c->id );
579 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.create')->run( @maps );
585 sub choose_nearest_copy {
588 my $prox_list = shift;
590 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
591 next unless (ref $$prox_list[$p]);
592 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
593 next unless (@capturable);
594 return $capturable[rand(scalar(@capturable))];
598 sub create_prox_list {
604 for my $cp (@$copies) {
605 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
606 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
607 push @{$prox_list[$prox]}, $cp;
612 sub volume_hold_capture {
617 if (!defined($vols)) {
619 ($vols) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.id.atomic')->run( $hold->target );
621 $cache{cns}{$_->id} = $_ for (@$vols);
625 die "Could not retrieve initial volume list:\n\n$e\n";
629 my @v_ids = map { $_->id } @$vols;
633 ($cp_list) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.call_number.atomic')->run( \@v_ids );
637 warn "Could not retrieve copy list:\n\n$e\n";
640 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
643 sub title_hold_capture {
648 if (!defined($titles)) {
650 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( $hold->target );
652 $cache{titles}{$_->id} = $_ for (@$titles);
656 die "Could not retrieve initial title list:\n\n$e\n";
660 my @t_ids = map { $_->id } @$titles;
663 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
667 warn "Could not retrieve volume list:\n\n$e\n";
670 $cache{cns}{$_->id} = $_ for (@$cn_list);
672 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
675 sub metarecord_hold_capture {
681 ($titles) = $self->method_lookup('open-ils.storage.ordered.metabib.metarecord.records.atomic')->run( $hold->target );
685 die "Could not retrieve initial title list:\n\n$e\n";
689 my @recs = map {$_->record}
690 $self->method_lookup('open-ils.storage.direct.metabib.record_descriptor.search')
691 ->run( record => $titles, item_type => [split '', $hold->holdable_formats] );
694 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( \@recs );
698 die "Could not retrieve format-pruned title list:\n\n$e\n";
702 $cache{titles}{$_->id} = $_ for (@$titles);
704 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);