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