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