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 $c_t = action::circulation->table;
19 $grace = " - ($grace * (fine_interval))" if ($grace);
24 WHERE stop_fines IS NULL
25 AND due_date < ( CURRENT_TIMESTAMP $grace)
28 my $sth = action::circulation->db_Main->prepare_cached($sql);
31 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
38 my $grace = shift || '';
40 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
45 __PACKAGE__->register_method(
46 api_name => 'open-ils.storage.action.circulation.overdue',
49 method => 'grab_overdue',
58 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $pl,$cp);
60 FROM action.hold_request h
61 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
62 WHERE h.pickup_lib = ?
63 AND hm.target_copy = ?
64 AND h.capture_time IS NULL
65 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.request_time
70 __PACKAGE__->register_method(
71 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
73 method => 'nearest_hold',
76 sub next_resp_group_id {
80 # XXX This is not replication safe!!!
82 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
83 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
87 __PACKAGE__->register_method(
88 api_name => 'open-ils.storage.action.survey_response.next_group_id',
90 method => 'next_resp_group_id',
93 sub patron_circ_summary {
98 return undef unless ($id);
99 my $c_table = action::circulation->table;
100 my $b_table = money::billing->table;
102 my $select = <<" SQL";
103 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
105 LEFT OUTER JOIN $b_table b ON (c.id = b.xact)
107 AND c.xact_finish IS NULL
108 AND c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
111 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
113 __PACKAGE__->register_method(
114 api_name => 'open-ils.storage.action.circulation.patron_summary',
116 method => 'patron_circ_summary',
119 #XXX Fix stored proc calls
120 sub find_local_surveys {
125 return undef unless ($ou);
126 my $s_table = action::survey->table;
128 my $select = <<" SQL";
131 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
132 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
135 my $sth = action::survey->db_Main->prepare_cached($select);
138 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
142 __PACKAGE__->register_method(
143 api_name => 'open-ils.storage.action.survey.all',
146 method => 'find_local_surveys',
149 #XXX Fix stored proc calls
150 sub find_opac_surveys {
155 return undef unless ($ou);
156 my $s_table = action::survey->table;
158 my $select = <<" SQL";
161 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
162 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
166 my $sth = action::survey->db_Main->prepare_cached($select);
169 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
173 __PACKAGE__->register_method(
174 api_name => 'open-ils.storage.action.survey.opac',
177 method => 'find_opac_surveys',
180 sub find_optional_surveys {
185 return undef unless ($ou);
186 my $s_table = action::survey->table;
188 my $select = <<" SQL";
191 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
192 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
193 AND s.required IS FALSE;
196 my $sth = action::survey->db_Main->prepare_cached($select);
199 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
203 __PACKAGE__->register_method(
204 api_name => 'open-ils.storage.action.survey.optional',
207 method => 'find_optional_surveys',
210 sub find_required_surveys {
215 return undef unless ($ou);
216 my $s_table = action::survey->table;
218 my $select = <<" SQL";
221 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
222 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
223 AND s.required IS TRUE;
226 my $sth = action::survey->db_Main->prepare_cached($select);
229 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
233 __PACKAGE__->register_method(
234 api_name => 'open-ils.storage.action.survey.required',
237 method => 'find_required_surveys',
240 sub find_usr_summary_surveys {
245 return undef unless ($ou);
246 my $s_table = action::survey->table;
248 my $select = <<" SQL";
251 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
252 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
253 AND s.usr_summary IS TRUE;
256 my $sth = action::survey->db_Main->prepare_cached($select);
259 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
263 __PACKAGE__->register_method(
264 api_name => 'open-ils.storage.action.survey.usr_summary',
267 method => 'find_usr_summary_surveys',
280 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
282 push @circs, overdue_circs($grace);
288 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
290 my $due = $due_dt->epoch;
292 my $fine_interval = interval_to_seconds( $c->fine_interval );
294 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
295 my $tz_offset_s = 0;;
296 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
297 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
300 $due -= ($due % $fine_interval) + $tz_offset_s;
301 $now -= ($now % $fine_interval) + $tz_offset_s;
305 "ARG! Overdue circulation ".$c->id.
306 " for item ".$c->target_copy.
307 " (user ".$c->usr.").\n".
308 "\tItem was due on or before: ".localtime($due)."\n");
310 my ($fine) = money::billing->search(
311 xact => $c->id, voided => 'f',
312 { order_by => 'billing_ts DESC', limit => '1' }
317 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
320 $last_fine += $fine_interval * $grace;
323 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
324 unless($pending_fine_count) {
325 $client->respond( "\tNo fines to create. " );
326 if ($grace && $now < $due + $fine_interval * $grace) {
327 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
329 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
334 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
336 for my $bill (1 .. $pending_fine_count) {
338 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
340 if ($total && $total->balance_owed > $c->max_fine) {
341 $c->update({stop_fines => 'MAXFINES'});
343 "\tMaximum fine level of ".$c->max_fine.
344 " reached for this circulation.\n".
345 "\tNo more fines will be generated.\n" );
349 my $billing = money::billing->create(
351 note => "Overdue Fine",
352 billing_type => "Overdue materials",
353 amount => ''.$c->recuring_fine,
354 billing_ts => DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
359 "\t\tCreating fine of ".$billing->amount." for period starting ".
361 $parser->parse_datetime(
362 clense_ISO8601( $billing->billing_ts )
368 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
372 __PACKAGE__->register_method(
373 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
376 method => 'generate_fines',
383 my %cache = (titles => {}, cns => {});
384 sub hold_copy_targeter {
387 my $check_expire = shift;
388 my $one_hold = shift;
390 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
391 $self->{user_filter}->connect;
392 $self->{client} = $client;
395 $check_expire ||= '12h';
396 $check_expire = interval_to_seconds( $check_expire );
398 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
401 my $expire_threshold = sprintf(
402 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
403 $year, $mon, $mday, $hour, $min, $sec
407 $statuses ||= [ config::copy_status->search(holdable => 't') ];
409 $locations ||= [ asset::copy_location->search(holdable => 't') ];
413 %cache = (titles => {}, cns => {});
417 $holds = [ action::hold_request->search(id => $one_hold) ];
419 $holds = [ action::hold_request->search_where(
420 { capture_time => undef,
421 prev_check_time => { '<=' => $expire_threshold },
423 { order_by => 'request_time,prev_check_time' } ) ];
424 push @$holds, action::hold_request->search(
425 capture_time => undef,
426 prev_check_time => undef,
427 { order_by => 'request_time' } );
431 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
434 for my $hold (@$holds) {
435 action::hold_request->db_Main->begin_work;
437 $client->respond("Processing hold ".$hold->id."...\n");
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 unless (ref $copies || !@$copies) {
453 $client->respond("\tNo copies available for targeting at all!\n");
457 for my $c (@$copies) {
458 next if ( grep {$c->id == $hold->current_copy} @good_copies);
459 push @good_copies, $c if ($c);
462 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
464 my $old_best = $hold->current_copy;
465 $hold->update({ current_copy => undef });
467 if (!scalar(@good_copies)) {
468 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
469 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
470 $client->respond("\tPushing current_copy back onto the targeting list\n");
471 push @good_copies, asset::copy->retrieve( $old_best );
473 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
479 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
480 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
482 my $best = $self->choose_nearest_copy($hold, $prox_list);
485 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
486 $best = $self->choose_nearest_copy($hold, $prox_list);
490 # hold wasn't fulfilled, record the fact
492 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
493 action::unfulfilled_hold_list->create(
494 { hold => ''.$hold->id,
495 current_copy => ''.$old_best->id,
496 circ_lib => ''.$old_best->circ_lib,
501 $hold->update( { current_copy => ''.$best->id } );
502 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
505 $hold->update( { prev_check_time => 'now' } );
506 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
508 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
509 $self->method_lookup('open-ils.storage.transaction.commit')->run;
511 action::hold_request->dbi_commit;
515 $client->respond("\tProcessing of hold ".$hold->id." failed!.\n\t\t$e\n");
516 action::hold_request->dbi_rollback;
520 $self->{user_filter}->disconnect;
521 $self->{user_filter}->finish;
522 delete $$self{user_filter};
525 __PACKAGE__->register_method(
526 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
529 method => 'hold_copy_targeter',
534 sub copy_hold_capture {
539 if (!defined($cps)) {
541 $cps = [ asset::copy->search( id => $hold->target ) ];
544 die "Could not retrieve initial volume list:\n\n$e\n";
548 my @copies = grep { $_->holdable and !$_->ref } @$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->to_fieldmapper, do {
562 my $cp_fm = $copies[$i]->to_fieldmapper;
563 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
564 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
565 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
568 { title => $rec->to_fieldmapper,
569 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
570 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
573 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
576 @copies = grep { $_ } @copies;
580 return unless ($count);
582 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
585 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
586 for my $c (@copies) {
587 push @maps, action::hold_copy_map->create( { hold => ''.$hold->id, target_copy => ''.$c->id } );
594 sub choose_nearest_copy {
597 my $prox_list = shift;
599 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
600 next unless (ref $$prox_list[$p]);
601 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
602 next unless (@capturable);
603 return $capturable[rand(scalar(@capturable))];
607 sub create_prox_list {
613 for my $cp (@$copies) {
614 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
615 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
616 push @{$prox_list[$prox]}, $cp;
621 sub volume_hold_capture {
626 if (!defined($vols)) {
628 $vols = [ asset::call_number->search( id => $hold->target ) ];
629 $cache{cns}{$_->id} = $_ for (@$vols);
632 die "Could not retrieve initial volume list:\n\n$e\n";
636 my @v_ids = map { $_->id } @$vols;
640 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
644 warn "Could not retrieve copy list:\n\n$e\n";
647 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
650 sub title_hold_capture {
655 if (!defined($titles)) {
657 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
658 $cache{titles}{$_->id} = $_ for (@$titles);
661 die "Could not retrieve initial title list:\n\n$e\n";
665 my @t_ids = map { $_->id } @$titles;
668 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
672 warn "Could not retrieve volume list:\n\n$e\n";
675 $cache{cns}{$_->id} = $_ for (@$cn_list);
677 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
680 sub metarecord_hold_capture {
686 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
690 die "Could not retrieve initial title list:\n\n$e\n";
694 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
696 $titles = [ biblio::record_entry->search( id => \@recs ) ];
700 die "Could not retrieve format-pruned title list:\n\n$e\n";
704 $cache{titles}{$_->id} = $_ for (@$titles);
705 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);