]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
forward-porting r15367: correct billing timestamp and count calculation issues introd...
[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 use OpenILS::Utils::Penalty;
12
13 sub isTrue {
14         my $v = shift;
15         return 1 if ($v == 1);
16         return 1 if ($v =~ /^t/io);
17         return 1 if ($v =~ /^y/io);
18         return 0;
19 }
20
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
23
24 sub open_noncat_circs {
25         my $self = shift;
26         my $client = shift;
27         my $user = shift;
28
29         my $a = action::non_cataloged_circulation->table;
30         my $c = config::non_cataloged_type->table;
31
32         my $sql = <<"   SQL";
33                 SELECT  a.id
34                   FROM  $a a
35                         JOIN $c c ON (a.item_type = c.id)
36                   WHERE a.circ_time + c.circ_duration > current_timestamp
37                         AND a.patron = ?
38         SQL
39
40         return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
41 }
42 __PACKAGE__->register_method(
43         api_name        => 'open-ils.storage.action.open_non_cataloged_circulation.user',
44         api_level       => 1,
45         argc            => 1,
46         method          => 'open_noncat_circs',
47 );
48
49
50 sub ou_hold_requests {
51         my $self = shift;
52         my $client = shift;
53         my $ou = shift;
54
55         my $h_table = action::hold_request->table;
56         my $c_table = asset::copy->table;
57         my $o_table = actor::org_unit->table;
58
59         my $SQL = <<"   SQL";
60                 SELECT  h.id
61                   FROM  $h_table h
62                         JOIN $c_table cp ON (cp.id = h.current_copy)
63                         JOIN $o_table ou ON (ou.id = cp.circ_lib)
64                   WHERE ou.id = ?
65                         AND h.capture_time IS NULL
66                         AND h.cancel_time IS NULL
67                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
68                   ORDER BY h.request_time
69         SQL
70
71         my $sth = action::hold_request->db_Main->prepare_cached($SQL);
72         $sth->execute($ou);
73
74         $client->respond($_) for (
75                 map {
76                         $self
77                                 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
78                                 ->run($_)
79                 } map {
80                         $_->[0]
81                 } @{ $sth->fetchall_arrayref }
82         );
83         return undef;
84 }
85 __PACKAGE__->register_method(
86         api_name        => 'open-ils.storage.action.targeted_hold_request.org_unit',
87         api_level       => 1,
88         argc            => 1,
89         stream          => 1,
90         method          => 'ou_hold_requests',
91 );
92
93
94 sub overdue_circs {
95         my $grace = shift;
96     my $upper_interval = shift || '1 millennium';
97
98         my $c_t = action::circulation->table;
99
100         if ($grace && $grace =~ /^\d+$/o) {
101         $grace = " - ($grace * (fine_interval))";
102     } else {
103         $grace = '';
104     } 
105
106         my $sql = <<"   SQL";
107                 SELECT  *
108                   FROM  $c_t
109                   WHERE stop_fines IS NULL
110                         AND due_date < ( CURRENT_TIMESTAMP $grace)
111             AND fine_interval < ?::INTERVAL
112         SQL
113
114         my $sth = action::circulation->db_Main->prepare_cached($sql);
115         $sth->execute($upper_interval);
116
117         my @circs = map { action::circulation->construct($_) } $sth->fetchall_hash;
118
119         $c_t = booking::reservation->table;
120         $sql = <<"      SQL";
121                 SELECT  *
122                   FROM  $c_t
123                   WHERE return_time IS NULL
124                         AND end_time < ( CURRENT_TIMESTAMP $grace)
125             AND fine_interval IS NOT NULL
126             AND cancel_time IS NULL
127         SQL
128
129         $sth = action::circulation->db_Main->prepare_cached($sql);
130         $sth->execute();
131
132     push @circs, map { booking::reservation->construct($_) } $sth->fetchall_hash;
133
134     return @circs;
135 }
136
137 sub complete_reshelving {
138         my $self = shift;
139         my $client = shift;
140         my $window = shift;
141
142         local $OpenILS::Application::Storage::WRITE = 1;
143
144         throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
145                 unless (interval_to_seconds( $window ));
146
147         my $setting = actor::org_unit_setting->table;
148         my $circ = action::circulation->table;
149         my $cp = asset::copy->table;
150
151         my $sql = <<"   SQL";
152                 UPDATE  $cp
153                   SET   status = 0
154                   WHERE id IN (
155             SELECT  id
156               FROM  (SELECT cp.id, MAX(circ.checkin_time)
157                       FROM  $cp cp
158                             JOIN $circ circ ON (circ.target_copy = cp.id)
159                             LEFT JOIN $setting setting
160                                 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
161                       WHERE circ.checkin_time IS NOT NULL
162                             AND cp.status = 7
163                       GROUP BY 1
164                       HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? )  AS INTERVAL)
165                     ) AS foo
166                                 UNION ALL
167             SELECT  cp.id
168                            FROM $cp cp 
169                     LEFT JOIN $setting setting
170                         ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
171                     LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
172               WHERE cp.status = 7 AND circ.id IS NULL
173                     AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? )  AS INTERVAL)
174           )
175         SQL
176
177         my $sth = action::circulation->db_Main->prepare_cached($sql);
178         $sth->execute($window, $window);
179
180         return $sth->rows;
181
182 }
183 __PACKAGE__->register_method(
184         api_name        => 'open-ils.storage.action.circulation.reshelving.complete',
185         api_level       => 1,
186         argc            => 1,
187         method          => 'complete_reshelving',
188 );
189
190 sub mark_longoverdue {
191         my $self = shift;
192         my $client = shift;
193         my $window = shift;
194
195         local $OpenILS::Application::Storage::WRITE = 1;
196
197         throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
198                 unless (interval_to_seconds( $window ));
199
200         my $setting = actor::org_unit_setting->table;
201         my $circ = action::circulation->table;
202
203         my $sql = <<"   SQL";
204                 UPDATE  $circ
205                   SET   stop_fines = 'LONGOVERDUE',
206                         stop_fines_time = now()
207                   WHERE id IN (
208                     SELECT  circ.id
209                       FROM  $circ circ
210                             LEFT JOIN $setting setting
211                                 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
212                       WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
213                             AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? )  AS INTERVAL)
214                   )
215         SQL
216
217         my $sth = action::circulation->db_Main->prepare_cached($sql);
218         $sth->execute($window);
219
220         return $sth->rows;
221
222 }
223 __PACKAGE__->register_method(
224         api_name        => 'open-ils.storage.action.circulation.long_overdue',
225         api_level       => 1,
226         argc            => 1,
227         method          => 'mark_longoverdue',
228 );
229
230 sub auto_thaw_frozen_holds {
231         my $self = shift;
232         my $client = shift;
233
234         local $OpenILS::Application::Storage::WRITE = 1;
235
236         my $holds = action::hold_request->table;
237
238         my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
239
240         my $sth = action::hold_request->db_Main->prepare_cached($sql);
241         $sth->execute();
242
243         return $sth->rows;
244
245 }
246 __PACKAGE__->register_method(
247         api_name        => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
248         api_level       => 1,
249         stream          => 0,
250         argc            => 0,
251         method          => 'auto_thaw_frozen_holds',
252 );
253
254 sub grab_overdue {
255         my $self = shift;
256         my $client = shift;
257         my $grace = shift || '';
258
259         $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
260
261         return undef;
262
263 }
264 __PACKAGE__->register_method(
265         api_name        => 'open-ils.storage.action.circulation.overdue',
266         api_level       => 1,
267         stream          => 1,
268         method          => 'grab_overdue',
269 );
270
271 sub nearest_hold {
272         my $self = shift;
273         my $client = shift;
274         my $here = shift;
275         my $cp = shift;
276         my $limit = int(shift()) || 10;
277         my $age = shift() || '0 seconds';
278
279         my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
280                 SELECT  h.id
281                   FROM  action.hold_request h
282                         JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
283                         JOIN action.hold_copy_map hm ON (hm.hold = h.id)
284                   WHERE hm.target_copy = ?
285                         AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
286                         AND h.capture_time IS NULL
287                         AND h.cancel_time IS NULL
288                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
289             AND h.frozen IS FALSE
290                 ORDER BY
291                         p.prox,
292             CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
293                         h.selection_depth DESC,
294                         h.request_time
295                 LIMIT $limit
296         SQL
297         
298         $client->respond( $_ ) for ( @$ids );
299         return undef;
300 }
301 __PACKAGE__->register_method(
302         api_name        => 'open-ils.storage.action.hold_request.nearest_hold',
303         api_level       => 1,
304         stream          => 1,
305         method          => 'nearest_hold',
306 );
307
308 sub next_resp_group_id {
309         my $self = shift;
310         my $client = shift;
311
312         # XXX This is not replication safe!!!
313
314         my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
315                 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
316         SQL
317         return $id;
318 }
319 __PACKAGE__->register_method(
320         api_name        => 'open-ils.storage.action.survey_response.next_group_id',
321         api_level       => 1,
322         method          => 'next_resp_group_id',
323 );
324
325 sub patron_circ_summary {
326         my $self = shift;
327         my $client = shift;
328         my $id = ''.shift();
329
330         return undef unless ($id);
331         my $c_table = action::circulation->table;
332         my $b_table = money::billing->table;
333
334         $log->debug("Retrieving patron summary for id $id", DEBUG);
335
336         my $select = <<"        SQL";
337                 SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
338                   FROM  $c_table c
339                         LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
340                   WHERE c.usr = ?
341                         AND c.xact_finish IS NULL
342                         AND (
343                                 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
344                                 OR c.stop_fines IS NULL
345                         )
346         SQL
347
348         return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
349 }
350 __PACKAGE__->register_method(
351         api_name        => 'open-ils.storage.action.circulation.patron_summary',
352         api_level       => 1,
353         method          => 'patron_circ_summary',
354 );
355
356 #XXX Fix stored proc calls
357 sub find_local_surveys {
358         my $self = shift;
359         my $client = shift;
360         my $ou = ''.shift();
361
362         return undef unless ($ou);
363         my $s_table = action::survey->table;
364
365         my $select = <<"        SQL";
366                 SELECT  s.*
367                   FROM  $s_table s
368                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
369                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
370         SQL
371
372         my $sth = action::survey->db_Main->prepare_cached($select);
373         $sth->execute($ou);
374
375         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
376
377         return undef;
378 }
379 __PACKAGE__->register_method(
380         api_name        => 'open-ils.storage.action.survey.all',
381         api_level       => 1,
382         stream          => 1,
383         method          => 'find_local_surveys',
384 );
385
386 #XXX Fix stored proc calls
387 sub find_opac_surveys {
388         my $self = shift;
389         my $client = shift;
390         my $ou = ''.shift();
391
392         return undef unless ($ou);
393         my $s_table = action::survey->table;
394
395         my $select = <<"        SQL";
396                 SELECT  s.*
397                   FROM  $s_table s
398                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
399                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
400                         AND s.opac IS TRUE;
401         SQL
402
403         my $sth = action::survey->db_Main->prepare_cached($select);
404         $sth->execute($ou);
405
406         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
407
408         return undef;
409 }
410 __PACKAGE__->register_method(
411         api_name        => 'open-ils.storage.action.survey.opac',
412         api_level       => 1,
413         stream          => 1,
414         method          => 'find_opac_surveys',
415 );
416
417 sub hold_pull_list {
418         my $self = shift;
419         my $client = shift;
420         my $ou = shift;
421         my $limit = shift || 10;
422         my $offset = shift || 0;
423
424         return undef unless ($ou);
425         my $h_table = action::hold_request->table;
426         my $a_table = asset::copy->table;
427         my $ord_table = asset::copy_location_order->table;
428
429         my $idlist = 1 if ($self->api_name =~/id_list/o);
430         my $count = 1 if ($self->api_name =~/count$/o);
431
432         my $status_filter = '';
433         $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
434
435         my $select = <<"        SQL";
436                 SELECT  h.*
437                   FROM  $h_table h
438                         JOIN $a_table a ON (h.current_copy = a.id)
439                         LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
440                   WHERE a.circ_lib = ?
441                         AND h.capture_time IS NULL
442                         AND h.cancel_time IS NULL
443                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
444                         $status_filter
445                   ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
446                   LIMIT $limit
447                   OFFSET $offset
448         SQL
449
450     if ($count) {
451         $select = <<"        SQL";
452             SELECT    count(*)
453               FROM    $h_table h
454                   JOIN $a_table a ON (h.current_copy = a.id)
455               WHERE    a.circ_lib = ?
456                   AND h.capture_time IS NULL
457                   AND h.cancel_time IS NULL
458                   AND (h.expire_time IS NULL OR h.expire_time > NOW())
459                 $status_filter
460         SQL
461     }
462
463         my $sth = action::survey->db_Main->prepare_cached($select);
464         $sth->execute($ou);
465
466         if ($count) {
467                 $client->respond( $sth->fetchall_arrayref()->[0][0] );
468         } elsif ($idlist) {
469                 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
470         } else {
471                 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
472         }
473
474         return undef;
475 }
476 __PACKAGE__->register_method(
477         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
478         api_level       => 1,
479         stream          => 1,
480         signature       => [
481                 "Returns a count of holds for a specific library's pull list.",
482                 [ [org_unit => "The library's org id", "number"] ],
483                 ['A count of holds for the stated library to pull ', 'number']
484         ],
485         method          => 'hold_pull_list',
486 );
487 __PACKAGE__->register_method(
488         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
489         api_level       => 1,
490         stream          => 1,
491         signature       => [
492                 "Returns a status filtered count of holds for a specific library's pull list.",
493                 [ [org_unit => "The library's org id", "number"] ],
494                 ['A status filtered count of holds for the stated library to pull ', 'number']
495         ],
496         method          => 'hold_pull_list',
497 );
498 __PACKAGE__->register_method(
499         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
500         api_level       => 1,
501         stream          => 1,
502         signature       => [
503                 "Returns the hold ids for a specific library's pull list.",
504                 [ [org_unit => "The library's org id", "number"],
505                   [limit => 'An optional page size, defaults to 10', 'number'],
506                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
507                 ],
508                 ['A list of holds for the stated library to pull for', 'array']
509         ],
510         method          => 'hold_pull_list',
511 );
512 __PACKAGE__->register_method(
513         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
514         api_level       => 1,
515         stream          => 1,
516         signature       => [
517                 "Returns the holds for a specific library's pull list.",
518                 [ [org_unit => "The library's org id", "number"],
519                   [limit => 'An optional page size, defaults to 10', 'number'],
520                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
521                 ],
522                 ['A list of holds for the stated library to pull for', 'array']
523         ],
524         method          => 'hold_pull_list',
525 );
526 __PACKAGE__->register_method(
527         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
528         api_level       => 1,
529         stream          => 1,
530         signature       => [
531                 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
532                 [ [org_unit => "The library's org id", "number"],
533                   [limit => 'An optional page size, defaults to 10', 'number'],
534                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
535                 ],
536                 ['A list of holds for the stated library to pull for', 'array']
537         ],
538         method          => 'hold_pull_list',
539 );
540 __PACKAGE__->register_method(
541         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
542         api_level       => 1,
543         stream          => 1,
544         signature       => [
545                 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
546                 [ [org_unit => "The library's org id", "number"],
547                   [limit => 'An optional page size, defaults to 10', 'number'],
548                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
549                 ],
550                 ['A list of holds for the stated library to pull for', 'array']
551         ],
552         method          => 'hold_pull_list',
553 );
554
555 sub find_optional_surveys {
556         my $self = shift;
557         my $client = shift;
558         my $ou = ''.shift();
559
560         return undef unless ($ou);
561         my $s_table = action::survey->table;
562
563         my $select = <<"        SQL";
564                 SELECT  s.*
565                   FROM  $s_table s
566                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
567                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
568                         AND s.required IS FALSE;
569         SQL
570
571         my $sth = action::survey->db_Main->prepare_cached($select);
572         $sth->execute($ou);
573
574         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
575
576         return undef;
577 }
578 __PACKAGE__->register_method(
579         api_name        => 'open-ils.storage.action.survey.optional',
580         api_level       => 1,
581         stream          => 1,
582         method          => 'find_optional_surveys',
583 );
584
585 sub find_required_surveys {
586         my $self = shift;
587         my $client = shift;
588         my $ou = ''.shift();
589
590         return undef unless ($ou);
591         my $s_table = action::survey->table;
592
593         my $select = <<"        SQL";
594                 SELECT  s.*
595                   FROM  $s_table s
596                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
597                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
598                         AND s.required IS TRUE;
599         SQL
600
601         my $sth = action::survey->db_Main->prepare_cached($select);
602         $sth->execute($ou);
603
604         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
605
606         return undef;
607 }
608 __PACKAGE__->register_method(
609         api_name        => 'open-ils.storage.action.survey.required',
610         api_level       => 1,
611         stream          => 1,
612         method          => 'find_required_surveys',
613 );
614
615 sub find_usr_summary_surveys {
616         my $self = shift;
617         my $client = shift;
618         my $ou = ''.shift();
619
620         return undef unless ($ou);
621         my $s_table = action::survey->table;
622
623         my $select = <<"        SQL";
624                 SELECT  s.*
625                   FROM  $s_table s
626                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
627                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
628                         AND s.usr_summary IS TRUE;
629         SQL
630
631         my $sth = action::survey->db_Main->prepare_cached($select);
632         $sth->execute($ou);
633
634         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
635
636         return undef;
637 }
638 __PACKAGE__->register_method(
639         api_name        => 'open-ils.storage.action.survey.usr_summary',
640         api_level       => 1,
641         stream          => 1,
642         method          => 'find_usr_summary_surveys',
643 );
644
645
646 sub generate_fines {
647         my $self = shift;
648         my $client = shift;
649         my $grace = shift;
650         my $circ = shift;
651         my $overbill = shift;
652
653         local $OpenILS::Application::Storage::WRITE = 1;
654
655         my @circs;
656         if ($circ) {
657                 push @circs,
658             action::circulation->search_where( { id => $circ, stop_fines => undef } ),
659             booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
660         } else {
661                 push @circs, overdue_circs($grace);
662         }
663
664         my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
665
666         my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
667         for my $c (@circs) {
668
669         my $ctype = ref($c);
670         $ctype =~ s/^.*([^:]+)$/$1/o;
671         
672         my $due_date_method = 'due_date';
673         my $target_copy_method = 'target_copy';
674         my $circ_lib_method = 'circ_lib';
675         my $recurring_fine_method = 'recurring_fine';
676         my $is_reservation = 0;
677         if ($ctype eq 'reservation') {
678             $is_reservation = 1;
679             $due_date_method = 'end_time';
680             $target_copy_method = 'current_resource';
681             $circ_lib_method = 'pickup_lib';
682             $recurring_fine_method = 'fine_amount';
683             next unless ($c->fine_interval);
684         }
685
686                 try {
687                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
688                                 $log->debug("Cleaning up after previous transaction\n");
689                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
690                         }
691                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
692                         $log->info("Processing circ ".$c->id."...\n");
693
694
695                         my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
696         
697                         my $due = $due_dt->epoch;
698                         my $now = time;
699
700                         my $fine_interval = $c->fine_interval;
701             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
702                         $fine_interval = interval_to_seconds( $fine_interval );
703         
704                         if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {        
705                                 my $tz_offset_s = 0;
706                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
707                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
708                                 }
709         
710                                 $due -= ($due % $fine_interval) + $tz_offset_s;
711                                 $now -= ($now % $fine_interval) + $tz_offset_s;
712                         }
713         
714                         $client->respond(
715                                 "ARG! Overdue $ctype ".$c->id.
716                                 " for item ".$c->$target_copy_method.
717                                 " (user ".$c->usr.").\n".
718                                 "\tItem was due on or before: ".localtime($due)."\n");
719         
720                         my @fines = money::billing->search_where(
721                                 { xact => $c->id,
722                                   btype => 1,
723                                   billing_ts => { '>' => $c->$due_date_method } },
724                                 { order_by => 'billing_ts DESC'}
725                         );
726
727                         my $f_idx = 0;
728                         my $fine = $fines[$f_idx] if (@fines);
729                         if ($overbill) {
730                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
731                         }
732
733                         my $current_fine_total = 0;
734                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
735         
736                         my $last_fine;
737                         if ($fine) {
738                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
739                                 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
740                         } else {
741                                 $log->info( "Potential first billing for circ ".$c->id );
742                                 $last_fine = $due;
743
744                                 if (0) {
745                                         if (my $h = $hoo{$c->$circ_lib_method}) { 
746
747                                                 $log->info( "Circ lib has an hours-of-operation entry" );
748                                                 # find the day after the due date...
749                                                 $due_dt = $due_dt->add( days => 1 );
750
751                                                 # get the day of the week for that day...
752                                                 my $dow = $due_dt->day_of_week_0;
753                                                 my $dow_open = "dow_${dow}_open";
754                                                 my $dow_close = "dow_${dow}_close";
755
756                                                 my $count = 0;
757                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
758                                                         # if the circ lib is closed, add a day to the grace period...
759
760                                                         $grace++;
761                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
762                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
763
764                                                         $due_dt = $due_dt->add( days => 1 );
765                                                         $dow = $due_dt->day_of_week_0;
766                                                         $dow_open = "dow_${dow}_open";
767                                                         $dow_close = "dow_${dow}_close";
768
769                                                         $count++;
770
771                                                         # and check for up to a week
772                                                         last if ($count > 6);
773                                                 }
774                                         }
775                                 }
776                         }
777
778             next if ($last_fine > $now);
779             my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
780
781             # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
782             $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
783
784             if ( $last_fine == $due                         # we have no fines yet
785                  && $grace                                  # and we have a grace period
786                  && $pending_fine_count <= $grace           # and we seem to be inside that period
787                  && $now < $due + $fine_interval * $grace   # and some date math bares that out, then
788             ) {
789                 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
790                 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
791                 next;
792             }
793
794             $client->respond( "\t$pending_fine_count pending fine(s)\n" );
795             next unless ($pending_fine_count);
796
797                         my $recuring_fine = int($c->$recurring_fine_method * 100);
798                         my $max_fine = int($c->max_fine * 100);
799
800                         my ($latest_billing_ts, $latest_amount) = ('',0);
801                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
802         
803                                 if ($current_fine_total >= $max_fine) {
804                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
805                                         $client->respond(
806                                                 "\tMaximum fine level of ".$c->max_fine.
807                                                 " reached for this $ctype.\n".
808                                                 "\tNo more fines will be generated.\n" );
809                                         last;
810                                 }
811                                 
812                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
813
814                                 my $dow = $billing_ts->day_of_week_0();
815                                 my $dow_open = "dow_${dow}_open";
816                                 my $dow_close = "dow_${dow}_close";
817
818                                 if (my $h = $hoo{$c->$circ_lib_method}) {
819                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
820                                 }
821
822                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
823                                 my @cl = actor::org_unit::closed_date->search_where(
824                                                 { close_start   => { '<=' => $timestamptz },
825                                                   close_end     => { '>=' => $timestamptz },
826                                                   org_unit      => $c->$circ_lib_method }
827                                 );
828                                 next if (@cl);
829         
830                                 $current_fine_total += $recurring_fine;
831                                 $latest_amount += $recurring_fine;
832                                 $latest_billing_ts = $timestamptz;
833
834                                 money::billing->create(
835                                         { xact          => ''.$c->id,
836                                           note          => "System Generated Overdue Fine",
837                                           billing_type  => "Overdue materials",
838                                           btype         => 1,
839                                           amount        => sprintf('%0.2f', $recurring_fine/100),
840                                           billing_ts    => $timestamptz,
841                                         }
842                                 );
843
844                         }
845
846                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
847                                 if ($latest_billing_ts and $latest_amount);
848
849                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
850
851                         if(1) { 
852
853                 # Caluclate penalties inline
854                                 OpenILS::Utils::Penalty->calculate_penalties(
855                                         undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
856
857                         } else {
858
859                 # Calculate penalties with an aysnc call to the penalty server.  This approach
860                 # may lead to duplicate penalties since multiple penalty processes for a
861                 # given user may be running at the same time. Leave this here for reference 
862                 # in case we later find that asyc calls are needed in some environments.
863                                 $penalty->request(
864                                     'open-ils.penalty.patron_penalty.calculate',
865                                     { patronid  => ''.$c->usr,
866                                     context_org => ''.$c->$circ_lib_method,
867                                     update      => 1,
868                                     background  => 1,
869                                     }
870                             )->gather(1);
871                         }
872
873                 } catch Error with {
874                         my $e = shift;
875                         $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
876                         $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
877                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
878                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
879                 };
880         }
881 }
882 __PACKAGE__->register_method(
883         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
884         api_level       => 1,
885         stream          => 1,
886         method          => 'generate_fines',
887 );
888
889
890
891 sub new_hold_copy_targeter {
892         my $self = shift;
893         my $client = shift;
894         my $check_expire = shift;
895         my $one_hold = shift;
896
897         local $OpenILS::Application::Storage::WRITE = 1;
898
899         $self->{target_weight} = {};
900
901         my $holds;
902
903         try {
904                 if ($one_hold) {
905                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
906                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
907                 } elsif ( $check_expire ) {
908
909                         # what's the retarget time threashold?
910                         my $time = time;
911                         $check_expire ||= '12h';
912                         $check_expire = interval_to_seconds( $check_expire );
913
914                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
915                         $year += 1900;
916                         $mon += 1;
917                         my $expire_threshold = sprintf(
918                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
919                                 $year, $mon, $mday, $hour, $min, $sec
920                         );
921
922                         # find all the holds holds needing retargeting
923                         $holds = [ action::hold_request->search_where(
924                                                         { capture_time => undef,
925                                                           fulfillment_time => undef,
926                                                           cancel_time => undef,
927                                                           frozen => 'f',
928                                                           prev_check_time => { '<=' => $expire_threshold },
929                                                         },
930                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
931
932                         # find all the holds holds needing first time targeting
933                         push @$holds, action::hold_request->search(
934                                                         capture_time => undef,
935                                                         fulfillment_time => undef,
936                                                         prev_check_time => undef,
937                                                         frozen => 'f',
938                                                         cancel_time => undef,
939                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
940                 } else {
941
942                         # find all the holds holds needing first time targeting ONLY
943                         $holds = [ action::hold_request->search(
944                                                         capture_time => undef,
945                                                         fulfillment_time => undef,
946                                                         prev_check_time => undef,
947                                                         cancel_time => undef,
948                                                         frozen => 'f',
949                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
950                 }
951         } catch Error with {
952                 my $e = shift;
953                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
954         };
955
956         my @closed = actor::org_unit::closed_date->search_where(
957                 { close_start => { '<=', 'now' },
958                   close_end => { '>=', 'now' } }
959         );
960
961     if ($check_expire) {
962
963         # $check_expire, if it exists, was already converted to seconds
964         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
965             $year += 1900;
966         $mon += 1;
967
968             my $next_check_time = sprintf(
969                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
970                 $year, $mon, $mday, $hour, $min, $sec
971         );
972
973
974             my @closed_at_next = actor::org_unit::closed_date->search_where(
975                     { close_start => { '<=', $next_check_time },
976                   close_end => { '>=', $next_check_time } }
977             );
978
979         my @new_closed;
980         for my $c_at_n (@closed_at_next) {
981             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
982                 push @new_closed, $c_at_n;
983             }
984         }
985         @closed = @new_closed;
986     }
987
988         my @successes;
989         my $actor = OpenSRF::AppSession->create('open-ils.actor');
990
991         for my $hold (@$holds) {
992                 try {
993                         #start a transaction if needed
994                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
995                                 $log->debug("Cleaning up after previous transaction\n");
996                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
997                         }
998                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
999                         $log->info("Processing hold ".$hold->id."...\n");
1000
1001                         #first, re-fetch the hold, to make sure it's not captured already
1002                         $hold->remove_from_object_index();
1003                         $hold = action::hold_request->retrieve( $hold->id );
1004
1005                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1006
1007                         # remove old auto-targeting maps
1008                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1009                         $_->delete for (@oldmaps);
1010
1011                         if ($hold->expire_time) {
1012                                 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1013                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1014
1015                                         # cancel cause = un-targeted expiration
1016                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1017                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1018
1019                                         # tell A/T the hold was cancelled
1020                                         my $fm_hold = $hold->to_fieldmapper;
1021                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1022                                         $ses->request('open-ils.trigger.event.autocreate', 
1023                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1024
1025                                         die "OK\n";
1026                                 }
1027                         }
1028
1029                         my $all_copies = [];
1030
1031                         # find filters for MR holds
1032                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1033
1034                         # find all the potential copies
1035                         if ($hold->hold_type eq 'M') {
1036                                 for my $r ( map
1037                                                 {$_->record}
1038                                                 metabib::record_descriptor
1039                                                         ->search(
1040                                                                 record => [
1041                                                                         map {
1042                                                                                 isTrue($_->deleted) ?  () : ($_->id)
1043                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
1044                                                                 ],
1045                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
1046                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
1047                                                                 ( $lang    ? (item_lang => $lang)                : () ),
1048                                                         )
1049                                 ) {
1050                                         my ($rtree) = $self
1051                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1052                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1053
1054                                         for my $cn ( @{ $rtree->call_numbers } ) {
1055                                                 push @$all_copies,
1056                                                         asset::copy->search_where(
1057                                                                 { id => [map {$_->id} @{ $cn->copies }],
1058                                                                   deleted => 'f' }
1059                                                         ) if ($cn && @{ $cn->copies });
1060                                         }
1061                                 }
1062                         } elsif ($hold->hold_type eq 'T') {
1063                                 my ($rtree) = $self
1064                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1065                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1066
1067                                 unless ($rtree) {
1068                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1069                                         die "OK\n";
1070                                 }
1071
1072                                 for my $cn ( @{ $rtree->call_numbers } ) {
1073                                         push @$all_copies,
1074                                                 asset::copy->search_where(
1075                                                         { id => [map {$_->id} @{ $cn->copies }],
1076                                                           deleted => 'f' }
1077                                                 ) if ($cn && @{ $cn->copies });
1078                                 }
1079                         } elsif ($hold->hold_type eq 'V') {
1080                                 my ($vtree) = $self
1081                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1082                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1083
1084                                 push @$all_copies,
1085                                         asset::copy->search_where(
1086                                                 { id => [map {$_->id} @{ $vtree->copies }],
1087                                                   deleted => 'f' }
1088                                         ) if ($vtree && @{ $vtree->copies });
1089                                         
1090                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1091                                 my $_cp = asset::copy->retrieve($hold->target);
1092                                 push @$all_copies, $_cp if $_cp;
1093                         }
1094
1095                         # trim unholdables
1096                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1097                                                 isTrue($_->location->holdable) && 
1098                                                 isTrue($_->holdable) &&
1099                                                 !isTrue($_->deleted) &&
1100                                                 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1101                                         } @$all_copies;
1102
1103                         # let 'em know we're still working
1104                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1105                         
1106                         # if we have no copies ...
1107                         if (!ref $all_copies || !@$all_copies) {
1108                                 $log->info("\tNo copies available for targeting at all!\n");
1109                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1110
1111                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1112                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1113                                 die "OK\n";
1114                         }
1115
1116                         my $copy_count = @$all_copies;
1117
1118                         # map the potentials, so that we can pick up checkins
1119                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1120                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1121                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1122                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1123
1124                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1125
1126                         my @good_copies;
1127                         for my $c (@$all_copies) {
1128                                 # current target
1129                                 next if ($c->id eq $hold->current_copy);
1130
1131                                 # circ lib is closed
1132                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1133
1134                                 # target of another hold
1135                                 next if (action::hold_request
1136                                                 ->search_where(
1137                                                         { current_copy => $c->id,
1138                                                           fulfillment_time => undef,
1139                                                           cancel_time => undef,
1140                                                         }
1141                                                 )
1142                                 );
1143
1144                                 # we passed all three, keep it
1145                                 push @good_copies, $c if ($c);
1146                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1147                         }
1148
1149                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1150
1151                         my $old_best = $hold->current_copy;
1152                         $hold->update({ current_copy => undef }) if ($old_best);
1153         
1154                         if (!scalar(@good_copies)) {
1155                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1156                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1157                                         # the old copy is still available
1158                                         $log->debug("\tPushing current_copy back onto the targeting list");
1159                                         push @good_copies, $old_best;
1160                                 } else {
1161                                         # oops, old copy is not available
1162                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1163                                         $hold->update( { prev_check_time => 'today' } );
1164                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1165                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1166                                         die "OK\n";
1167                                 }
1168                         }
1169
1170                         my $prox_list = [];
1171                         $$prox_list[0] =
1172                         [
1173                                 grep {
1174                                         $_->circ_lib == $hold->pickup_lib
1175                                 } @good_copies
1176                         ];
1177
1178                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1179                         # $all_copies is now a list of copies not at the pickup library
1180
1181                         my $best = choose_nearest_copy($hold, $prox_list);
1182                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1183
1184                         if (!$best) {
1185                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1186
1187                                 my $max_loops = $actor->request(
1188                                         'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1189                                 )->gather(1);
1190
1191                                 if (defined($max_loops)) {
1192                                         my %circ_lib_map =  map { $_->circ_lib => 1 } @$all_copies;
1193                                         my $circ_lib_list = [keys %circ_lib_map];
1194         
1195                                         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1196         
1197                                         # Grab the "biggest" loop for this hold so far
1198                                         my $current_loop = $cstore->request(
1199                                                 'open-ils.cstore.json_query',
1200                                                 { distinct => 1,
1201                                                   select => { aufhmxl => ['max'] },
1202                                                   from => 'aufhmxl',
1203                                                   where => { hold => $hold->id}
1204                                                 }
1205                                         )->gather(1);
1206         
1207                                         $current_loop = $current_loop->{max} if ($current_loop);
1208                                         $current_loop ||= 1;
1209         
1210                                         my $exclude_list = $cstore->request(
1211                                                 'open-ils.cstore.json_query.atomic',
1212                                                 { distinct => 1,
1213                                                   select => { aufhol => [circ_lib] },
1214                                                   from => 'aufhol',
1215                                                   where => { hold => $hold->id}
1216                                                 }
1217                                         )->gather(1);
1218         
1219                                         my @keepers;
1220                                         if ($exclude_list && @$exclude_list) {
1221                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1222                                                 # check to see if we've used up every library in the potentials list
1223                                                 for my $l ( @$circ_lib_list ) {
1224                                                         my $keep = 1;
1225                                                         for my $ex ( @$exclude_list ) {
1226                                                                 if ($ex eq $l) {
1227                                                                         $keep = 0;
1228                                                                         last;
1229                                                                 }
1230                                                         }
1231                                                         push(@keepers, $l) if ($keep);
1232                                                 }
1233                                         } else {
1234                                                 @keepers = @$circ_lib_list;
1235                                         }
1236         
1237                                         $current_loop++ if (!@keepers);
1238         
1239                                         if ($max_loops && $max_loops <= $current_loop) {
1240                                                 # We haven't exceeded max_loops yet
1241                                                 my @keeper_copies;
1242                                                 for my $cp ( @$all_copies ) {
1243                                                         push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1244                                                 }
1245                                         } else {
1246                                                 # We have, and should remove potentials and cancel the hold
1247                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1248                                                 $_->delete for (@oldmaps);
1249
1250                                                 # cancel cause = un-targeted expiration
1251                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1252                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1253
1254                                                 # tell A/T the hold was cancelled
1255                                                 my $fm_hold = $hold->to_fieldmapper;
1256                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1257                                                 $ses->request('open-ils.trigger.event.autocreate', 
1258                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1259
1260                                                 die "OK\n";
1261                                         }
1262                                 }
1263
1264                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1265
1266                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1267
1268                                 $best = choose_nearest_copy($hold, $prox_list);
1269                         }
1270
1271                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1272                         if ($old_best) {
1273                                 # hold wasn't fulfilled, record the fact
1274                         
1275                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1276                                 action::unfulfilled_hold_list->create(
1277                                                 { hold => ''.$hold->id,
1278                                                   current_copy => ''.$old_best->id,
1279                                                   circ_lib => ''.$old_best->circ_lib,
1280                                                 });
1281                         }
1282
1283                         if ($best) {
1284                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1285                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1286                         } elsif (
1287                                 $old_best &&
1288                                 action::hold_request
1289                                         ->search_where(
1290                                                 { current_copy => $old_best->id,
1291                                                   fulfillment_time => undef,
1292                                                   cancel_time => undef,
1293                                                 }       
1294                                         )
1295                         ) {     
1296                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1297                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1298                         } else {
1299                                 $hold->update( { prev_check_time => 'now' } );
1300                                 $log->info( "\tThere were no targetable copies for the hold" );
1301                         }
1302
1303                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1304                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1305
1306                         push @successes,
1307                                 { hold => $hold->id,
1308                                   old_target => ($old_best ? $old_best->id : undef),
1309                                   eligible_copies => $copy_count,
1310                                   target => ($best ? $best->id : undef) };
1311
1312                 } otherwise {
1313                         my $e = shift;
1314                         if ($e !~ /^OK/o) {
1315                                 $log->error("Processing of hold failed:  $e");
1316                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1317                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1318                         }
1319                 };
1320         }
1321
1322         return \@successes;
1323 }
1324 __PACKAGE__->register_method(
1325         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1326         api_level       => 1,
1327         method          => 'new_hold_copy_targeter',
1328 );
1329
1330 sub reservation_targeter {
1331         my $self = shift;
1332         my $client = shift;
1333         my $one_reservation = shift;
1334
1335         local $OpenILS::Application::Storage::WRITE = 1;
1336
1337         my $reservations;
1338
1339         try {
1340                 if ($one_reservation) {
1341                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1342                         $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1343                 } else {
1344
1345                         # find all the reservations needing targeting
1346                         $reservations = [
1347                 booking::reservation->search_where(
1348                                         { current_resource => undef,
1349                                           cancel_time => undef,
1350                                           start_time => { '>' => 'now' }
1351                     },
1352                     { order_by => 'start_time' }
1353                 )
1354             ];
1355                 }
1356         } catch Error with {
1357                 my $e = shift;
1358                 die "Could not retrieve reservation requests:\n\n$e\n";
1359         };
1360
1361         my @successes = ();
1362         for my $bresv (@$reservations) {
1363                 try {
1364                         #start a transaction if needed
1365                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1366                                 $log->debug("Cleaning up after previous transaction\n");
1367                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1368                         }
1369                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1370                         $log->info("Processing reservation ".$bresv->id."...\n");
1371
1372                         #first, re-fetch the hold, to make sure it's not captured already
1373                         $bresv->remove_from_object_index();
1374                         $bresv = booking::reservation->retrieve( $bresv->id );
1375
1376                         die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1377
1378                         my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1379                         if (DateTime->compare($end_time, DateTime->now) < 0) {
1380
1381                                 # cancel cause = un-targeted expiration
1382                                 $bresv->update( { cancel_time => 'now' } ); 
1383                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1384
1385                                 # tell A/T the reservation was cancelled
1386                                 my $fm_bresv = $bresv->to_fieldmapper;
1387                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1388                                 $ses->request('open-ils.trigger.event.autocreate', 
1389                                         'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1390
1391                                 die "OK\n";
1392                         }
1393
1394                         my $possible_resources;
1395
1396                         # find all the potential resources
1397                         if (!$bresv->target_resource) {
1398                                 my $filter = { type => $bresv->target_resource_type };
1399                                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1400
1401                                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1402
1403                                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1404                                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1405                                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1406                         } else {
1407                                 $possible_resources = $bresv->target_resource;
1408                         }
1409
1410             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1411                         @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1412
1413
1414             my @good_resources = ();
1415             for my $res (@$all_resources) {
1416                 unless (isTrue($res->type->catalog_item)) {
1417                     push @good_resources, $res;
1418                     next;
1419                 }
1420
1421                 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1422
1423                 unless ($copy) {
1424                     push @good_resources, $res;
1425                     next;
1426                 }
1427
1428                 if ($copy->status->id == 0 || $copy->status->id == 7) {
1429                     push @good_resources, $res;
1430                     next;
1431                 }
1432
1433                 if ($copy->status->id == 1) {
1434                     my $circs = action::circulation->search_where(
1435                         {target_copy => $copy->id, checkin_time => undef },
1436                         { order_by => 'id DESC' }
1437                     );
1438
1439                     if (@$circs) {
1440                         my $due_date = $circs->[0]->due_date;
1441                                     $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1442                                     my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1443                         next if (DateTime->compare($start_time, $due_date) < 0);
1444                         push @good_resources, $res;
1445                     }
1446
1447                     next;
1448                 }
1449
1450                 push @good_resources, $res if (isTrue($copy->status->holdable));
1451             }
1452
1453                         # let 'em know we're still working
1454                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1455                         
1456                         # if we have no copies ...
1457                         if (!@good_resources) {
1458                                 $log->info("\tNo resources available for targeting at all!\n");
1459                                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1460
1461                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1462                                 die "OK\n";
1463                         }
1464
1465                         $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1466
1467                         my $prox_list = [];
1468                         $$prox_list[0] =
1469                         [
1470                                 grep {
1471                                         $_->owner == $bresv->pickup_lib
1472                                 } @good_resources
1473                         ];
1474
1475                         $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1476                         # $all_copies is now a list of copies not at the pickup library
1477
1478                         my $best = shift @good_resources;
1479                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1480
1481                         if (!$best) {
1482                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1483
1484                                 $prox_list =
1485                     map  { $_->[1] }
1486                     sort { $a->[0] <=> $b->[0] }
1487                     map  {
1488                         [   actor::org_unit_proximity->search_where(
1489                                 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1490                             )->[0]->prox,
1491                             $_
1492                         ]
1493                     } @$all_resources;
1494
1495                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1496
1497                                 $best = shift @$prox_list
1498                         }
1499
1500                         if ($best) {
1501                                 $bresv->update( { current_resource => ''.$best->id } );
1502                                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1503                         }
1504
1505                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1506                         $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1507
1508                         push @successes,
1509                                 { reservation => $bresv->id,
1510                                   current_resource => ($best ? $best->id : undef) };
1511
1512                 } otherwise {
1513                         my $e = shift;
1514                         if ($e !~ /^OK/o) {
1515                                 $log->error("Processing of bresv failed:  $e");
1516                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1517                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1518                         }
1519                 };
1520         }
1521
1522         return \@successes;
1523 }
1524 __PACKAGE__->register_method(
1525         api_name        => 'open-ils.storage.booking.reservation.resource_targeter',
1526         api_level       => 1,
1527         method          => 'reservation_targeter',
1528 );
1529
1530 my $locations;
1531 my $statuses;
1532 my %cache = (titles => {}, cns => {});
1533 sub hold_copy_targeter {
1534         my $self = shift;
1535         my $client = shift;
1536         my $check_expire = shift;
1537         my $one_hold = shift;
1538
1539         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1540         $self->{user_filter}->connect;
1541         $self->{client} = $client;
1542
1543         my $time = time;
1544         $check_expire ||= '12h';
1545         $check_expire = interval_to_seconds( $check_expire );
1546
1547         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1548         $year += 1900;
1549         $mon += 1;
1550         my $expire_threshold = sprintf(
1551                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1552                 $year, $mon, $mday, $hour, $min, $sec
1553         );
1554
1555
1556         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1557
1558         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1559
1560         my $holds;
1561
1562         %cache = (titles => {}, cns => {});
1563
1564         try {
1565                 if ($one_hold) {
1566                         $holds = [ action::hold_request->search(id => $one_hold) ];
1567                 } else {
1568                         $holds = [ action::hold_request->search_where(
1569                                                         { capture_time => undef,
1570                                                           prev_check_time => { '<=' => $expire_threshold },
1571                                                         },
1572                                                         { order_by => 'request_time,prev_check_time' } ) ];
1573                         push @$holds, action::hold_request->search_where(
1574                                                         { capture_time => undef,
1575                                                           prev_check_time => undef,
1576                                                         },
1577                                                         { order_by => 'request_time' } );
1578                 }
1579         } catch Error with {
1580                 my $e = shift;
1581                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1582         };
1583
1584         for my $hold (@$holds) {
1585                 try {
1586                         #action::hold_request->db_Main->begin_work;
1587                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1588                                 $client->respond("Cleaning up after previous transaction\n");
1589                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1590                         }
1591                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1592                         $client->respond("Processing hold ".$hold->id."...\n");
1593
1594                         my $copies;
1595
1596                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1597                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1598
1599                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1600                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1601                         
1602                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1603                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1604                         
1605                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1606
1607                         unless (ref $copies || !@$copies) {
1608                                 $client->respond("\tNo copies available for targeting at all!\n");
1609                         }
1610
1611                         my @good_copies;
1612                         for my $c (@$copies) {
1613                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1614                                 push @good_copies, $c if ($c);
1615                         }
1616
1617                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1618
1619                         my $old_best = $hold->current_copy;
1620                         $hold->update({ current_copy => undef });
1621         
1622                         if (!scalar(@good_copies)) {
1623                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1624                                 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1625                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1626                                         push @good_copies, asset::copy->retrieve( $old_best );
1627                                 } else {
1628                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1629                                         next;
1630                                 }
1631                         }
1632
1633                         my $prox_list;
1634                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1635                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1636
1637                         my $best = choose_nearest_copy($hold, $prox_list);
1638
1639                         if (!$best) {
1640                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1641                                 $best = choose_nearest_copy($hold, $prox_list);
1642                         }
1643
1644                         if ($old_best) {
1645                                 # hold wasn't fulfilled, record the fact
1646                         
1647                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1648                                 action::unfulfilled_hold_list->create(
1649                                                 { hold => ''.$hold->id,
1650                                                   current_copy => ''.$old_best->id,
1651                                                   circ_lib => ''.$old_best->circ_lib,
1652                                                 });
1653                         }
1654
1655                         if ($best) {
1656                                 $hold->update( { current_copy => ''.$best->id } );
1657                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1658                         }
1659
1660                         $hold->update( { prev_check_time => 'now' } );
1661                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1662
1663                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1664                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1665
1666                         #action::hold_request->dbi_commit;
1667
1668                 } otherwise {
1669                         my $e = shift;
1670                         $log->error("Processing of hold failed:  $e");
1671                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1672                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1673                         #action::hold_request->dbi_rollback;
1674                 };
1675         }
1676
1677         $self->{user_filter}->disconnect;
1678         $self->{user_filter}->finish;
1679         delete $$self{user_filter};
1680         return undef;
1681 }
1682 #__PACKAGE__->register_method(
1683 #       api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1684 #       api_level       => 0,
1685 #       stream          => 1,
1686 #       method          => 'hold_copy_targeter',
1687 #);
1688
1689
1690 sub copy_hold_capture {
1691         my $self = shift;
1692         my $hold = shift;
1693         my $cps = shift;
1694
1695         if (!defined($cps)) {
1696                 try {
1697                         $cps = [ asset::copy->search( id => $hold->target ) ];
1698                 } catch Error with {
1699                         my $e = shift;
1700                         die "Could not retrieve initial volume list:\n\n$e\n";
1701                 };
1702         }
1703
1704         my @copies = grep { $_->holdable } @$cps;
1705
1706         for (my $i = 0; $i < @$cps; $i++) {
1707                 next unless $$cps[$i];
1708                 
1709                 my $cn = $cache{cns}{$copies[$i]->call_number};
1710                 my $rec = $cache{titles}{$cn->record};
1711                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1712                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1713                 $copies[$i] = undef if (
1714                         !$copies[$i] ||
1715                         !$self->{user_filter}->request(
1716                                 'open-ils.circ.permit_hold',
1717                                 $hold->to_fieldmapper, do {
1718                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1719                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1720                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1721                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1722                                         $cp_fm;
1723                                 },
1724                                 { title => $rec->to_fieldmapper,
1725                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1726                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1727                                 })->gather(1)
1728                 );
1729                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1730         }
1731
1732         @copies = grep { $_ } @copies;
1733
1734         my $count = @copies;
1735
1736         return unless ($count);
1737         
1738         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1739         
1740         my @maps;
1741         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1742         for my $c (@copies) {
1743                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1744         }
1745         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1746
1747         return \@copies;
1748 }
1749
1750
1751 sub choose_nearest_copy {
1752         my $hold = shift;
1753         my $prox_list = shift;
1754
1755         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1756                 next unless (ref $$prox_list[$p]);
1757
1758                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1759                 next unless (@capturable);
1760
1761                 my $rand = int(rand(scalar(@capturable)));
1762                 while (my ($c) = splice(@capturable,$rand)) {
1763                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1764                                 { title => $c->call_number->record->to_fieldmapper,
1765                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1766                                   patron => $hold->usr->to_fieldmapper,
1767                                   copy => $c->to_fieldmapper,
1768                                   requestor => $hold->requestor->to_fieldmapper,
1769                                   request_lib => $hold->request_lib->to_fieldmapper,
1770                                    pickup_lib => $hold->pickup_lib->id,
1771                                 }
1772                         ));
1773
1774                         last unless(@capturable);
1775                         $rand = int(rand(scalar(@capturable)));
1776                 }
1777         }
1778 }
1779
1780 sub create_prox_list {
1781         my $self = shift;
1782         my $lib = shift;
1783         my $copies = shift;
1784
1785         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1786
1787         my @prox_list;
1788         for my $cp (@$copies) {
1789                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1790                 next unless (defined($prox));
1791
1792                 # Fetch the weighting value for hold targeting, defaulting to 1
1793                 $self->{target_weight}{$lib} ||= $actor->request(
1794                         'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1795                 )->gather(1) || 1;
1796
1797                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1798                 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1799                         push @{$prox_list[$prox]}, $cp;
1800                 }
1801         }
1802         return \@prox_list;
1803 }
1804
1805 sub volume_hold_capture {
1806         my $self = shift;
1807         my $hold = shift;
1808         my $vols = shift;
1809
1810         if (!defined($vols)) {
1811                 try {
1812                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1813                         $cache{cns}{$_->id} = $_ for (@$vols);
1814                 } catch Error with {
1815                         my $e = shift;
1816                         die "Could not retrieve initial volume list:\n\n$e\n";
1817                 };
1818         }
1819
1820         my @v_ids = map { $_->id } @$vols;
1821
1822         my $cp_list;
1823         try {
1824                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1825         
1826         } catch Error with {
1827                 my $e = shift;
1828                 warn "Could not retrieve copy list:\n\n$e\n";
1829         };
1830
1831         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1832 }
1833
1834 sub title_hold_capture {
1835         my $self = shift;
1836         my $hold = shift;
1837         my $titles = shift;
1838
1839         if (!defined($titles)) {
1840                 try {
1841                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1842                         $cache{titles}{$_->id} = $_ for (@$titles);
1843                 } catch Error with {
1844                         my $e = shift;
1845                         die "Could not retrieve initial title list:\n\n$e\n";
1846                 };
1847         }
1848
1849         my @t_ids = map { $_->id } @$titles;
1850         my $cn_list;
1851         try {
1852                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1853         
1854         } catch Error with {
1855                 my $e = shift;
1856                 warn "Could not retrieve volume list:\n\n$e\n";
1857         };
1858
1859         $cache{cns}{$_->id} = $_ for (@$cn_list);
1860
1861         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1862 }
1863
1864 sub metarecord_hold_capture {
1865         my $self = shift;
1866         my $hold = shift;
1867
1868         my $titles;
1869         try {
1870                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1871         
1872         } catch Error with {
1873                 my $e = shift;
1874                 die "Could not retrieve initial title list:\n\n$e\n";
1875         };
1876
1877         try {
1878                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1879
1880                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1881         
1882         } catch Error with {
1883                 my $e = shift;
1884                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1885         };
1886
1887
1888         $cache{titles}{$_->id} = $_ for (@$titles);
1889         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1890 }
1891
1892 1;