]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
fixing weird edge case of pushing out the due date after fines start to acrue
[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,
532                                   billing_type => 'Overdue materials',
533                                   billing_ts => { '>' => $c->due_date } },
534                                 { order_by => 'billing_ts DESC'}
535                         );
536
537                         my $f_idx = 0;
538                         my $fine = $fines[$f_idx] if (@fines);
539                         if ($overbill) {
540                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
541                         }
542
543                         my $current_fine_total = 0;
544                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
545         
546                         my $last_fine;
547                         if ($fine) {
548                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
549                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
550                         } else {
551                                 $log->info( "Potential first billing for circ ".$c->id );
552                                 $last_fine = $due;
553
554                                 if (0) {
555                                         if (my $h = $hoo{$c->circ_lib}) { 
556
557                                                 $log->info( "Circ lib has an hours-of-operation entry" );
558                                                 # find the day after the due date...
559                                                 $due_dt = $due_dt->add( days => 1 );
560
561                                                 # get the day of the week for that day...
562                                                 my $dow = $due_dt->day_of_week_0;
563                                                 my $dow_open = "dow_${dow}_open";
564                                                 my $dow_close = "dow_${dow}_close";
565
566                                                 my $count = 0;
567                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
568                                                         # if the circ lib is closed, add a day to the grace period...
569
570                                                         $grace++;
571                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
572                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
573
574                                                         $due_dt = $due_dt->add( days => 1 );
575                                                         $dow = $due_dt->day_of_week_0;
576                                                         $dow_open = "dow_${dow}_open";
577                                                         $dow_close = "dow_${dow}_close";
578
579                                                         $count++;
580
581                                                         # and check for up to a week
582                                                         last if ($count > 6);
583                                                 }
584                                         }
585                                 }
586                         }
587
588
589                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
590                         if ($pending_fine_count < 1 + $grace) {
591                                 $client->respond( "\tNo fines to create.  " );
592                                 if ($grace && $now < $due + $fine_interval * $grace) {
593                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
594                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
595                                 } else {
596                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
597                                 }
598                                 next;
599                         }
600         
601                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
602
603                         my $recuring_fine = int($c->recuring_fine * 100);
604                         my $max_fine = int($c->max_fine * 100);
605
606                         my ($latest_billing_ts, $latest_amount) = ('',0);
607                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
608         
609                                 if ($current_fine_total >= $max_fine) {
610                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
611                                         $client->respond(
612                                                 "\tMaximum fine level of ".$c->max_fine.
613                                                 " reached for this circulation.\n".
614                                                 "\tNo more fines will be generated.\n" );
615                                         last;
616                                 }
617                                 
618                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
619
620                                 my $dow = $billing_ts->day_of_week_0();
621                                 my $dow_open = "dow_${dow}_open";
622                                 my $dow_close = "dow_${dow}_close";
623
624                                 if (my $h = $hoo{$c->circ_lib}) {
625                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
626                                 }
627
628                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
629                                 my @cl = actor::org_unit::closed_date->search_where(
630                                                 { close_start   => { '<=' => $timestamptz },
631                                                   close_end     => { '>=' => $timestamptz },
632                                                   org_unit      => $c->circ_lib }
633                                 );
634                                 next if (@cl);
635         
636                                 $current_fine_total += $recuring_fine;
637                                 $latest_amount += $recuring_fine;
638                                 $latest_billing_ts = $timestamptz;
639
640                                 money::billing->create(
641                                         { xact          => ''.$c->id,
642                                           note          => "System Generated Overdue Fine",
643                                           billing_type  => "Overdue materials",
644                                           amount        => sprintf('%0.2f', $recuring_fine/100),
645                                           billing_ts    => $timestamptz,
646                                         }
647                                 );
648
649                         }
650
651                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
652                                 if ($latest_billing_ts and $latest_amount);
653
654                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
655
656                         $penalty->request(
657                                 'open-ils.penalty.patron_penalty.calculate',
658                                 { patron        => $c->usr->to_fieldmapper,
659                                   update        => 1,
660                                   background    => 1,
661                                 }
662                         )->gather(1);
663
664                 } catch Error with {
665                         my $e = shift;
666                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
667                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
668                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
669                         throw $e ifif ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
670                 };
671         }
672 }
673 __PACKAGE__->register_method(
674         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
675         api_level       => 1,
676         stream          => 1,
677         method          => 'generate_fines',
678 );
679
680
681
682 sub new_hold_copy_targeter {
683         my $self = shift;
684         my $client = shift;
685         my $check_expire = shift;
686         my $one_hold = shift;
687
688         local $OpenILS::Application::Storage::WRITE = 1;
689
690         my $holds;
691
692         try {
693                 if ($one_hold) {
694                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
695                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
696                 } elsif ( $check_expire ) {
697
698                         # what's the retarget time threashold?
699                         my $time = time;
700                         $check_expire ||= '12h';
701                         $check_expire = interval_to_seconds( $check_expire );
702
703                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
704                         $year += 1900;
705                         $mon += 1;
706                         my $expire_threshold = sprintf(
707                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
708                                 $year, $mon, $mday, $hour, $min, $sec
709                         );
710
711                         # find all the holds holds needing retargeting
712                         $holds = [ action::hold_request->search_where(
713                                                         { capture_time => undef,
714                                                           fulfillment_time => undef,
715                                                           cancel_time => undef,
716                                                           frozen => 'f',
717                                                           prev_check_time => { '<=' => $expire_threshold },
718                                                         },
719                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
720
721                         # find all the holds holds needing first time targeting
722                         push @$holds, action::hold_request->search(
723                                                         capture_time => undef,
724                                                         fulfillment_time => undef,
725                                                         prev_check_time => undef,
726                                                         frozen => 'f',
727                                                         cancel_time => undef,
728                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
729                 } else {
730
731                         # find all the holds holds needing first time targeting ONLY
732                         $holds = [ action::hold_request->search(
733                                                         capture_time => undef,
734                                                         fulfillment_time => undef,
735                                                         prev_check_time => undef,
736                                                         cancel_time => undef,
737                                                         frozen => 'f',
738                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
739                 }
740         } catch Error with {
741                 my $e = shift;
742                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
743         };
744
745         my @closed = actor::org_unit::closed_date->search_where(
746                 { close_start => { '<=', 'now' },
747                   close_end => { '>=', 'now' } }
748         );
749
750
751         my @successes;
752
753         for my $hold (@$holds) {
754                 try {
755                         #start a transaction if needed
756                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
757                                 $log->debug("Cleaning up after previous transaction\n");
758                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
759                         }
760                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
761                         $log->info("Processing hold ".$hold->id."...\n");
762
763                         #first, re-fetch the hold, to make sure it's not captured already
764                         $hold = action::hold_request->retrieve( $hold->id );
765                         die "OK\n" if (!$hold or $hold->capture_time);
766
767                         # remove old auto-targeting maps
768                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
769                         $_->delete for (@oldmaps);
770
771         
772                         my $all_copies = [];
773
774                         # find filters for MR holds
775                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
776
777                         # find all the potential copies
778                         if ($hold->hold_type eq 'M') {
779                                 for my $r ( map
780                                                 {$_->record}
781                                                 metabib::record_descriptor
782                                                         ->search(
783                                                                 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
784                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
785                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
786                                                                 ( $lang    ? (item_lang => $lang)                : () ),
787                                                         )
788                                 ) {
789                                         my ($rtree) = $self
790                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
791                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
792
793                                         for my $cn ( @{ $rtree->call_numbers } ) {
794                                                 push @$all_copies,
795                                                         asset::copy->search_where(
796                                                                 { id => [map {$_->id} @{ $cn->copies }],
797                                                                   deleted => 'f' }
798                                                         ) if ($cn && @{ $cn->copies });
799                                         }
800                                 }
801                         } elsif ($hold->hold_type eq 'T') {
802                                 my ($rtree) = $self
803                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
804                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
805
806                                 unless ($rtree) {
807                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
808                                         die "OK\n";
809                                 }
810
811                                 for my $cn ( @{ $rtree->call_numbers } ) {
812                                         push @$all_copies,
813                                                 asset::copy->search_where(
814                                                         { id => [map {$_->id} @{ $cn->copies }],
815                                                           deleted => 'f' }
816                                                 ) if ($cn && @{ $cn->copies });
817                                 }
818                         } elsif ($hold->hold_type eq 'V') {
819                                 my ($vtree) = $self
820                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
821                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
822
823                                 push @$all_copies,
824                                         asset::copy->search_where(
825                                                 { id => [map {$_->id} @{ $vtree->copies }],
826                                                   deleted => 'f' }
827                                         ) if ($vtree && @{ $vtree->copies });
828                                         
829                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
830                                 my $_cp = asset::copy->retrieve($hold->target);
831                                 push @$all_copies, $_cp if $_cp;
832                         }
833
834                         # trim unholdables
835                         @$all_copies = grep {   isTrue($_->status->holdable) && 
836                                                 isTrue($_->location->holdable) && 
837                                                 isTrue($_->holdable) &&
838                                                 !isTrue($_->deleted)
839                                         } @$all_copies;
840
841                         # let 'em know we're still working
842                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
843                         
844                         # if we have no copies ...
845                         if (!ref $all_copies || !@$all_copies) {
846                                 $log->info("\tNo copies available for targeting at all!\n");
847                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
848
849                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
850                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
851                                 die "OK\n";
852                         }
853
854                         my $copy_count = @$all_copies;
855
856                         # map the potentials, so that we can pick up checkins
857                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
858                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
859
860                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
861
862                         my @good_copies;
863                         for my $c (@$all_copies) {
864                                 # current target
865                                 next if ($c->id eq $hold->current_copy);
866
867                                 # circ lib is closed
868                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
869
870                                 # target of another hold
871                                 next if (action::hold_request
872                                                 ->search_where(
873                                                         { current_copy => $c->id,
874                                                           fulfillment_time => undef,
875                                                           cancel_time => undef,
876                                                         }
877                                                 )
878                                 );
879
880                                 # we passed all three, keep it
881                                 push @good_copies, $c if ($c);
882                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
883                         }
884
885                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
886
887                         my $old_best = $hold->current_copy;
888                         $hold->update({ current_copy => undef }) if ($old_best);
889         
890                         if (!scalar(@good_copies)) {
891                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
892                                 if (
893                                   $old_best &&
894                                   grep { $old_best eq $_ } @$all_copies &&
895                                   !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
896                                 ) {
897                                         # the old copy is still available
898                                         $log->debug("\tPushing current_copy back onto the targeting list");
899                                         push @good_copies, $old_best;
900                                 } else {
901                                         # oops, old copy is not available
902                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
903                                         $hold->update( { prev_check_time => 'today' } );
904                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
905                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
906                                         die "OK\n";
907                                 }
908                         }
909
910                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
911                         my $prox_list = [];
912                         $$prox_list[0] =
913                         [
914                                 grep {
915                                         $_->circ_lib == $hold->pickup_lib
916                                 } @good_copies
917                         ];
918
919                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
920
921                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
922                         my $best = choose_nearest_copy($hold, $prox_list);
923                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
924
925                         if (!$best) {
926                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
927                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
928
929                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
930
931                                 $best = choose_nearest_copy($hold, $prox_list);
932                         }
933
934                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
935                         if ($old_best) {
936                                 # hold wasn't fulfilled, record the fact
937                         
938                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
939                                 action::unfulfilled_hold_list->create(
940                                                 { hold => ''.$hold->id,
941                                                   current_copy => ''.$old_best->id,
942                                                   circ_lib => ''.$old_best->circ_lib,
943                                                 });
944                         }
945
946                         if ($best) {
947                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
948                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
949                         } elsif (
950                                 $old_best &&
951                                 action::hold_request
952                                         ->search_where(
953                                                 { current_copy => $old_best->id,
954                                                   fulfillment_time => undef,
955                                                   cancel_time => undef,
956                                                 }       
957                                         )
958                         ) {     
959                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
960                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
961                         } else {
962                                 $hold->update( { prev_check_time => 'now' } );
963                                 $log->info( "\tThere were no targetable copies for the hold" );
964                         }
965
966                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
967                         $log->info("\tProcessing of hold ".$hold->id." complete.");
968
969                         push @successes,
970                                 { hold => $hold->id,
971                                   old_target => ($old_best ? $old_best->id : undef),
972                                   eligible_copies => $copy_count,
973                                   target => ($best ? $best->id : undef) };
974
975                 } otherwise {
976                         my $e = shift;
977                         if ($e !~ /^OK/o) {
978                                 $log->error("Processing of hold failed:  $e");
979                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
980                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
981                         }
982                 };
983         }
984
985         return \@successes;
986 }
987 __PACKAGE__->register_method(
988         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
989         api_level       => 1,
990         method          => 'new_hold_copy_targeter',
991 );
992
993 my $locations;
994 my $statuses;
995 my %cache = (titles => {}, cns => {});
996 sub hold_copy_targeter {
997         my $self = shift;
998         my $client = shift;
999         my $check_expire = shift;
1000         my $one_hold = shift;
1001
1002         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1003         $self->{user_filter}->connect;
1004         $self->{client} = $client;
1005
1006         my $time = time;
1007         $check_expire ||= '12h';
1008         $check_expire = interval_to_seconds( $check_expire );
1009
1010         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1011         $year += 1900;
1012         $mon += 1;
1013         my $expire_threshold = sprintf(
1014                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1015                 $year, $mon, $mday, $hour, $min, $sec
1016         );
1017
1018
1019         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1020
1021         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1022
1023         my $holds;
1024
1025         %cache = (titles => {}, cns => {});
1026
1027         try {
1028                 if ($one_hold) {
1029                         $holds = [ action::hold_request->search(id => $one_hold) ];
1030                 } else {
1031                         $holds = [ action::hold_request->search_where(
1032                                                         { capture_time => undef,
1033                                                           prev_check_time => { '<=' => $expire_threshold },
1034                                                         },
1035                                                         { order_by => 'request_time,prev_check_time' } ) ];
1036                         push @$holds, action::hold_request->search_where(
1037                                                         { capture_time => undef,
1038                                                           prev_check_time => undef,
1039                                                         },
1040                                                         { order_by => 'request_time' } );
1041                 }
1042         } catch Error with {
1043                 my $e = shift;
1044                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1045         };
1046
1047         for my $hold (@$holds) {
1048                 try {
1049                         #action::hold_request->db_Main->begin_work;
1050                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1051                                 $client->respond("Cleaning up after previous transaction\n");
1052                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1053                         }
1054                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1055                         $client->respond("Processing hold ".$hold->id."...\n");
1056
1057                         my $copies;
1058
1059                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1060                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1061
1062                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1063                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1064                         
1065                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1066                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1067                         
1068                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1069
1070                         unless (ref $copies || !@$copies) {
1071                                 $client->respond("\tNo copies available for targeting at all!\n");
1072                         }
1073
1074                         my @good_copies;
1075                         for my $c (@$copies) {
1076                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1077                                 push @good_copies, $c if ($c);
1078                         }
1079
1080                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1081
1082                         my $old_best = $hold->current_copy;
1083                         $hold->update({ current_copy => undef });
1084         
1085                         if (!scalar(@good_copies)) {
1086                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1087                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1088                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1089                                         push @good_copies, asset::copy->retrieve( $old_best );
1090                                 } else {
1091                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1092                                         next;
1093                                 }
1094                         }
1095
1096                         my $prox_list;
1097                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1098                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1099
1100                         my $best = choose_nearest_copy($hold, $prox_list);
1101
1102                         if (!$best) {
1103                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1104                                 $best = choose_nearest_copy($hold, $prox_list);
1105                         }
1106
1107                         if ($old_best) {
1108                                 # hold wasn't fulfilled, record the fact
1109                         
1110                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1111                                 action::unfulfilled_hold_list->create(
1112                                                 { hold => ''.$hold->id,
1113                                                   current_copy => ''.$old_best->id,
1114                                                   circ_lib => ''.$old_best->circ_lib,
1115                                                 });
1116                         }
1117
1118                         if ($best) {
1119                                 $hold->update( { current_copy => ''.$best->id } );
1120                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1121                         }
1122
1123                         $hold->update( { prev_check_time => 'now' } );
1124                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1125
1126                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1127                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1128
1129                         #action::hold_request->dbi_commit;
1130
1131                 } otherwise {
1132                         my $e = shift;
1133                         $log->error("Processing of hold failed:  $e");
1134                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1135                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1136                         #action::hold_request->dbi_rollback;
1137                 };
1138         }
1139
1140         $self->{user_filter}->disconnect;
1141         $self->{user_filter}->finish;
1142         delete $$self{user_filter};
1143         return undef;
1144 }
1145 __PACKAGE__->register_method(
1146         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1147         api_level       => 0,
1148         stream          => 1,
1149         method          => 'hold_copy_targeter',
1150 );
1151
1152
1153 sub copy_hold_capture {
1154         my $self = shift;
1155         my $hold = shift;
1156         my $cps = shift;
1157
1158         if (!defined($cps)) {
1159                 try {
1160                         $cps = [ asset::copy->search( id => $hold->target ) ];
1161                 } catch Error with {
1162                         my $e = shift;
1163                         die "Could not retrieve initial volume list:\n\n$e\n";
1164                 };
1165         }
1166
1167         my @copies = grep { $_->holdable } @$cps;
1168
1169         for (my $i = 0; $i < @$cps; $i++) {
1170                 next unless $$cps[$i];
1171                 
1172                 my $cn = $cache{cns}{$copies[$i]->call_number};
1173                 my $rec = $cache{titles}{$cn->record};
1174                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1175                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1176                 $copies[$i] = undef if (
1177                         !$copies[$i] ||
1178                         !$self->{user_filter}->request(
1179                                 'open-ils.circ.permit_hold',
1180                                 $hold->to_fieldmapper, do {
1181                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1182                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1183                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1184                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1185                                         $cp_fm;
1186                                 },
1187                                 { title => $rec->to_fieldmapper,
1188                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1189                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1190                                 })->gather(1)
1191                 );
1192                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1193         }
1194
1195         @copies = grep { $_ } @copies;
1196
1197         my $count = @copies;
1198
1199         return unless ($count);
1200         
1201         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1202         
1203         my @maps;
1204         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1205         for my $c (@copies) {
1206                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1207         }
1208         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1209
1210         return \@copies;
1211 }
1212
1213
1214 sub choose_nearest_copy {
1215         my $hold = shift;
1216         my $prox_list = shift;
1217
1218         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1219                 next unless (ref $$prox_list[$p]);
1220
1221                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1222                 next unless (@capturable);
1223
1224                 my $rand = int(rand(scalar(@capturable)));
1225                 while (my ($c) = splice(@capturable,$rand)) {
1226                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1227                                 { title => $c->call_number->record->to_fieldmapper,
1228                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1229                                   patron => $hold->usr->to_fieldmapper,
1230                                   copy => $c->to_fieldmapper,
1231                                   requestor => $hold->requestor->to_fieldmapper,
1232                                   request_lib => $hold->request_lib->to_fieldmapper,
1233                                    pickup_lib => $hold->pickup_lib->id,
1234                                 }
1235                         ));
1236
1237                         last unless(@capturable);
1238                         $rand = int(rand(scalar(@capturable)));
1239                 }
1240         }
1241 }
1242
1243 sub create_prox_list {
1244         my $self = shift;
1245         my $lib = shift;
1246         my $copies = shift;
1247
1248         my @prox_list;
1249         for my $cp (@$copies) {
1250                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1251                 next unless (defined($prox));
1252                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1253                 push @{$prox_list[$prox]}, $cp;
1254         }
1255         return \@prox_list;
1256 }
1257
1258 sub volume_hold_capture {
1259         my $self = shift;
1260         my $hold = shift;
1261         my $vols = shift;
1262
1263         if (!defined($vols)) {
1264                 try {
1265                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1266                         $cache{cns}{$_->id} = $_ for (@$vols);
1267                 } catch Error with {
1268                         my $e = shift;
1269                         die "Could not retrieve initial volume list:\n\n$e\n";
1270                 };
1271         }
1272
1273         my @v_ids = map { $_->id } @$vols;
1274
1275         my $cp_list;
1276         try {
1277                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1278         
1279         } catch Error with {
1280                 my $e = shift;
1281                 warn "Could not retrieve copy list:\n\n$e\n";
1282         };
1283
1284         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1285 }
1286
1287 sub title_hold_capture {
1288         my $self = shift;
1289         my $hold = shift;
1290         my $titles = shift;
1291
1292         if (!defined($titles)) {
1293                 try {
1294                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1295                         $cache{titles}{$_->id} = $_ for (@$titles);
1296                 } catch Error with {
1297                         my $e = shift;
1298                         die "Could not retrieve initial title list:\n\n$e\n";
1299                 };
1300         }
1301
1302         my @t_ids = map { $_->id } @$titles;
1303         my $cn_list;
1304         try {
1305                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1306         
1307         } catch Error with {
1308                 my $e = shift;
1309                 warn "Could not retrieve volume list:\n\n$e\n";
1310         };
1311
1312         $cache{cns}{$_->id} = $_ for (@$cn_list);
1313
1314         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1315 }
1316
1317 sub metarecord_hold_capture {
1318         my $self = shift;
1319         my $hold = shift;
1320
1321         my $titles;
1322         try {
1323                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1324         
1325         } catch Error with {
1326                 my $e = shift;
1327                 die "Could not retrieve initial title list:\n\n$e\n";
1328         };
1329
1330         try {
1331                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1332
1333                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1334         
1335         } catch Error with {
1336                 my $e = shift;
1337                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1338         };
1339
1340
1341         $cache{titles}{$_->id} = $_ for (@$titles);
1342         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1343 }
1344
1345 1;