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