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