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