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