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