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;
391 $self->{client} = $client;
394 $check_expire ||= '12h';
395 $check_expire = interval_to_seconds( $check_expire );
397 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
400 my $expire_threshold = sprintf(
401 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
402 $year, $mon, $mday, $hour, $min, $sec
405 $self->method_lookup( 'open-ils.storage.transaction.begin')->run($client);
407 ($statuses) = $self->method_lookup('open-ils.storage.direct.config.copy_status.search.holdable.atomic')->run('t');
409 ($locations) = $self->method_lookup('open-ils.storage.direct.asset.copy_location.search.holdable.atomic')->run('t');
413 %cache = (titles => {}, cns => {});
417 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search.atomic')
418 ->run(id => $one_hold);
420 ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search_where.atomic')
422 { capture_time => undef,
423 prev_check_time => { '<=' => $expire_threshold },
425 { order_by => 'request_time,prev_check_time' } );
426 push @$holds, $self->method_lookup('open-ils.storage.direct.action.hold_request.search')
428 { capture_time => undef,
429 prev_check_time => undef },
430 { order_by => 'request_time' } );
434 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
437 for my $hold (@$holds) {
441 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
442 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
444 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
445 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
447 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
448 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
450 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
452 $client->respond("Processing hold ".$hold->id."...\n");
453 unless (ref $copies || !@$copies) {
454 $client->respond("\tNo copies available for targeting at all!\n");
458 for my $c (@$copies) {
459 next if ( grep {$c->id == $hold->current_copy} @good_copies);
460 push @good_copies, $c if ($c);
463 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
465 my $old_best = $hold->current_copy;
466 $hold->clear_current_copy;
468 if (!scalar(@good_copies)) {
469 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
470 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
471 $client->respond("\tPushing current_copy back onto the targeting list\n");
472 push @good_copies, $self->method_lookup('open-ils.storage.direct.asset.copy.retrieve')->run( $old_best );
474 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
480 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
481 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
483 my $best = $self->choose_nearest_copy($hold, $prox_list);
486 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
487 $best = $self->choose_nearest_copy($hold, $prox_list);
491 # hold wasn't fulfilled, record the fact
493 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
494 my $ufh = new Fieldmapper::action::unfulfilled_hold_list;
495 $ufh->hold( $hold->id );
496 $ufh->current_copy( $old_best->id );
497 $ufh->circ_lib( $old_best->circ_lib );
498 $self->method_lookup('open-ils.storage.direct.action.unfulfilled_hold_list.create')->run( $ufh );
502 $hold->current_copy( $best->id );
503 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
506 $hold->prev_check_time( 'now' );
507 my ($r) = $self->method_lookup('open-ils.storage.direct.action.hold_request.update')->run( $hold );
509 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
510 $self->method_lookup('open-ils.storage.transaction.commit')->run;
514 $client->respond("\tProcessing of hold ".$hold->id." failed!.\n\t\t$e\n");
515 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
518 $self->{user_filter}->disconnect;
519 $self->{user_filter}->finish;
520 delete $$self{user_filter};
523 __PACKAGE__->register_method(
524 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
527 method => 'hold_copy_targeter',
532 sub copy_hold_capture {
537 if (!defined($cps)) {
539 ($cps) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.id.atomic')
540 ->run( $hold->target );
544 die "Could not retrieve initial volume list:\n\n$e\n";
548 my @copies = grep { $_->holdable == 1 and $_->ref == 0 } @$cps;
550 for (my $i = 0; $i < @copies; $i++) {
551 next unless $copies[$i];
553 my $cn = $cache{cns}{$copies[$i]->call_number};
554 my $rec = $cache{titles}{$cn->record};
555 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
556 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
557 $copies[$i] = undef if (
559 !$self->{user_filter}->request(
560 'open-ils.circ.permit_hold',
561 $hold => $copies[$i],
562 { title => $rec, call_number => $cn }
565 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
568 @copies = grep { defined $_ } @copies;
572 return unless ($count);
574 my @old_maps = $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.search.hold')->run( $hold->id );
576 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.delete')->run(@old_maps );
579 for my $c (@copies) {
580 my $m = new Fieldmapper::action::hold_copy_map;
581 $m->hold( $hold->id );
582 $m->target_copy( $c->id );
587 $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.create')->run( @maps );
593 sub choose_nearest_copy {
596 my $prox_list = shift;
598 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
599 next unless (ref $$prox_list[$p]);
600 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
601 next unless (@capturable);
602 return $capturable[rand(scalar(@capturable))];
606 sub create_prox_list {
612 for my $cp (@$copies) {
613 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
614 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
615 push @{$prox_list[$prox]}, $cp;
620 sub volume_hold_capture {
625 if (!defined($vols)) {
627 ($vols) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.id.atomic')->run( $hold->target );
629 $cache{cns}{$_->id} = $_ for (@$vols);
633 die "Could not retrieve initial volume list:\n\n$e\n";
637 my @v_ids = map { $_->id } @$vols;
641 ($cp_list) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.call_number.atomic')->run( \@v_ids );
645 warn "Could not retrieve copy list:\n\n$e\n";
648 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
651 sub title_hold_capture {
656 if (!defined($titles)) {
658 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( $hold->target );
660 $cache{titles}{$_->id} = $_ for (@$titles);
664 die "Could not retrieve initial title list:\n\n$e\n";
668 my @t_ids = map { $_->id } @$titles;
671 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
675 warn "Could not retrieve volume list:\n\n$e\n";
678 $cache{cns}{$_->id} = $_ for (@$cn_list);
680 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
683 sub metarecord_hold_capture {
689 ($titles) = $self->method_lookup('open-ils.storage.ordered.metabib.metarecord.records.atomic')->run( $hold->target );
693 die "Could not retrieve initial title list:\n\n$e\n";
697 my @recs = map {$_->record}
698 $self->method_lookup('open-ils.storage.direct.metabib.record_descriptor.search')
699 ->run( record => $titles, item_type => [split '', $hold->holdable_formats] );
702 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( \@recs );
706 die "Could not retrieve format-pruned title list:\n\n$e\n";
710 $cache{titles}{$_->id} = $_ for (@$titles);
712 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);