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