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