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