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