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