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