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