]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
added targeted, uncaptured hold_request method
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Storage / Publisher / action.pm
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;
8 use OpenILS::Utils::PermitHold;
9 use DateTime;
10 use DateTime::Format::ISO8601;
11
12
13 my $parser = DateTime::Format::ISO8601->new;
14 my $log = 'OpenSRF::Utils::Logger';
15
16 sub ou_hold_requests {
17         my $self = shift;
18         my $client = shift;
19         my $ou = shift;
20
21         my $h_table = action::hold_request->table;
22         my $c_table = asset::copy->table;
23         my $o_table = actor::org_unit->table;
24
25         my $SQL = <<"   SQL";
26                 SELECT  h.id
27                   FROM  $h_table h
28                         JOIN $c_table cp ON (cp.id = h.current_copy)
29                         JOIN $o_table ou ON (ou.id = cp.circ_lib)
30                   WHERE ou.id = ?
31                         AND h.capture_time IS NULL
32                   ORDER BY h.request_time
33         SQL
34
35         my $sth = action::hold_request->db_Main->prepare_cached($SQL);
36         $sth->execute($ou);
37
38         $client->respond($_) for (
39                 map {
40                         $self
41                                 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
42                                 ->run($_)
43                 } map {
44                         $_->[0]
45                 } @{ $sth->fetchall_arrayref }
46         );
47         return undef;
48 }
49 __PACKAGE__->register_method(
50         api_name        => 'open-ils.storage.action.targeted_hold_request.org_unit',
51         api_level       => 1,
52         argc            => 1,
53         stream          => 1,
54         method          => 'ou_hold_requests',
55 );
56
57
58 sub overdue_circs {
59         my $grace = shift;
60
61         my $c_t = action::circulation->table;
62
63         $grace = " - ($grace * (fine_interval))" if ($grace);
64
65         my $sql = <<"   SQL";
66                 SELECT  *
67                   FROM  $c_t
68                   WHERE stop_fines IS NULL
69                         AND due_date < ( CURRENT_TIMESTAMP $grace)
70         SQL
71
72         my $sth = action::circulation->db_Main->prepare_cached($sql);
73         $sth->execute;
74
75         return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
76
77 }
78
79 sub grab_overdue {
80         my $self = shift;
81         my $client = shift;
82         my $grace = shift || '';
83
84         $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
85
86         return undef;
87
88 }
89 __PACKAGE__->register_method(
90         api_name        => 'open-ils.storage.action.circulation.overdue',
91         api_level       => 1,
92         stream          => 1,
93         method          => 'grab_overdue',
94 );
95
96 sub nearest_hold {
97         my $self = shift;
98         my $client = shift;
99         my $pl = shift;
100         my $cp = shift;
101
102         my ($id) = action::hold_request->db_Main->selectrow_array(<<"   SQL", {}, $pl,$cp);
103                 SELECT  h.id
104                   FROM  action.hold_request h
105                         JOIN action.hold_copy_map hm ON (hm.hold = h.id)
106                   WHERE h.pickup_lib = ?
107                         AND hm.target_copy = ?
108                         AND h.capture_time IS NULL
109                 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.selection_depth DESC, h.request_time
110                 LIMIT 1
111         SQL
112         return $id;
113 }
114 __PACKAGE__->register_method(
115         api_name        => 'open-ils.storage.action.hold_request.nearest_hold',
116         api_level       => 1,
117         method          => 'nearest_hold',
118 );
119
120 sub next_resp_group_id {
121         my $self = shift;
122         my $client = shift;
123
124         # XXX This is not replication safe!!!
125
126         my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
127                 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
128         SQL
129         return $id;
130 }
131 __PACKAGE__->register_method(
132         api_name        => 'open-ils.storage.action.survey_response.next_group_id',
133         api_level       => 1,
134         method          => 'next_resp_group_id',
135 );
136
137 sub patron_circ_summary {
138         my $self = shift;
139         my $client = shift;
140         my $id = ''.shift();
141
142         return undef unless ($id);
143         my $c_table = action::circulation->table;
144         my $b_table = money::billing->table;
145
146         $log->debug("Retrieving patron summary for id $id", DEBUG);
147
148         my $select = <<"        SQL";
149                 SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
150                   FROM  $c_table c
151                         LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
152                   WHERE c.usr = ?
153                         AND c.xact_finish IS NULL
154                         AND (
155                                 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
156                                 OR c.stop_fines IS NULL
157                         )
158         SQL
159
160         return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
161 }
162 __PACKAGE__->register_method(
163         api_name        => 'open-ils.storage.action.circulation.patron_summary',
164         api_level       => 1,
165         method          => 'patron_circ_summary',
166 );
167
168 #XXX Fix stored proc calls
169 sub find_local_surveys {
170         my $self = shift;
171         my $client = shift;
172         my $ou = ''.shift();
173
174         return undef unless ($ou);
175         my $s_table = action::survey->table;
176
177         my $select = <<"        SQL";
178                 SELECT  s.*
179                   FROM  $s_table s
180                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
181                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
182         SQL
183
184         my $sth = action::survey->db_Main->prepare_cached($select);
185         $sth->execute($ou);
186
187         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
188
189         return undef;
190 }
191 __PACKAGE__->register_method(
192         api_name        => 'open-ils.storage.action.survey.all',
193         api_level       => 1,
194         stream          => 1,
195         method          => 'find_local_surveys',
196 );
197
198 #XXX Fix stored proc calls
199 sub find_opac_surveys {
200         my $self = shift;
201         my $client = shift;
202         my $ou = ''.shift();
203
204         return undef unless ($ou);
205         my $s_table = action::survey->table;
206
207         my $select = <<"        SQL";
208                 SELECT  s.*
209                   FROM  $s_table s
210                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
211                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
212                         AND s.opac IS TRUE;
213         SQL
214
215         my $sth = action::survey->db_Main->prepare_cached($select);
216         $sth->execute($ou);
217
218         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
219
220         return undef;
221 }
222 __PACKAGE__->register_method(
223         api_name        => 'open-ils.storage.action.survey.opac',
224         api_level       => 1,
225         stream          => 1,
226         method          => 'find_opac_surveys',
227 );
228
229 sub find_optional_surveys {
230         my $self = shift;
231         my $client = shift;
232         my $ou = ''.shift();
233
234         return undef unless ($ou);
235         my $s_table = action::survey->table;
236
237         my $select = <<"        SQL";
238                 SELECT  s.*
239                   FROM  $s_table s
240                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
241                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
242                         AND s.required IS FALSE;
243         SQL
244
245         my $sth = action::survey->db_Main->prepare_cached($select);
246         $sth->execute($ou);
247
248         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
249
250         return undef;
251 }
252 __PACKAGE__->register_method(
253         api_name        => 'open-ils.storage.action.survey.optional',
254         api_level       => 1,
255         stream          => 1,
256         method          => 'find_optional_surveys',
257 );
258
259 sub find_required_surveys {
260         my $self = shift;
261         my $client = shift;
262         my $ou = ''.shift();
263
264         return undef unless ($ou);
265         my $s_table = action::survey->table;
266
267         my $select = <<"        SQL";
268                 SELECT  s.*
269                   FROM  $s_table s
270                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
271                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
272                         AND s.required IS TRUE;
273         SQL
274
275         my $sth = action::survey->db_Main->prepare_cached($select);
276         $sth->execute($ou);
277
278         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
279
280         return undef;
281 }
282 __PACKAGE__->register_method(
283         api_name        => 'open-ils.storage.action.survey.required',
284         api_level       => 1,
285         stream          => 1,
286         method          => 'find_required_surveys',
287 );
288
289 sub find_usr_summary_surveys {
290         my $self = shift;
291         my $client = shift;
292         my $ou = ''.shift();
293
294         return undef unless ($ou);
295         my $s_table = action::survey->table;
296
297         my $select = <<"        SQL";
298                 SELECT  s.*
299                   FROM  $s_table s
300                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
301                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
302                         AND s.usr_summary IS TRUE;
303         SQL
304
305         my $sth = action::survey->db_Main->prepare_cached($select);
306         $sth->execute($ou);
307
308         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
309
310         return undef;
311 }
312 __PACKAGE__->register_method(
313         api_name        => 'open-ils.storage.action.survey.usr_summary',
314         api_level       => 1,
315         stream          => 1,
316         method          => 'find_usr_summary_surveys',
317 );
318
319
320 sub generate_fines {
321         my $self = shift;
322         my $client = shift;
323         my $grace = shift;
324         my $circ = shift;
325         
326         
327         my @circs;
328         if ($circ) {
329                 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
330         } else {
331                 push @circs, overdue_circs($grace);
332         }
333
334         for my $c (@circs) {
335         
336                 try {
337                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
338         
339                         my $due = $due_dt->epoch;
340                         my $now = time;
341                         my $fine_interval = interval_to_seconds( $c->fine_interval );
342         
343                         if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {  
344                                 my $tz_offset_s = 0;;
345                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
346                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
347                                 }
348         
349                                 $due -= ($due % $fine_interval) + $tz_offset_s;
350                                 $now -= ($now % $fine_interval) + $tz_offset_s;
351                         }
352         
353                         $client->respond(
354                                 "ARG! Overdue circulation ".$c->id.
355                                 " for item ".$c->target_copy.
356                                 " (user ".$c->usr.").\n".
357                                 "\tItem was due on or before: ".localtime($due)."\n");
358         
359                         my ($fine) = money::billing->search(
360                                 xact => $c->id, voided => 'f',
361                                 { order_by => 'billing_ts DESC', limit => '1' }
362                         );
363         
364                         my $last_fine;
365                         if ($fine) {
366                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
367                         } else {
368                                 $last_fine = $due;
369                                 $last_fine += $fine_interval * $grace;
370                         }
371         
372                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
373                         unless($pending_fine_count) {
374                                 $client->respond( "\tNo fines to create.  " );
375                                 if ($grace && $now < $due + $fine_interval * $grace) {
376                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
377                                 } else {
378                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
379                                 }
380                                 next;
381                         }
382         
383                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
384         
385                         for my $bill (1 .. $pending_fine_count) {
386         
387                                 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
388         
389                                 if ($total && $total->balance_owed > $c->max_fine) {
390                                         $c->update({stop_fines => 'MAXFINES'});
391                                         $client->respond(
392                                                 "\tMaximum fine level of ".$c->max_fine.
393                                                 " reached for this circulation.\n".
394                                                 "\tNo more fines will be generated.\n" );
395                                         last;
396                                 }
397         
398                                 my $billing = money::billing->create(
399                                         { xact          => ''.$c->id,
400                                           note          => "Overdue Fine",
401                                           billing_type  => "Overdue materials",
402                                           amount        => ''.$c->recuring_fine,
403                                           billing_ts    => DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
404                                         }
405                                 );
406         
407                                 $client->respond(
408                                         "\t\tCreating fine of ".$billing->amount." for period starting ".
409                                         localtime(
410                                                 $parser->parse_datetime(
411                                                         clense_ISO8601( $billing->billing_ts )
412                                                 )->epoch
413                                         )."\n" );
414                         }
415                 } catch Error with {
416                         my $e = shift;
417                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
418                 };
419         }
420 }
421 __PACKAGE__->register_method(
422         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
423         api_level       => 1,
424         stream          => 1,
425         method          => 'generate_fines',
426 );
427
428
429
430 sub new_hold_copy_targeter {
431         my $self = shift;
432         my $client = shift;
433         my $check_expire = shift;
434         my $one_hold = shift;
435
436         my $time = time;
437         $check_expire ||= '12h';
438         $check_expire = interval_to_seconds( $check_expire );
439
440         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
441         $year += 1900;
442         $mon += 1;
443         my $expire_threshold = sprintf(
444                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
445                 $year, $mon, $mday, $hour, $min, $sec
446         );
447
448
449         my $holds;
450
451         try {
452                 if ($one_hold) {
453                         $holds = [ action::hold_request->search(id => $one_hold) ];
454                 } else {
455                         $holds = [ action::hold_request->search_where(
456                                                         { capture_time => undef,
457                                                           fulfillment_time => undef,
458                                                           prev_check_time => { '<=' => $expire_threshold },
459                                                         },
460                                                         { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
461                         push @$holds, action::hold_request->search(
462                                                         capture_time => undef,
463                                                         fulfillment_time => undef,
464                                                         prev_check_time => undef,
465                                                         { order_by => 'selection_depth DESC, request_time' } );
466                 }
467         } catch Error with {
468                 my $e = shift;
469                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
470         };
471
472         my @successes;
473         for my $hold (@$holds) {
474                 try {
475                         #action::hold_request->db_Main->begin_work;
476                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
477                                 $log->debug("Cleaning up after previous transaction\n");
478                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
479                         }
480                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
481                         $log->info("Processing hold ".$hold->id."...\n");
482
483                         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
484         
485                         my $all_copies = [];
486
487                         # find all the potential copies
488                         if ($hold->hold_type eq 'M') {
489                                 for my $r ( map
490                                                 {$_->record}
491                                                 metabib::record_descriptor
492                                                         ->search(
493                                                                 record => [ map { $_->id } metabib::metarecord
494                                                                                         ->retrieve($hold->target)
495                                                                                         ->source_records ],
496                                                                 item_type => [split '', $hold->holdable_formats]
497                                                         )
498                                 ) {
499                                         my ($rtree) = $self
500                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
501                                                 ->run( $r->id, $hold->usr->home_ou->id, $hold->selection_depth );
502
503                                         for my $cn ( @{ $rtree->call_numbers } ) {
504                                                 push @$all_copies,
505                                                         asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
506                                         }
507                                 }
508                         } elsif ($hold->hold_type eq 'T') {
509                                 my ($rtree) = $self
510                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
511                                         ->run( $hold->target, $hold->usr->home_ou->id, $hold->selection_depth );
512
513                                 unless ($rtree) {
514                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
515                                         die 'OK';
516                                 }
517
518                                 for my $cn ( @{ $rtree->call_numbers } ) {
519                                         push @$all_copies,
520                                                 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
521                                 }
522                         } elsif ($hold->hold_type eq 'V') {
523                                 my ($vtree) = $self
524                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
525                                         ->run( $hold->target, $hold->usr->home_ou->id, $hold->selection_depth );
526
527                                 push @$all_copies,
528                                         asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
529                                         
530                         } elsif  ($hold->hold_type eq 'C') {
531
532                                 $all_copies = [asset::copy->retrieve($hold->target)];
533                         }
534
535                         # let 'em know we're still working
536                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
537                         
538                         if (!ref $all_copies || !@$all_copies) {
539                                 $log->info("\tNo copies available for targeting at all!\n");
540                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
541                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
542                                 die 'OK';
543                         }
544
545                         my $copies = [];
546                         for my $c ( @$all_copies ) {
547                                 push @$copies, $c
548                                         if ( OpenILS::Utils::PermitHold::permit_copy_hold(
549                                                 { title => $c->call_number->record->to_fieldmapper,
550                                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
551                                                   patron => $hold->usr->to_fieldmapper,
552                                                   copy => $c->to_fieldmapper,
553                                                   requestor => $hold->requestor->to_fieldmapper,
554                                                   request_lib => $hold->request_lib->to_fieldmapper,
555                                                 } ));
556                         }
557                         my $copy_count = @$copies;
558                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
559
560                         # map the potentials, so that we can pick up checkins
561                         $log->debug( "\tMapping ".scalar(@copies)." potential copies for hold ".$hold->id);
562                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@copies);
563
564                         my @good_copies;
565                         for my $c (@$copies) {
566                                 next if ($c->id == $hold->current_copy);
567                                 push @good_copies, $c if ($c);
568                         }
569
570                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
571
572                         my $old_best = $hold->current_copy;
573                         $hold->update({ current_copy => undef });
574         
575                         if (!scalar(@good_copies)) {
576                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
577                                 if ( $old_best && grep { $old_best == $_ } @$copies ) {
578                                         $log->debug("\tPushing current_copy back onto the targeting list");
579                                         push @good_copies, $old_best;
580                                 } else {
581                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
582                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
583                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
584                                         die 'OK';
585                                 }
586                         }
587
588                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
589                         my $prox_list = [];
590                         $$prox_list[0] =
591                         [
592                                 grep {
593                                         $_->circ_lib == $hold->pickup_lib && 
594                                         ( $_->status == 0 || $_->status == 7 )
595                                 } @good_copies
596                         ];
597
598                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
599
600                         my $best = $self->choose_nearest_copy($hold, $prox_list);
601
602                         if (!$best) {
603                                 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
604                                 $best = $self->choose_nearest_copy($hold, $prox_list);
605                         }
606
607                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
608                         if ($old_best) {
609                                 # hold wasn't fulfilled, record the fact
610                         
611                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
612                                 action::unfulfilled_hold_list->create(
613                                                 { hold => ''.$hold->id,
614                                                   current_copy => ''.$old_best->id,
615                                                   circ_lib => ''.$old_best->circ_lib,
616                                                 });
617                         }
618
619                         if ($best) {
620                                 $hold->update( { current_copy => ''.$best->id } );
621                                 $log->debug("\tTargeting copy ".$best->id." for hold fulfillment.");
622                         } else {
623                                 $log->debug( "\tThere were no targetable copies for the hold" );
624                         }
625
626                         $hold->update( { prev_check_time => 'now' } );
627                         $log->info("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
628
629                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
630                         $log->info("\tProcessing of hold ".$hold->id." complete.");
631
632                         push @successes,
633                                 { hold => $hold->id,
634                                   old_target => ($old_best ? $old_best->id : undef),
635                                   eligible_copies => $copy_count,
636                                   target => ($best ? $best->id : undef) };
637
638                 } otherwise {
639                         my $e = shift;
640                         if ($e !~ /^OK/o) {
641                                 $log->error("Processing of hold failed:  $e");
642                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
643                         }
644                 };
645         }
646
647         return \@successes;
648 }
649 __PACKAGE__->register_method(
650         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
651         api_level       => 1,
652         method          => 'new_hold_copy_targeter',
653 );
654
655 my $locations;
656 my $statuses;
657 my %cache = (titles => {}, cns => {});
658 sub hold_copy_targeter {
659         my $self = shift;
660         my $client = shift;
661         my $check_expire = shift;
662         my $one_hold = shift;
663
664         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
665         $self->{user_filter}->connect;
666         $self->{client} = $client;
667
668         my $time = time;
669         $check_expire ||= '12h';
670         $check_expire = interval_to_seconds( $check_expire );
671
672         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
673         $year += 1900;
674         $mon += 1;
675         my $expire_threshold = sprintf(
676                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
677                 $year, $mon, $mday, $hour, $min, $sec
678         );
679
680
681         $statuses ||= [ config::copy_status->search(holdable => 't') ];
682
683         $locations ||= [ asset::copy_location->search(holdable => 't') ];
684
685         my $holds;
686
687         %cache = (titles => {}, cns => {});
688
689         try {
690                 if ($one_hold) {
691                         $holds = [ action::hold_request->search(id => $one_hold) ];
692                 } else {
693                         $holds = [ action::hold_request->search_where(
694                                                         { capture_time => undef,
695                                                           prev_check_time => { '<=' => $expire_threshold },
696                                                         },
697                                                         { order_by => 'request_time,prev_check_time' } ) ];
698                         push @$holds, action::hold_request->search(
699                                                         capture_time => undef,
700                                                         prev_check_time => undef,
701                                                         { order_by => 'request_time' } );
702                 }
703         } catch Error with {
704                 my $e = shift;
705                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
706         };
707
708         for my $hold (@$holds) {
709                 try {
710                         #action::hold_request->db_Main->begin_work;
711                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
712                                 $client->respond("Cleaning up after previous transaction\n");
713                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
714                         }
715                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
716                         $client->respond("Processing hold ".$hold->id."...\n");
717
718                         my $copies;
719
720                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
721                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
722
723                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
724                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
725                         
726                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
727                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
728                         
729                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
730
731                         unless (ref $copies || !@$copies) {
732                                 $client->respond("\tNo copies available for targeting at all!\n");
733                         }
734
735                         my @good_copies;
736                         for my $c (@$copies) {
737                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
738                                 push @good_copies, $c if ($c);
739                         }
740
741                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
742
743                         my $old_best = $hold->current_copy;
744                         $hold->update({ current_copy => undef });
745         
746                         if (!scalar(@good_copies)) {
747                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
748                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
749                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
750                                         push @good_copies, asset::copy->retrieve( $old_best );
751                                 } else {
752                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
753                                         next;
754                                 }
755                         }
756
757                         my $prox_list;
758                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
759                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
760
761                         my $best = $self->choose_nearest_copy($hold, $prox_list);
762
763                         if (!$best) {
764                                 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
765                                 $best = $self->choose_nearest_copy($hold, $prox_list);
766                         }
767
768                         if ($old_best) {
769                                 # hold wasn't fulfilled, record the fact
770                         
771                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
772                                 action::unfulfilled_hold_list->create(
773                                                 { hold => ''.$hold->id,
774                                                   current_copy => ''.$old_best->id,
775                                                   circ_lib => ''.$old_best->circ_lib,
776                                                 });
777                         }
778
779                         if ($best) {
780                                 $hold->update( { current_copy => ''.$best->id } );
781                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
782                         }
783
784                         $hold->update( { prev_check_time => 'now' } );
785                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
786
787                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
788                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
789
790                         #action::hold_request->dbi_commit;
791
792                 } otherwise {
793                         my $e = shift;
794                         $log->error("Processing of hold failed:  $e");
795                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
796                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
797                         #action::hold_request->dbi_rollback;
798                 };
799         }
800
801         $self->{user_filter}->disconnect;
802         $self->{user_filter}->finish;
803         delete $$self{user_filter};
804         return undef;
805 }
806 __PACKAGE__->register_method(
807         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
808         api_level       => 0,
809         stream          => 1,
810         method          => 'hold_copy_targeter',
811 );
812
813
814 sub copy_hold_capture {
815         my $self = shift;
816         my $hold = shift;
817         my $cps = shift;
818
819         if (!defined($cps)) {
820                 try {
821                         $cps = [ asset::copy->search( id => $hold->target ) ];
822                 } catch Error with {
823                         my $e = shift;
824                         die "Could not retrieve initial volume list:\n\n$e\n";
825                 };
826         }
827
828         my @copies = grep { $_->holdable } @$cps;
829
830         for (my $i = 0; $i < @$cps; $i++) {
831                 next unless $$cps[$i];
832                 
833                 my $cn = $cache{cns}{$copies[$i]->call_number};
834                 my $rec = $cache{titles}{$cn->record};
835                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
836                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
837                 $copies[$i] = undef if (
838                         !$copies[$i] ||
839                         !$self->{user_filter}->request(
840                                 'open-ils.circ.permit_hold',
841                                 $hold->to_fieldmapper, do {
842                                         my $cp_fm = $copies[$i]->to_fieldmapper;
843                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
844                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
845                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
846                                         $cp_fm;
847                                 },
848                                 { title => $rec->to_fieldmapper,
849                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
850                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
851                                 })->gather(1)
852                 );
853                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
854         }
855
856         @copies = grep { $_ } @copies;
857
858         my $count = @copies;
859
860         return unless ($count);
861         
862         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
863         
864         my @maps;
865         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
866         for my $c (@copies) {
867                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
868         }
869         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
870
871         return \@copies;
872 }
873
874
875 sub choose_nearest_copy {
876         my $self = shift;
877         my $hold = shift;
878         my $prox_list = shift;
879
880         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
881                 next unless (ref $$prox_list[$p]);
882                 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
883                 next unless (@capturable);
884                 return $capturable[rand(scalar(@capturable))];
885         }
886 }
887
888 sub create_prox_list {
889         my $self = shift;
890         my $lib = shift;
891         my $copies = shift;
892
893         my @prox_list;
894         for my $cp (@$copies) {
895                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
896                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
897                 push @{$prox_list[$prox]}, $cp;
898         }
899         return \@prox_list;
900 }
901
902 sub volume_hold_capture {
903         my $self = shift;
904         my $hold = shift;
905         my $vols = shift;
906
907         if (!defined($vols)) {
908                 try {
909                         $vols = [ asset::call_number->search( id => $hold->target ) ];
910                         $cache{cns}{$_->id} = $_ for (@$vols);
911                 } catch Error with {
912                         my $e = shift;
913                         die "Could not retrieve initial volume list:\n\n$e\n";
914                 };
915         }
916
917         my @v_ids = map { $_->id } @$vols;
918
919         my $cp_list;
920         try {
921                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
922         
923         } catch Error with {
924                 my $e = shift;
925                 warn "Could not retrieve copy list:\n\n$e\n";
926         };
927
928         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
929 }
930
931 sub title_hold_capture {
932         my $self = shift;
933         my $hold = shift;
934         my $titles = shift;
935
936         if (!defined($titles)) {
937                 try {
938                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
939                         $cache{titles}{$_->id} = $_ for (@$titles);
940                 } catch Error with {
941                         my $e = shift;
942                         die "Could not retrieve initial title list:\n\n$e\n";
943                 };
944         }
945
946         my @t_ids = map { $_->id } @$titles;
947         my $cn_list;
948         try {
949                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
950         
951         } catch Error with {
952                 my $e = shift;
953                 warn "Could not retrieve volume list:\n\n$e\n";
954         };
955
956         $cache{cns}{$_->id} = $_ for (@$cn_list);
957
958         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
959 }
960
961 sub metarecord_hold_capture {
962         my $self = shift;
963         my $hold = shift;
964
965         my $titles;
966         try {
967                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
968         
969         } catch Error with {
970                 my $e = shift;
971                 die "Could not retrieve initial title list:\n\n$e\n";
972         };
973
974         try {
975                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
976
977                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
978         
979         } catch Error with {
980                 my $e = shift;
981                 die "Could not retrieve format-pruned title list:\n\n$e\n";
982         };
983
984
985         $cache{titles}{$_->id} = $_ for (@$titles);
986         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
987 }
988
989 1;