]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
Address long-standing typo: clense_ISO8601, matching change to OpenSRF-trunk.
[working/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         if ($ctype eq 'reservation') {
677             $due_date_method = 'end_time';
678             $target_copy_method = 'current_resource';
679             $circ_lib_method = 'pickup_lib';
680             $recurring_fine_method = 'fine_amount';
681             next unless ($c->fine_interval);
682         }
683
684                 try {
685                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
686                                 $log->debug("Cleaning up after previous transaction\n");
687                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
688                         }
689                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
690                         $log->info("Processing circ ".$c->id."...\n");
691
692
693                         my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
694         
695                         my $due = $due_dt->epoch;
696                         my $now = time;
697
698                         my $fine_interval = $c->fine_interval;
699             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
700                         $fine_interval = interval_to_seconds( $fine_interval );
701         
702                         if ( $fine_interval >= interval_to_seconds('1d') ) {    
703                                 my $tz_offset_s = 0;
704                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
705                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
706                                 }
707         
708                                 $due -= ($due % $fine_interval) + $tz_offset_s;
709                                 $now -= ($now % $fine_interval) + $tz_offset_s;
710                         }
711         
712                         $client->respond(
713                                 "ARG! Overdue $ctype ".$c->id.
714                                 " for item ".$c->$target_copy_method.
715                                 " (user ".$c->usr.").\n".
716                                 "\tItem was due on or before: ".localtime($due)."\n");
717         
718                         my @fines = money::billing->search_where(
719                                 { xact => $c->id,
720                                   btype => 1,
721                                   billing_ts => { '>' => $c->$due_date_method } },
722                                 { order_by => 'billing_ts DESC'}
723                         );
724
725                         my $f_idx = 0;
726                         my $fine = $fines[$f_idx] if (@fines);
727                         if ($overbill) {
728                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
729                         }
730
731                         my $current_fine_total = 0;
732                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
733         
734                         my $last_fine;
735                         if ($fine) {
736                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
737                                 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
738                         } else {
739                                 $log->info( "Potential first billing for circ ".$c->id );
740                                 $last_fine = $due;
741
742                                 if (0) {
743                                         if (my $h = $hoo{$c->$circ_lib_method}) { 
744
745                                                 $log->info( "Circ lib has an hours-of-operation entry" );
746                                                 # find the day after the due date...
747                                                 $due_dt = $due_dt->add( days => 1 );
748
749                                                 # get the day of the week for that day...
750                                                 my $dow = $due_dt->day_of_week_0;
751                                                 my $dow_open = "dow_${dow}_open";
752                                                 my $dow_close = "dow_${dow}_close";
753
754                                                 my $count = 0;
755                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
756                                                         # if the circ lib is closed, add a day to the grace period...
757
758                                                         $grace++;
759                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
760                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
761
762                                                         $due_dt = $due_dt->add( days => 1 );
763                                                         $dow = $due_dt->day_of_week_0;
764                                                         $dow_open = "dow_${dow}_open";
765                                                         $dow_close = "dow_${dow}_close";
766
767                                                         $count++;
768
769                                                         # and check for up to a week
770                                                         last if ($count > 6);
771                                                 }
772                                         }
773                                 }
774                         }
775
776
777                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
778                         if ($pending_fine_count < 1 + $grace) {
779                                 $client->respond( "\tNo fines to create.  " );
780                                 if ($grace && $now < $due + $fine_interval * $grace) {
781                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
782                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
783                                 } else {
784                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
785                                 }
786                                 next;
787                         }
788         
789                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
790
791                         my $recurring_fine = int($c->$recurring_fine_method * 100);
792                         my $max_fine = int($c->max_fine * 100);
793
794                         my ($latest_billing_ts, $latest_amount) = ('',0);
795                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
796         
797                                 if ($current_fine_total >= $max_fine) {
798                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
799                                         $client->respond(
800                                                 "\tMaximum fine level of ".$c->max_fine.
801                                                 " reached for this $ctype.\n".
802                                                 "\tNo more fines will be generated.\n" );
803                                         last;
804                                 }
805                                 
806                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
807
808                                 my $dow = $billing_ts->day_of_week_0();
809                                 my $dow_open = "dow_${dow}_open";
810                                 my $dow_close = "dow_${dow}_close";
811
812                                 if (my $h = $hoo{$c->$circ_lib_method}) {
813                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
814                                 }
815
816                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
817                                 my @cl = actor::org_unit::closed_date->search_where(
818                                                 { close_start   => { '<=' => $timestamptz },
819                                                   close_end     => { '>=' => $timestamptz },
820                                                   org_unit      => $c->$circ_lib_method }
821                                 );
822                                 next if (@cl);
823         
824                                 $current_fine_total += $recurring_fine;
825                                 $latest_amount += $recurring_fine;
826                                 $latest_billing_ts = $timestamptz;
827
828                                 money::billing->create(
829                                         { xact          => ''.$c->id,
830                                           note          => "System Generated Overdue Fine",
831                                           billing_type  => "Overdue materials",
832                                           btype         => 1,
833                                           amount        => sprintf('%0.2f', $recurring_fine/100),
834                                           billing_ts    => $timestamptz,
835                                         }
836                                 );
837
838                         }
839
840                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
841                                 if ($latest_billing_ts and $latest_amount);
842
843                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
844
845                         if(1) { 
846
847                 # Caluclate penalties inline
848                                 OpenILS::Utils::Penalty->calculate_penalties(
849                                         undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
850
851                         } else {
852
853                 # Calculate penalties with an aysnc call to the penalty server.  This approach
854                 # may lead to duplicate penalties since multiple penalty processes for a
855                 # given user may be running at the same time. Leave this here for reference 
856                 # in case we later find that asyc calls are needed in some environments.
857                                 $penalty->request(
858                                     'open-ils.penalty.patron_penalty.calculate',
859                                     { patronid  => ''.$c->usr,
860                                     context_org => ''.$c->$circ_lib_method,
861                                     update      => 1,
862                                     background  => 1,
863                                     }
864                             )->gather(1);
865                         }
866
867                 } catch Error with {
868                         my $e = shift;
869                         $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
870                         $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
871                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
872                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
873                 };
874         }
875 }
876 __PACKAGE__->register_method(
877         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
878         api_level       => 1,
879         stream          => 1,
880         method          => 'generate_fines',
881 );
882
883
884
885 sub new_hold_copy_targeter {
886         my $self = shift;
887         my $client = shift;
888         my $check_expire = shift;
889         my $one_hold = shift;
890
891         local $OpenILS::Application::Storage::WRITE = 1;
892
893         $self->{target_weight} = {};
894
895         my $holds;
896
897         try {
898                 if ($one_hold) {
899                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
900                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
901                 } elsif ( $check_expire ) {
902
903                         # what's the retarget time threashold?
904                         my $time = time;
905                         $check_expire ||= '12h';
906                         $check_expire = interval_to_seconds( $check_expire );
907
908                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
909                         $year += 1900;
910                         $mon += 1;
911                         my $expire_threshold = sprintf(
912                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
913                                 $year, $mon, $mday, $hour, $min, $sec
914                         );
915
916                         # find all the holds holds needing retargeting
917                         $holds = [ action::hold_request->search_where(
918                                                         { capture_time => undef,
919                                                           fulfillment_time => undef,
920                                                           cancel_time => undef,
921                                                           frozen => 'f',
922                                                           prev_check_time => { '<=' => $expire_threshold },
923                                                         },
924                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
925
926                         # find all the holds holds needing first time targeting
927                         push @$holds, action::hold_request->search(
928                                                         capture_time => undef,
929                                                         fulfillment_time => undef,
930                                                         prev_check_time => undef,
931                                                         frozen => 'f',
932                                                         cancel_time => undef,
933                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
934                 } else {
935
936                         # find all the holds holds needing first time targeting ONLY
937                         $holds = [ action::hold_request->search(
938                                                         capture_time => undef,
939                                                         fulfillment_time => undef,
940                                                         prev_check_time => undef,
941                                                         cancel_time => undef,
942                                                         frozen => 'f',
943                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
944                 }
945         } catch Error with {
946                 my $e = shift;
947                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
948         };
949
950         my @closed = actor::org_unit::closed_date->search_where(
951                 { close_start => { '<=', 'now' },
952                   close_end => { '>=', 'now' } }
953         );
954
955     if ($check_expire) {
956
957         # $check_expire, if it exists, was already converted to seconds
958         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
959             $year += 1900;
960         $mon += 1;
961
962             my $next_check_time = sprintf(
963                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
964                 $year, $mon, $mday, $hour, $min, $sec
965         );
966
967
968             my @closed_at_next = actor::org_unit::closed_date->search_where(
969                     { close_start => { '<=', $next_check_time },
970                   close_end => { '>=', $next_check_time } }
971             );
972
973         my @new_closed;
974         for my $c_at_n (@closed_at_next) {
975             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
976                 push @new_closed, $c_at_n;
977             }
978         }
979         @closed = @new_closed;
980     }
981
982         my @successes;
983         my $actor = OpenSRF::AppSession->create('open-ils.actor');
984
985         for my $hold (@$holds) {
986                 try {
987                         #start a transaction if needed
988                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
989                                 $log->debug("Cleaning up after previous transaction\n");
990                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
991                         }
992                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
993                         $log->info("Processing hold ".$hold->id."...\n");
994
995                         #first, re-fetch the hold, to make sure it's not captured already
996                         $hold->remove_from_object_index();
997                         $hold = action::hold_request->retrieve( $hold->id );
998
999                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1000
1001                         # remove old auto-targeting maps
1002                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1003                         $_->delete for (@oldmaps);
1004
1005                         if ($hold->expire_time) {
1006                                 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1007                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1008
1009                                         # cancel cause = un-targeted expiration
1010                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1011                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1012
1013                                         # tell A/T the hold was cancelled
1014                                         my $fm_hold = $hold->to_fieldmapper;
1015                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1016                                         $ses->request('open-ils.trigger.event.autocreate', 
1017                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1018
1019                                         die "OK\n";
1020                                 }
1021                         }
1022
1023                         my $all_copies = [];
1024
1025                         # find filters for MR holds
1026                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1027
1028                         # find all the potential copies
1029                         if ($hold->hold_type eq 'M') {
1030                                 for my $r ( map
1031                                                 {$_->record}
1032                                                 metabib::record_descriptor
1033                                                         ->search(
1034                                                                 record => [
1035                                                                         map {
1036                                                                                 isTrue($_->deleted) ?  () : ($_->id)
1037                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
1038                                                                 ],
1039                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
1040                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
1041                                                                 ( $lang    ? (item_lang => $lang)                : () ),
1042                                                         )
1043                                 ) {
1044                                         my ($rtree) = $self
1045                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1046                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1047
1048                                         for my $cn ( @{ $rtree->call_numbers } ) {
1049                                                 push @$all_copies,
1050                                                         asset::copy->search_where(
1051                                                                 { id => [map {$_->id} @{ $cn->copies }],
1052                                                                   deleted => 'f' }
1053                                                         ) if ($cn && @{ $cn->copies });
1054                                         }
1055                                 }
1056                         } elsif ($hold->hold_type eq 'T') {
1057                                 my ($rtree) = $self
1058                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1059                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1060
1061                                 unless ($rtree) {
1062                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1063                                         die "OK\n";
1064                                 }
1065
1066                                 for my $cn ( @{ $rtree->call_numbers } ) {
1067                                         push @$all_copies,
1068                                                 asset::copy->search_where(
1069                                                         { id => [map {$_->id} @{ $cn->copies }],
1070                                                           deleted => 'f' }
1071                                                 ) if ($cn && @{ $cn->copies });
1072                                 }
1073                         } elsif ($hold->hold_type eq 'V') {
1074                                 my ($vtree) = $self
1075                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1076                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1077
1078                                 push @$all_copies,
1079                                         asset::copy->search_where(
1080                                                 { id => [map {$_->id} @{ $vtree->copies }],
1081                                                   deleted => 'f' }
1082                                         ) if ($vtree && @{ $vtree->copies });
1083                                         
1084                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1085                                 my $_cp = asset::copy->retrieve($hold->target);
1086                                 push @$all_copies, $_cp if $_cp;
1087                         }
1088
1089                         # trim unholdables
1090                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1091                                                 isTrue($_->location->holdable) && 
1092                                                 isTrue($_->holdable) &&
1093                                                 !isTrue($_->deleted) &&
1094                                                 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1095                                         } @$all_copies;
1096
1097                         # let 'em know we're still working
1098                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1099                         
1100                         # if we have no copies ...
1101                         if (!ref $all_copies || !@$all_copies) {
1102                                 $log->info("\tNo copies available for targeting at all!\n");
1103                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1104
1105                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1106                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1107                                 die "OK\n";
1108                         }
1109
1110                         my $copy_count = @$all_copies;
1111
1112                         # map the potentials, so that we can pick up checkins
1113                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1114                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1115                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1116                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1117
1118                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1119
1120                         my @good_copies;
1121                         for my $c (@$all_copies) {
1122                                 # current target
1123                                 next if ($c->id eq $hold->current_copy);
1124
1125                                 # circ lib is closed
1126                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1127
1128                                 # target of another hold
1129                                 next if (action::hold_request
1130                                                 ->search_where(
1131                                                         { current_copy => $c->id,
1132                                                           fulfillment_time => undef,
1133                                                           cancel_time => undef,
1134                                                         }
1135                                                 )
1136                                 );
1137
1138                                 # we passed all three, keep it
1139                                 push @good_copies, $c if ($c);
1140                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1141                         }
1142
1143                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1144
1145                         my $old_best = $hold->current_copy;
1146                         $hold->update({ current_copy => undef }) if ($old_best);
1147         
1148                         if (!scalar(@good_copies)) {
1149                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1150                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1151                                         # the old copy is still available
1152                                         $log->debug("\tPushing current_copy back onto the targeting list");
1153                                         push @good_copies, $old_best;
1154                                 } else {
1155                                         # oops, old copy is not available
1156                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1157                                         $hold->update( { prev_check_time => 'today' } );
1158                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1159                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1160                                         die "OK\n";
1161                                 }
1162                         }
1163
1164                         my $prox_list = [];
1165                         $$prox_list[0] =
1166                         [
1167                                 grep {
1168                                         $_->circ_lib == $hold->pickup_lib
1169                                 } @good_copies
1170                         ];
1171
1172                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1173                         # $all_copies is now a list of copies not at the pickup library
1174
1175                         my $best = choose_nearest_copy($hold, $prox_list);
1176                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1177
1178                         if (!$best) {
1179                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1180
1181                                 my $max_loops = $actor->request(
1182                                         'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1183                                 )->gather(1);
1184
1185                                 if (defined($max_loops)) {
1186                                         my %circ_lib_map =  map { $_->circ_lib => 1 } @$all_copies;
1187                                         my $circ_lib_list = [keys %circ_lib_map];
1188         
1189                                         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1190         
1191                                         # Grab the "biggest" loop for this hold so far
1192                                         my $current_loop = $cstore->request(
1193                                                 'open-ils.cstore.json_query',
1194                                                 { distinct => 1,
1195                                                   select => { aufhmxl => ['max'] },
1196                                                   from => 'aufhmxl',
1197                                                   where => { hold => $hold->id}
1198                                                 }
1199                                         )->gather(1);
1200         
1201                                         $current_loop = $current_loop->{max} if ($current_loop);
1202                                         $current_loop ||= 1;
1203         
1204                                         my $exclude_list = $cstore->request(
1205                                                 'open-ils.cstore.json_query.atomic',
1206                                                 { distinct => 1,
1207                                                   select => { aufhol => [circ_lib] },
1208                                                   from => 'aufhol',
1209                                                   where => { hold => $hold->id}
1210                                                 }
1211                                         )->gather(1);
1212         
1213                                         my @keepers;
1214                                         if ($exclude_list && @$exclude_list) {
1215                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1216                                                 # check to see if we've used up every library in the potentials list
1217                                                 for my $l ( @$circ_lib_list ) {
1218                                                         my $keep = 1;
1219                                                         for my $ex ( @$exclude_list ) {
1220                                                                 if ($ex eq $l) {
1221                                                                         $keep = 0;
1222                                                                         last;
1223                                                                 }
1224                                                         }
1225                                                         push(@keepers, $l) if ($keep);
1226                                                 }
1227                                         } else {
1228                                                 @keepers = @$circ_lib_list;
1229                                         }
1230         
1231                                         $current_loop++ if (!@keepers);
1232         
1233                                         if ($max_loops && $max_loops <= $current_loop) {
1234                                                 # We haven't exceeded max_loops yet
1235                                                 my @keeper_copies;
1236                                                 for my $cp ( @$all_copies ) {
1237                                                         push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1238                                                 }
1239                                         } else {
1240                                                 # We have, and should remove potentials and cancel the hold
1241                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1242                                                 $_->delete for (@oldmaps);
1243
1244                                                 # cancel cause = un-targeted expiration
1245                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1246                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1247
1248                                                 # tell A/T the hold was cancelled
1249                                                 my $fm_hold = $hold->to_fieldmapper;
1250                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1251                                                 $ses->request('open-ils.trigger.event.autocreate', 
1252                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1253
1254                                                 die "OK\n";
1255                                         }
1256                                 }
1257
1258                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1259
1260                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1261
1262                                 $best = choose_nearest_copy($hold, $prox_list);
1263                         }
1264
1265                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1266                         if ($old_best) {
1267                                 # hold wasn't fulfilled, record the fact
1268                         
1269                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1270                                 action::unfulfilled_hold_list->create(
1271                                                 { hold => ''.$hold->id,
1272                                                   current_copy => ''.$old_best->id,
1273                                                   circ_lib => ''.$old_best->circ_lib,
1274                                                 });
1275                         }
1276
1277                         if ($best) {
1278                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1279                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1280                         } elsif (
1281                                 $old_best &&
1282                                 action::hold_request
1283                                         ->search_where(
1284                                                 { current_copy => $old_best->id,
1285                                                   fulfillment_time => undef,
1286                                                   cancel_time => undef,
1287                                                 }       
1288                                         )
1289                         ) {     
1290                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1291                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1292                         } else {
1293                                 $hold->update( { prev_check_time => 'now' } );
1294                                 $log->info( "\tThere were no targetable copies for the hold" );
1295                         }
1296
1297                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1298                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1299
1300                         push @successes,
1301                                 { hold => $hold->id,
1302                                   old_target => ($old_best ? $old_best->id : undef),
1303                                   eligible_copies => $copy_count,
1304                                   target => ($best ? $best->id : undef) };
1305
1306                 } otherwise {
1307                         my $e = shift;
1308                         if ($e !~ /^OK/o) {
1309                                 $log->error("Processing of hold failed:  $e");
1310                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1311                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1312                         }
1313                 };
1314         }
1315
1316         return \@successes;
1317 }
1318 __PACKAGE__->register_method(
1319         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1320         api_level       => 1,
1321         method          => 'new_hold_copy_targeter',
1322 );
1323
1324 sub reservation_targeter {
1325         my $self = shift;
1326         my $client = shift;
1327         my $one_reservation = shift;
1328
1329         local $OpenILS::Application::Storage::WRITE = 1;
1330
1331         my $reservations;
1332
1333         try {
1334                 if ($one_reservation) {
1335                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1336                         $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1337                 } else {
1338
1339                         # find all the reservations needing targeting
1340                         $reservations = [
1341                 booking::reservation->search_where(
1342                                         { current_resource => undef,
1343                                           cancel_time => undef,
1344                                           start_time => { '>' => 'now' }
1345                     },
1346                     { order_by => 'start_time' }
1347                 )
1348             ];
1349                 }
1350         } catch Error with {
1351                 my $e = shift;
1352                 die "Could not retrieve reservation requests:\n\n$e\n";
1353         };
1354
1355         my @successes = ();
1356         for my $bresv (@$reservations) {
1357                 try {
1358                         #start a transaction if needed
1359                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1360                                 $log->debug("Cleaning up after previous transaction\n");
1361                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1362                         }
1363                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1364                         $log->info("Processing reservation ".$bresv->id."...\n");
1365
1366                         #first, re-fetch the hold, to make sure it's not captured already
1367                         $bresv->remove_from_object_index();
1368                         $bresv = booking::reservation->retrieve( $bresv->id );
1369
1370                         die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1371
1372                         my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1373                         if (DateTime->compare($end_time, DateTime->now) < 0) {
1374
1375                                 # cancel cause = un-targeted expiration
1376                                 $bresv->update( { cancel_time => 'now' } ); 
1377                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1378
1379                                 # tell A/T the reservation was cancelled
1380                                 my $fm_bresv = $bresv->to_fieldmapper;
1381                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1382                                 $ses->request('open-ils.trigger.event.autocreate', 
1383                                         'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1384
1385                                 die "OK\n";
1386                         }
1387
1388                         my $possible_resources;
1389
1390                         # find all the potential resources
1391                         if (!$bresv->target_resource) {
1392                                 my $filter = { type => $bresv->target_resource_type };
1393                                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1394
1395                                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1396
1397                                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1398                                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1399                                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1400                         } else {
1401                                 $possible_resources = $bresv->target_resource;
1402                         }
1403
1404             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1405                         @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1406
1407
1408             my @good_resources = ();
1409             for my $res (@$all_resources) {
1410                 unless (isTrue($res->type->catalog_item)) {
1411                     push @good_resources, $res;
1412                     next;
1413                 }
1414
1415                 my $copy = [ asset::copy->search( deleted => f, barcode => $res->barcode )]->[0];
1416
1417                 unless ($copy) {
1418                     push @good_resources, $res;
1419                     next;
1420                 }
1421
1422                 if ($copy->status->id == 0 || $copy->status->id == 7) {
1423                     push @good_resources, $res;
1424                     next;
1425                 }
1426
1427                 if ($copy->status->id == 1) {
1428                     my $circs = action::circulation->search_where(
1429                         {target_copy => $copy->id, checkin_time => undef },
1430                         { order_by => 'id DESC' }
1431                     );
1432
1433                     if (@$circs) {
1434                         my $due_date = $circs->[0]->due_date;
1435                                     $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1436                                     my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1437                         next if (DateTime->compare($start_time, $due_date) < 0);
1438                         push @good_resources, $res;
1439                     }
1440
1441                     next;
1442                 }
1443
1444                 push @good_resources, $res if (isTrue($copy->status->holdable));
1445             }
1446
1447                         # let 'em know we're still working
1448                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1449                         
1450                         # if we have no copies ...
1451                         if (!@good_resources) {
1452                                 $log->info("\tNo resources available for targeting at all!\n");
1453                                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES' };
1454
1455                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1456                                 die "OK\n";
1457                         }
1458
1459                         $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1460
1461                         my $prox_list = [];
1462                         $$prox_list[0] =
1463                         [
1464                                 grep {
1465                                         $_->owner == $bresv->pickup_lib
1466                                 } @good_resources
1467                         ];
1468
1469                         $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1470                         # $all_copies is now a list of copies not at the pickup library
1471
1472                         my $best = shift @good_resources;
1473                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1474
1475                         if (!$best) {
1476                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1477
1478                                 $prox_list =
1479                     map  { $_->[1] }
1480                     sort { $a->[0] <=> $b->[0] }
1481                     map  {
1482                         [   actor::org_unit_proximity->search_where(
1483                                 { from_org => $bresv->pickup_lib.'', to_org => $_=>owner.'' }
1484                             )->[0]->prox,
1485                             $_
1486                         ]
1487                     } @$all_resources;
1488
1489                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1490
1491                                 $best = shift @$prox_list
1492                         }
1493
1494                         if ($best) {
1495                                 $bresv->update( { current_resource => ''.$best->id } );
1496                                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1497                         }
1498
1499                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1500                         $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1501
1502                         push @successes,
1503                                 { reservation => $bresv->id,
1504                                   current_resource => ($best ? $best->id : undef) };
1505
1506                 } otherwise {
1507                         my $e = shift;
1508                         if ($e !~ /^OK/o) {
1509                                 $log->error("Processing of bresv failed:  $e");
1510                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1511                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1512                         }
1513                 };
1514         }
1515
1516         return \@successes;
1517 }
1518 __PACKAGE__->register_method(
1519         api_name        => 'open-ils.storage.booking.reservation.resource_targeter',
1520         api_level       => 1,
1521         method          => 'reservation_targeter',
1522 );
1523
1524 my $locations;
1525 my $statuses;
1526 my %cache = (titles => {}, cns => {});
1527 sub hold_copy_targeter {
1528         my $self = shift;
1529         my $client = shift;
1530         my $check_expire = shift;
1531         my $one_hold = shift;
1532
1533         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1534         $self->{user_filter}->connect;
1535         $self->{client} = $client;
1536
1537         my $time = time;
1538         $check_expire ||= '12h';
1539         $check_expire = interval_to_seconds( $check_expire );
1540
1541         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1542         $year += 1900;
1543         $mon += 1;
1544         my $expire_threshold = sprintf(
1545                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1546                 $year, $mon, $mday, $hour, $min, $sec
1547         );
1548
1549
1550         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1551
1552         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1553
1554         my $holds;
1555
1556         %cache = (titles => {}, cns => {});
1557
1558         try {
1559                 if ($one_hold) {
1560                         $holds = [ action::hold_request->search(id => $one_hold) ];
1561                 } else {
1562                         $holds = [ action::hold_request->search_where(
1563                                                         { capture_time => undef,
1564                                                           prev_check_time => { '<=' => $expire_threshold },
1565                                                         },
1566                                                         { order_by => 'request_time,prev_check_time' } ) ];
1567                         push @$holds, action::hold_request->search_where(
1568                                                         { capture_time => undef,
1569                                                           prev_check_time => undef,
1570                                                         },
1571                                                         { order_by => 'request_time' } );
1572                 }
1573         } catch Error with {
1574                 my $e = shift;
1575                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1576         };
1577
1578         for my $hold (@$holds) {
1579                 try {
1580                         #action::hold_request->db_Main->begin_work;
1581                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1582                                 $client->respond("Cleaning up after previous transaction\n");
1583                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1584                         }
1585                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1586                         $client->respond("Processing hold ".$hold->id."...\n");
1587
1588                         my $copies;
1589
1590                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1591                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1592
1593                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1594                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1595                         
1596                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1597                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1598                         
1599                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1600
1601                         unless (ref $copies || !@$copies) {
1602                                 $client->respond("\tNo copies available for targeting at all!\n");
1603                         }
1604
1605                         my @good_copies;
1606                         for my $c (@$copies) {
1607                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1608                                 push @good_copies, $c if ($c);
1609                         }
1610
1611                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1612
1613                         my $old_best = $hold->current_copy;
1614                         $hold->update({ current_copy => undef });
1615         
1616                         if (!scalar(@good_copies)) {
1617                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1618                                 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1619                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1620                                         push @good_copies, asset::copy->retrieve( $old_best );
1621                                 } else {
1622                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1623                                         next;
1624                                 }
1625                         }
1626
1627                         my $prox_list;
1628                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1629                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1630
1631                         my $best = choose_nearest_copy($hold, $prox_list);
1632
1633                         if (!$best) {
1634                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1635                                 $best = choose_nearest_copy($hold, $prox_list);
1636                         }
1637
1638                         if ($old_best) {
1639                                 # hold wasn't fulfilled, record the fact
1640                         
1641                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1642                                 action::unfulfilled_hold_list->create(
1643                                                 { hold => ''.$hold->id,
1644                                                   current_copy => ''.$old_best->id,
1645                                                   circ_lib => ''.$old_best->circ_lib,
1646                                                 });
1647                         }
1648
1649                         if ($best) {
1650                                 $hold->update( { current_copy => ''.$best->id } );
1651                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1652                         }
1653
1654                         $hold->update( { prev_check_time => 'now' } );
1655                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1656
1657                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1658                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1659
1660                         #action::hold_request->dbi_commit;
1661
1662                 } otherwise {
1663                         my $e = shift;
1664                         $log->error("Processing of hold failed:  $e");
1665                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1666                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1667                         #action::hold_request->dbi_rollback;
1668                 };
1669         }
1670
1671         $self->{user_filter}->disconnect;
1672         $self->{user_filter}->finish;
1673         delete $$self{user_filter};
1674         return undef;
1675 }
1676 #__PACKAGE__->register_method(
1677 #       api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1678 #       api_level       => 0,
1679 #       stream          => 1,
1680 #       method          => 'hold_copy_targeter',
1681 #);
1682
1683
1684 sub copy_hold_capture {
1685         my $self = shift;
1686         my $hold = shift;
1687         my $cps = shift;
1688
1689         if (!defined($cps)) {
1690                 try {
1691                         $cps = [ asset::copy->search( id => $hold->target ) ];
1692                 } catch Error with {
1693                         my $e = shift;
1694                         die "Could not retrieve initial volume list:\n\n$e\n";
1695                 };
1696         }
1697
1698         my @copies = grep { $_->holdable } @$cps;
1699
1700         for (my $i = 0; $i < @$cps; $i++) {
1701                 next unless $$cps[$i];
1702                 
1703                 my $cn = $cache{cns}{$copies[$i]->call_number};
1704                 my $rec = $cache{titles}{$cn->record};
1705                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1706                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1707                 $copies[$i] = undef if (
1708                         !$copies[$i] ||
1709                         !$self->{user_filter}->request(
1710                                 'open-ils.circ.permit_hold',
1711                                 $hold->to_fieldmapper, do {
1712                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1713                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1714                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1715                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1716                                         $cp_fm;
1717                                 },
1718                                 { title => $rec->to_fieldmapper,
1719                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1720                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1721                                 })->gather(1)
1722                 );
1723                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1724         }
1725
1726         @copies = grep { $_ } @copies;
1727
1728         my $count = @copies;
1729
1730         return unless ($count);
1731         
1732         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1733         
1734         my @maps;
1735         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1736         for my $c (@copies) {
1737                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1738         }
1739         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1740
1741         return \@copies;
1742 }
1743
1744
1745 sub choose_nearest_copy {
1746         my $hold = shift;
1747         my $prox_list = shift;
1748
1749         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1750                 next unless (ref $$prox_list[$p]);
1751
1752                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1753                 next unless (@capturable);
1754
1755                 my $rand = int(rand(scalar(@capturable)));
1756                 while (my ($c) = splice(@capturable,$rand)) {
1757                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1758                                 { title => $c->call_number->record->to_fieldmapper,
1759                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1760                                   patron => $hold->usr->to_fieldmapper,
1761                                   copy => $c->to_fieldmapper,
1762                                   requestor => $hold->requestor->to_fieldmapper,
1763                                   request_lib => $hold->request_lib->to_fieldmapper,
1764                                    pickup_lib => $hold->pickup_lib->id,
1765                                 }
1766                         ));
1767
1768                         last unless(@capturable);
1769                         $rand = int(rand(scalar(@capturable)));
1770                 }
1771         }
1772 }
1773
1774 sub create_prox_list {
1775         my $self = shift;
1776         my $lib = shift;
1777         my $copies = shift;
1778
1779         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1780
1781         my @prox_list;
1782         for my $cp (@$copies) {
1783                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1784                 next unless (defined($prox));
1785
1786                 # Fetch the weighting value for hold targeting, defaulting to 1
1787                 $self->{target_weight}{$lib} ||= $actor->request(
1788                         'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1789                 )->gather(1) || 1;
1790
1791                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1792                 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1793                         push @{$prox_list[$prox]}, $cp;
1794                 }
1795         }
1796         return \@prox_list;
1797 }
1798
1799 sub volume_hold_capture {
1800         my $self = shift;
1801         my $hold = shift;
1802         my $vols = shift;
1803
1804         if (!defined($vols)) {
1805                 try {
1806                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1807                         $cache{cns}{$_->id} = $_ for (@$vols);
1808                 } catch Error with {
1809                         my $e = shift;
1810                         die "Could not retrieve initial volume list:\n\n$e\n";
1811                 };
1812         }
1813
1814         my @v_ids = map { $_->id } @$vols;
1815
1816         my $cp_list;
1817         try {
1818                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1819         
1820         } catch Error with {
1821                 my $e = shift;
1822                 warn "Could not retrieve copy list:\n\n$e\n";
1823         };
1824
1825         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1826 }
1827
1828 sub title_hold_capture {
1829         my $self = shift;
1830         my $hold = shift;
1831         my $titles = shift;
1832
1833         if (!defined($titles)) {
1834                 try {
1835                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1836                         $cache{titles}{$_->id} = $_ for (@$titles);
1837                 } catch Error with {
1838                         my $e = shift;
1839                         die "Could not retrieve initial title list:\n\n$e\n";
1840                 };
1841         }
1842
1843         my @t_ids = map { $_->id } @$titles;
1844         my $cn_list;
1845         try {
1846                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1847         
1848         } catch Error with {
1849                 my $e = shift;
1850                 warn "Could not retrieve volume list:\n\n$e\n";
1851         };
1852
1853         $cache{cns}{$_->id} = $_ for (@$cn_list);
1854
1855         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1856 }
1857
1858 sub metarecord_hold_capture {
1859         my $self = shift;
1860         my $hold = shift;
1861
1862         my $titles;
1863         try {
1864                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1865         
1866         } catch Error with {
1867                 my $e = shift;
1868                 die "Could not retrieve initial title list:\n\n$e\n";
1869         };
1870
1871         try {
1872                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1873
1874                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1875         
1876         } catch Error with {
1877                 my $e = shift;
1878                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1879         };
1880
1881
1882         $cache{titles}{$_->id} = $_ for (@$titles);
1883         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1884 }
1885
1886 1;