]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
added a "only target new holds" mode to the copy targeter
[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 $holds;
437
438         try {
439                 if ($one_hold) {
440                         $holds = [ action::hold_request->search(id => $one_hold) ];
441                 } elsif ( $check_expire ) {
442
443                         my $time = time;
444                         $check_expire ||= '12h';
445                         $check_expire = interval_to_seconds( $check_expire );
446
447                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
448                         $year += 1900;
449                         $mon += 1;
450                         my $expire_threshold = sprintf(
451                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
452                                 $year, $mon, $mday, $hour, $min, $sec
453                         );
454
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                 } else {
467                         $holds [ action::hold_request->search(
468                                                         capture_time => undef,
469                                                         fulfillment_time => undef,
470                                                         prev_check_time => undef,
471                                                         { order_by => 'selection_depth DESC, request_time' } ) ];
472                 }
473         } catch Error with {
474                 my $e = shift;
475                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
476         };
477
478         my @successes;
479         for my $hold (@$holds) {
480                 try {
481                         #action::hold_request->db_Main->begin_work;
482                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
483                                 $log->debug("Cleaning up after previous transaction\n");
484                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
485                         }
486                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
487                         $log->info("Processing hold ".$hold->id."...\n");
488
489                         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
490         
491                         my $all_copies = [];
492
493                         # find all the potential copies
494                         if ($hold->hold_type eq 'M') {
495                                 for my $r ( map
496                                                 {$_->record}
497                                                 metabib::record_descriptor
498                                                         ->search(
499                                                                 record => [ map { $_->id } metabib::metarecord
500                                                                                         ->retrieve($hold->target)
501                                                                                         ->source_records ],
502                                                                 item_type => [split '', $hold->holdable_formats]
503                                                         )
504                                 ) {
505                                         my ($rtree) = $self
506                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
507                                                 ->run( $r->id, $hold->usr->home_ou->id, $hold->selection_depth );
508
509                                         for my $cn ( @{ $rtree->call_numbers } ) {
510                                                 push @$all_copies,
511                                                         asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
512                                         }
513                                 }
514                         } elsif ($hold->hold_type eq 'T') {
515                                 my ($rtree) = $self
516                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
517                                         ->run( $hold->target, $hold->usr->home_ou->id, $hold->selection_depth );
518
519                                 unless ($rtree) {
520                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
521                                         die 'OK';
522                                 }
523
524                                 for my $cn ( @{ $rtree->call_numbers } ) {
525                                         push @$all_copies,
526                                                 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
527                                 }
528                         } elsif ($hold->hold_type eq 'V') {
529                                 my ($vtree) = $self
530                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
531                                         ->run( $hold->target, $hold->usr->home_ou->id, $hold->selection_depth );
532
533                                 push @$all_copies,
534                                         asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
535                                         
536                         } elsif  ($hold->hold_type eq 'C') {
537
538                                 $all_copies = [asset::copy->retrieve($hold->target)];
539                         }
540
541                         # let 'em know we're still working
542                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
543                         
544                         if (!ref $all_copies || !@$all_copies) {
545                                 $log->info("\tNo copies available for targeting at all!\n");
546                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
547                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
548                                 die 'OK';
549                         }
550
551                         my $copies = [];
552                         for my $c ( @$all_copies ) {
553                                 push @$copies, $c
554                                         if ( OpenILS::Utils::PermitHold::permit_copy_hold(
555                                                 { title => $c->call_number->record->to_fieldmapper,
556                                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
557                                                   patron => $hold->usr->to_fieldmapper,
558                                                   copy => $c->to_fieldmapper,
559                                                   requestor => $hold->requestor->to_fieldmapper,
560                                                   request_lib => $hold->request_lib->to_fieldmapper,
561                                                 } ));
562                         }
563                         my $copy_count = @$copies;
564                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
565
566                         # map the potentials, so that we can pick up checkins
567                         $log->debug( "\tMapping ".scalar(@copies)." potential copies for hold ".$hold->id);
568                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@copies);
569
570                         my @good_copies;
571                         for my $c (@$copies) {
572                                 next if ($c->id == $hold->current_copy);
573                                 push @good_copies, $c if ($c);
574                         }
575
576                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
577
578                         my $old_best = $hold->current_copy;
579                         $hold->update({ current_copy => undef });
580         
581                         if (!scalar(@good_copies)) {
582                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
583                                 if ( $old_best && grep { $old_best == $_ } @$copies ) {
584                                         $log->debug("\tPushing current_copy back onto the targeting list");
585                                         push @good_copies, $old_best;
586                                 } else {
587                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
588                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
589                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
590                                         die 'OK';
591                                 }
592                         }
593
594                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
595                         my $prox_list = [];
596                         $$prox_list[0] =
597                         [
598                                 grep {
599                                         $_->circ_lib == $hold->pickup_lib && 
600                                         ( $_->status == 0 || $_->status == 7 )
601                                 } @good_copies
602                         ];
603
604                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
605
606                         my $best = $self->choose_nearest_copy($hold, $prox_list);
607
608                         if (!$best) {
609                                 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
610                                 $best = $self->choose_nearest_copy($hold, $prox_list);
611                         }
612
613                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
614                         if ($old_best) {
615                                 # hold wasn't fulfilled, record the fact
616                         
617                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
618                                 action::unfulfilled_hold_list->create(
619                                                 { hold => ''.$hold->id,
620                                                   current_copy => ''.$old_best->id,
621                                                   circ_lib => ''.$old_best->circ_lib,
622                                                 });
623                         }
624
625                         if ($best) {
626                                 $hold->update( { current_copy => ''.$best->id } );
627                                 $log->debug("\tTargeting copy ".$best->id." for hold fulfillment.");
628                         } else {
629                                 $log->debug( "\tThere were no targetable copies for the hold" );
630                         }
631
632                         $hold->update( { prev_check_time => 'now' } );
633                         $log->info("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
634
635                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
636                         $log->info("\tProcessing of hold ".$hold->id." complete.");
637
638                         push @successes,
639                                 { hold => $hold->id,
640                                   old_target => ($old_best ? $old_best->id : undef),
641                                   eligible_copies => $copy_count,
642                                   target => ($best ? $best->id : undef) };
643
644                 } otherwise {
645                         my $e = shift;
646                         if ($e !~ /^OK/o) {
647                                 $log->error("Processing of hold failed:  $e");
648                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
649                         }
650                 };
651         }
652
653         return \@successes;
654 }
655 __PACKAGE__->register_method(
656         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
657         api_level       => 1,
658         method          => 'new_hold_copy_targeter',
659 );
660
661 my $locations;
662 my $statuses;
663 my %cache = (titles => {}, cns => {});
664 sub hold_copy_targeter {
665         my $self = shift;
666         my $client = shift;
667         my $check_expire = shift;
668         my $one_hold = shift;
669
670         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
671         $self->{user_filter}->connect;
672         $self->{client} = $client;
673
674         my $time = time;
675         $check_expire ||= '12h';
676         $check_expire = interval_to_seconds( $check_expire );
677
678         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
679         $year += 1900;
680         $mon += 1;
681         my $expire_threshold = sprintf(
682                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
683                 $year, $mon, $mday, $hour, $min, $sec
684         );
685
686
687         $statuses ||= [ config::copy_status->search(holdable => 't') ];
688
689         $locations ||= [ asset::copy_location->search(holdable => 't') ];
690
691         my $holds;
692
693         %cache = (titles => {}, cns => {});
694
695         try {
696                 if ($one_hold) {
697                         $holds = [ action::hold_request->search(id => $one_hold) ];
698                 } else {
699                         $holds = [ action::hold_request->search_where(
700                                                         { capture_time => undef,
701                                                           prev_check_time => { '<=' => $expire_threshold },
702                                                         },
703                                                         { order_by => 'request_time,prev_check_time' } ) ];
704                         push @$holds, action::hold_request->search(
705                                                         capture_time => undef,
706                                                         prev_check_time => undef,
707                                                         { order_by => 'request_time' } );
708                 }
709         } catch Error with {
710                 my $e = shift;
711                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
712         };
713
714         for my $hold (@$holds) {
715                 try {
716                         #action::hold_request->db_Main->begin_work;
717                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
718                                 $client->respond("Cleaning up after previous transaction\n");
719                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
720                         }
721                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
722                         $client->respond("Processing hold ".$hold->id."...\n");
723
724                         my $copies;
725
726                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
727                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
728
729                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
730                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
731                         
732                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
733                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
734                         
735                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
736
737                         unless (ref $copies || !@$copies) {
738                                 $client->respond("\tNo copies available for targeting at all!\n");
739                         }
740
741                         my @good_copies;
742                         for my $c (@$copies) {
743                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
744                                 push @good_copies, $c if ($c);
745                         }
746
747                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
748
749                         my $old_best = $hold->current_copy;
750                         $hold->update({ current_copy => undef });
751         
752                         if (!scalar(@good_copies)) {
753                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
754                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
755                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
756                                         push @good_copies, asset::copy->retrieve( $old_best );
757                                 } else {
758                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
759                                         next;
760                                 }
761                         }
762
763                         my $prox_list;
764                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
765                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
766
767                         my $best = $self->choose_nearest_copy($hold, $prox_list);
768
769                         if (!$best) {
770                                 $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
771                                 $best = $self->choose_nearest_copy($hold, $prox_list);
772                         }
773
774                         if ($old_best) {
775                                 # hold wasn't fulfilled, record the fact
776                         
777                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
778                                 action::unfulfilled_hold_list->create(
779                                                 { hold => ''.$hold->id,
780                                                   current_copy => ''.$old_best->id,
781                                                   circ_lib => ''.$old_best->circ_lib,
782                                                 });
783                         }
784
785                         if ($best) {
786                                 $hold->update( { current_copy => ''.$best->id } );
787                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
788                         }
789
790                         $hold->update( { prev_check_time => 'now' } );
791                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
792
793                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
794                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
795
796                         #action::hold_request->dbi_commit;
797
798                 } otherwise {
799                         my $e = shift;
800                         $log->error("Processing of hold failed:  $e");
801                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
802                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
803                         #action::hold_request->dbi_rollback;
804                 };
805         }
806
807         $self->{user_filter}->disconnect;
808         $self->{user_filter}->finish;
809         delete $$self{user_filter};
810         return undef;
811 }
812 __PACKAGE__->register_method(
813         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
814         api_level       => 0,
815         stream          => 1,
816         method          => 'hold_copy_targeter',
817 );
818
819
820 sub copy_hold_capture {
821         my $self = shift;
822         my $hold = shift;
823         my $cps = shift;
824
825         if (!defined($cps)) {
826                 try {
827                         $cps = [ asset::copy->search( id => $hold->target ) ];
828                 } catch Error with {
829                         my $e = shift;
830                         die "Could not retrieve initial volume list:\n\n$e\n";
831                 };
832         }
833
834         my @copies = grep { $_->holdable } @$cps;
835
836         for (my $i = 0; $i < @$cps; $i++) {
837                 next unless $$cps[$i];
838                 
839                 my $cn = $cache{cns}{$copies[$i]->call_number};
840                 my $rec = $cache{titles}{$cn->record};
841                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
842                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
843                 $copies[$i] = undef if (
844                         !$copies[$i] ||
845                         !$self->{user_filter}->request(
846                                 'open-ils.circ.permit_hold',
847                                 $hold->to_fieldmapper, do {
848                                         my $cp_fm = $copies[$i]->to_fieldmapper;
849                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
850                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
851                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
852                                         $cp_fm;
853                                 },
854                                 { title => $rec->to_fieldmapper,
855                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
856                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
857                                 })->gather(1)
858                 );
859                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
860         }
861
862         @copies = grep { $_ } @copies;
863
864         my $count = @copies;
865
866         return unless ($count);
867         
868         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
869         
870         my @maps;
871         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
872         for my $c (@copies) {
873                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
874         }
875         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
876
877         return \@copies;
878 }
879
880
881 sub choose_nearest_copy {
882         my $self = shift;
883         my $hold = shift;
884         my $prox_list = shift;
885
886         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
887                 next unless (ref $$prox_list[$p]);
888                 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
889                 next unless (@capturable);
890                 return $capturable[rand(scalar(@capturable))];
891         }
892 }
893
894 sub create_prox_list {
895         my $self = shift;
896         my $lib = shift;
897         my $copies = shift;
898
899         my @prox_list;
900         for my $cp (@$copies) {
901                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
902                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
903                 push @{$prox_list[$prox]}, $cp;
904         }
905         return \@prox_list;
906 }
907
908 sub volume_hold_capture {
909         my $self = shift;
910         my $hold = shift;
911         my $vols = shift;
912
913         if (!defined($vols)) {
914                 try {
915                         $vols = [ asset::call_number->search( id => $hold->target ) ];
916                         $cache{cns}{$_->id} = $_ for (@$vols);
917                 } catch Error with {
918                         my $e = shift;
919                         die "Could not retrieve initial volume list:\n\n$e\n";
920                 };
921         }
922
923         my @v_ids = map { $_->id } @$vols;
924
925         my $cp_list;
926         try {
927                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
928         
929         } catch Error with {
930                 my $e = shift;
931                 warn "Could not retrieve copy list:\n\n$e\n";
932         };
933
934         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
935 }
936
937 sub title_hold_capture {
938         my $self = shift;
939         my $hold = shift;
940         my $titles = shift;
941
942         if (!defined($titles)) {
943                 try {
944                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
945                         $cache{titles}{$_->id} = $_ for (@$titles);
946                 } catch Error with {
947                         my $e = shift;
948                         die "Could not retrieve initial title list:\n\n$e\n";
949                 };
950         }
951
952         my @t_ids = map { $_->id } @$titles;
953         my $cn_list;
954         try {
955                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
956         
957         } catch Error with {
958                 my $e = shift;
959                 warn "Could not retrieve volume list:\n\n$e\n";
960         };
961
962         $cache{cns}{$_->id} = $_ for (@$cn_list);
963
964         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
965 }
966
967 sub metarecord_hold_capture {
968         my $self = shift;
969         my $hold = shift;
970
971         my $titles;
972         try {
973                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
974         
975         } catch Error with {
976                 my $e = shift;
977                 die "Could not retrieve initial title list:\n\n$e\n";
978         };
979
980         try {
981                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
982
983                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
984         
985         } catch Error with {
986                 my $e = shift;
987                 die "Could not retrieve format-pruned title list:\n\n$e\n";
988         };
989
990
991         $cache{titles}{$_->id} = $_ for (@$titles);
992         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
993 }
994
995 1;