]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/action.pm
TPac: first try audience_group SVF for audience maps
[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     my $find_copy = shift;
1046
1047         local $OpenILS::Application::Storage::WRITE = 1;
1048
1049         $self->{target_weight} = {};
1050         $self->{max_loops} = {};
1051
1052         my $holds;
1053
1054         try {
1055                 if ($one_hold) {
1056                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1057                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
1058                 } elsif ( $check_expire ) {
1059
1060                         # what's the retarget time threashold?
1061                         my $time = time;
1062                         $check_expire ||= '12h';
1063                         $check_expire = interval_to_seconds( $check_expire );
1064
1065                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1066                         $year += 1900;
1067                         $mon += 1;
1068                         my $expire_threshold = sprintf(
1069                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1070                                 $year, $mon, $mday, $hour, $min, $sec
1071                         );
1072
1073                         # find all the holds holds needing retargeting
1074                         $holds = [ action::hold_request->search_where(
1075                                                         { capture_time => undef,
1076                                                           fulfillment_time => undef,
1077                                                           cancel_time => undef,
1078                                                           frozen => 'f',
1079                                                           prev_check_time => { '<=' => $expire_threshold },
1080                                                         },
1081                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1082
1083                         # find all the holds holds needing first time targeting
1084                         push @$holds, action::hold_request->search(
1085                                                         capture_time => undef,
1086                                                         fulfillment_time => undef,
1087                                                         prev_check_time => undef,
1088                                                         frozen => 'f',
1089                                                         cancel_time => undef,
1090                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1091                 } else {
1092
1093                         # find all the holds holds needing first time targeting ONLY
1094                         $holds = [ action::hold_request->search(
1095                                                         capture_time => undef,
1096                                                         fulfillment_time => undef,
1097                                                         prev_check_time => undef,
1098                                                         cancel_time => undef,
1099                                                         frozen => 'f',
1100                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1101                 }
1102         } catch Error with {
1103                 my $e = shift;
1104                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1105         };
1106
1107         my @closed = actor::org_unit::closed_date->search_where(
1108                 { close_start => { '<=', 'now' },
1109                   close_end => { '>=', 'now' } }
1110         );
1111
1112     if ($check_expire) {
1113
1114         # $check_expire, if it exists, was already converted to seconds
1115         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1116             $year += 1900;
1117         $mon += 1;
1118
1119             my $next_check_time = sprintf(
1120                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1121                 $year, $mon, $mday, $hour, $min, $sec
1122         );
1123
1124
1125             my @closed_at_next = actor::org_unit::closed_date->search_where(
1126                     { close_start => { '<=', $next_check_time },
1127                   close_end => { '>=', $next_check_time } }
1128             );
1129
1130         my @new_closed;
1131         for my $c_at_n (@closed_at_next) {
1132             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1133                 push @new_closed, $c_at_n;
1134             }
1135         }
1136         @closed = @new_closed;
1137     }
1138
1139         my @successes;
1140         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1141
1142         for my $hold (@$holds) {
1143                 try {
1144                         #start a transaction if needed
1145                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1146                                 $log->debug("Cleaning up after previous transaction\n");
1147                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1148                         }
1149                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1150                         $log->info("Processing hold ".$hold->id."...\n");
1151
1152                         #first, re-fetch the hold, to make sure it's not captured already
1153                         $hold->remove_from_object_index();
1154                         $hold = action::hold_request->retrieve( $hold->id );
1155
1156                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1157
1158                         # remove old auto-targeting maps
1159                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1160                         $_->delete for (@oldmaps);
1161
1162                         if ($hold->expire_time) {
1163                                 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1164                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1165
1166                                         # cancel cause = un-targeted expiration
1167                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1168                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1169
1170                                         # tell A/T the hold was cancelled
1171                                         my $fm_hold = $hold->to_fieldmapper;
1172                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1173                                         $ses->request('open-ils.trigger.event.autocreate', 
1174                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1175
1176                                         die "OK\n";
1177                                 }
1178                         }
1179
1180                         my $all_copies = [];
1181
1182                         # find filters for MR holds
1183                         my ($types, $formats, $lang);
1184                         if (defined($hold->holdable_formats)) {
1185                                 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1186                         }
1187
1188                         # find all the potential copies
1189                         if ($hold->hold_type eq 'M') {
1190                                 for my $r ( map
1191                                                 {$_->record}
1192                                                 metabib::record_descriptor
1193                                                         ->search(
1194                                                                 record => [
1195                                                                         map {
1196                                                                                 isTrue($_->deleted) ?  () : ($_->id)
1197                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
1198                                                                 ],
1199                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
1200                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
1201                                                                 ( $lang    ? (item_lang => $lang)                                : () ),
1202                                                         )
1203                                 ) {
1204                                         my ($rtree) = $self
1205                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1206                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1207
1208                                         for my $cn ( @{ $rtree->call_numbers } ) {
1209                                                 push @$all_copies,
1210                                                         asset::copy->search_where(
1211                                                                 { id => [map {$_->id} @{ $cn->copies }],
1212                                                                   deleted => 'f' }
1213                                                         ) if ($cn && @{ $cn->copies });
1214                                         }
1215                                 }
1216                         } elsif ($hold->hold_type eq 'T') {
1217                                 my ($rtree) = $self
1218                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1219                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1220
1221                                 unless ($rtree) {
1222                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1223                                         die "OK\n";
1224                                 }
1225
1226                                 for my $cn ( @{ $rtree->call_numbers } ) {
1227                                         push @$all_copies,
1228                                                 asset::copy->search_where(
1229                                                         { id => [map {$_->id} @{ $cn->copies }],
1230                                                           deleted => 'f' }
1231                                                 ) if ($cn && @{ $cn->copies });
1232                                 }
1233                         } elsif ($hold->hold_type eq 'V') {
1234                                 my ($vtree) = $self
1235                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1236                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1237
1238                                 push @$all_copies,
1239                                         asset::copy->search_where(
1240                                                 { id => [map {$_->id} @{ $vtree->copies }],
1241                                                   deleted => 'f' }
1242                                         ) if ($vtree && @{ $vtree->copies });
1243
1244                         } elsif ($hold->hold_type eq 'P') {
1245                                 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1246                                 $all_copies = [
1247                                         asset::copy->search_where(
1248                                                 { id => [map {$_->target_copy} @part_maps],
1249                                                   deleted => 'f' }
1250                                         )
1251                                 ] if (@part_maps);
1252                                         
1253                         } elsif ($hold->hold_type eq 'I') {
1254                                 my ($itree) = $self
1255                                         ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1256                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1257
1258                                 push @$all_copies,
1259                                         asset::copy->search_where(
1260                                                 { id => [map {$_->unit->id} @{ $itree->items }],
1261                                                   deleted => 'f' }
1262                                         ) if ($itree && @{ $itree->items });
1263                                         
1264                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1265                                 my $_cp = asset::copy->retrieve($hold->target);
1266                                 push @$all_copies, $_cp if $_cp;
1267                         }
1268
1269                         # trim unholdables
1270                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1271                                                 isTrue($_->location->holdable) && 
1272                                                 isTrue($_->holdable) &&
1273                                                 !isTrue($_->deleted) &&
1274                                                 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1275                                                 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1276                                         } @$all_copies;
1277
1278                         # let 'em know we're still working
1279                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1280                         
1281                         # if we have no copies ...
1282                         if (!ref $all_copies || !@$all_copies) {
1283                                 $log->info("\tNo copies available for targeting at all!\n");
1284                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1285
1286                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1287                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1288                                 die "OK\n";
1289                         }
1290
1291                         my $copy_count = @$all_copies;
1292             my $found_copy = undef;
1293             $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1294
1295                         # map the potentials, so that we can pick up checkins
1296                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1297                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1298                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1299                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1300
1301                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1302
1303                         my @good_copies;
1304                         for my $c (@$all_copies) {
1305                                 # current target
1306                                 next if ($c->id eq $hold->current_copy);
1307
1308                                 # circ lib is closed
1309                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1310
1311                                 # target of another hold
1312                                 next if (action::hold_request
1313                                                 ->search_where(
1314                                                         { current_copy => $c->id,
1315                                                           fulfillment_time => undef,
1316                                                           cancel_time => undef,
1317                                                         }
1318                                                 )
1319                                 );
1320
1321                                 # we passed all three, keep it
1322                                 push @good_copies, $c if ($c);
1323                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1324                         }
1325
1326                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1327
1328                         my $old_best = $hold->current_copy;
1329                         $hold->update({ current_copy => undef }) if ($old_best);
1330         
1331                         if (!scalar(@good_copies)) {
1332                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1333                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1334                                         # the old copy is still available
1335                                         $log->debug("\tPushing current_copy back onto the targeting list");
1336                                         push @good_copies, $old_best;
1337                                 } else {
1338                                         # oops, old copy is not available
1339                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1340                                         $hold->update( { prev_check_time => 'today' } );
1341                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1342                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1343                                         die "OK\n";
1344                                 }
1345                         }
1346
1347             my $pu_lib = ''.$hold->pickup_lib;
1348
1349                         my $prox_list = [];
1350                         $$prox_list[0] =
1351                         [
1352                                 grep {
1353                                         ''.$_->circ_lib eq $pu_lib &&
1354                     ( $_->status == 0 || $_->status == 7 )
1355                                 } @good_copies
1356                         ];
1357
1358                         $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1359                         # $all_copies is now a list of copies not at the pickup library
1360
1361                         my $best = choose_nearest_copy($hold, $prox_list);
1362                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1363
1364                         if (!$best) {
1365                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1366
1367                                 $self->{max_loops}{$pu_lib} = $actor->request(
1368                                         'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1369                                 )->gather(1);
1370
1371                                 if (defined($self->{max_loops}{$pu_lib})) {
1372                                         $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1373
1374                                         my %circ_lib_map =  map { (''.$_->circ_lib => 1) } @$all_copies;
1375                                         my $circ_lib_list = [keys %circ_lib_map];
1376         
1377                                         my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1378         
1379                                         # Grab the "biggest" loop for this hold so far
1380                                         my $current_loop = $cstore->request(
1381                                                 'open-ils.cstore.json_query',
1382                                                 { distinct => 1,
1383                                                   select => { aufhmxl => ['max'] },
1384                                                   from => 'aufhmxl',
1385                                                   where => { hold => $hold->id}
1386                                                 }
1387                                         )->gather(1);
1388         
1389                                         $current_loop = $current_loop->{max} if ($current_loop);
1390                                         $current_loop ||= 1;
1391         
1392                                         my $exclude_list = $cstore->request(
1393                                                 'open-ils.cstore.json_query.atomic',
1394                                                 { distinct => 1,
1395                                                   select => { aufhol => ['circ_lib'] },
1396                                                   from => 'aufhol',
1397                                                   where => { hold => $hold->id}
1398                                                 }
1399                                         )->gather(1);
1400         
1401                                         my @keepers;
1402                                         if ($exclude_list && @$exclude_list) {
1403                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1404                                                 # check to see if we've used up every library in the potentials list
1405                                                 for my $l ( @$circ_lib_list ) {
1406                                                         my $keep = 1;
1407                                                         for my $ex ( @$exclude_list ) {
1408                                                                 if ($ex eq $l) {
1409                                                                         $keep = 0;
1410                                                                         last;
1411                                                                 }
1412                                                         }
1413                                                         push(@keepers, $l) if ($keep);
1414                                                 }
1415                                         } else {
1416                                                 @keepers = @$circ_lib_list;
1417                                         }
1418         
1419                                         $current_loop++ if (!@keepers);
1420         
1421                                         if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1422                                                 # We haven't exceeded max_loops yet
1423                                                 my @keeper_copies;
1424                                                 for my $cp ( @$all_copies ) {
1425                                                         push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1426
1427                                                 }
1428                                                 $all_copies = [@keeper_copies];
1429                                         } else {
1430                                                 # We have, and should remove potentials and cancel the hold
1431                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1432                                                 $_->delete for (@oldmaps);
1433
1434                                                 # cancel cause = un-targeted expiration
1435                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1436                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1437
1438                                                 # tell A/T the hold was cancelled
1439                                                 my $fm_hold = $hold->to_fieldmapper;
1440                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1441                                                 $ses->request('open-ils.trigger.event.autocreate', 
1442                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1443
1444                                                 die "OK\n";
1445                                         }
1446                                 }
1447
1448                                 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1449
1450                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1451
1452                                 $best = choose_nearest_copy($hold, $prox_list);
1453                         }
1454
1455                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1456                         if ($old_best) {
1457                                 # hold wasn't fulfilled, record the fact
1458                         
1459                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1460                                 action::unfulfilled_hold_list->create(
1461                                                 { hold => ''.$hold->id,
1462                                                   current_copy => ''.$old_best->id,
1463                                                   circ_lib => ''.$old_best->circ_lib,
1464                                                 });
1465                         }
1466
1467                         if ($best) {
1468                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1469                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1470                         } elsif (
1471                                 $old_best &&
1472                                 !action::hold_request
1473                                         ->search_where(
1474                                                 { current_copy => $old_best->id,
1475                                                   fulfillment_time => undef,
1476                                                   cancel_time => undef,
1477                                                 }       
1478                                         )
1479                         ) {     
1480                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1481                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1482                         } else {
1483                                 $hold->update( { prev_check_time => 'now' } );
1484                                 $log->info( "\tThere were no targetable copies for the hold" );
1485                                 process_recall($actor, $log, $hold, \@good_copies);
1486                         }
1487
1488                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1489                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1490
1491                         push @successes,
1492                                 { hold => $hold->id,
1493                                   old_target => ($old_best ? $old_best->id : undef),
1494                                   eligible_copies => $copy_count,
1495                                   target => ($best ? $best->id : undef),
1496                   found_copy => $found_copy };
1497
1498                 } otherwise {
1499                         my $e = shift;
1500                         if ($e !~ /^OK/o) {
1501                                 $log->error("Processing of hold failed:  $e");
1502                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1503                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1504                         }
1505                 };
1506         }
1507
1508         return \@successes;
1509 }
1510 __PACKAGE__->register_method(
1511         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1512         api_level       => 1,
1513         method          => 'new_hold_copy_targeter',
1514 );
1515
1516 sub process_recall {
1517     my ($actor, $log, $hold, $good_copies) = @_;
1518
1519     # Bail early if we don't have required settings to avoid spurious requests
1520     my ($recall_threshold, $return_interval, $fine_rules);
1521
1522     my $rv = $actor->request(
1523         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1524     )->gather(1);
1525
1526     if (!$rv) {
1527         $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1528         return;
1529     }
1530     $recall_threshold = $rv->{value};
1531
1532     $rv = $actor->request(
1533         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1534     )->gather(1);
1535
1536     if (!$rv) {
1537         $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1538         return;
1539     }
1540     $return_interval = $rv->{value};
1541
1542     $rv = $actor->request(
1543         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1544     )->gather(1);
1545
1546     if ($rv) {
1547         $fine_rules = $rv->{value};
1548     }
1549
1550     $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1551
1552     # We want checked out copies (status = 1) at the hold pickup lib
1553     my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1554
1555     my @copy_ids = map { $_->id } @$all_copies;
1556
1557     $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1558
1559     my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1560
1561     # Iterate over the checked-out copies to find a copy with a
1562     # loan period longer than the recall threshold:
1563     my $circs = [ action::circulation->search_where(
1564         { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1565         { order_by => 'due_date ASC' }
1566     )];
1567
1568     # If we have a candidate copy, then:
1569     if (scalar(@$circs)) {
1570         my $circ = $circs->[0];
1571         $log->info("Recalling circ ID : " . $circ->id);
1572
1573         # Give the user a new due date of either a full recall threshold,
1574         # or the return interval, whichever is further in the future
1575         my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1576         if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1577             $return_date = $threshold_date;
1578         }
1579
1580         my $update_fields = {
1581             due_date => $return_date,
1582             renewal_remaining => 0,
1583         };
1584
1585         # If the OU hasn't defined new fine rules for recalls, keep them
1586         # as they were
1587         if ($fine_rules) {
1588             $log->info("Apply recall fine rules: $fine_rules");
1589             my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1590             $update_fields->{recurring_fine} = $rules->[0];
1591             $update_fields->{fine_interval} = $rules->[1];
1592             $update_fields->{max_fine} = $rules->[2];
1593         }
1594
1595         # Adjust circ for current user
1596         $circ->update($update_fields);
1597
1598         # Create trigger event for notifying current user
1599         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1600         $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1601     }
1602
1603     $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1604 }
1605
1606 sub reservation_targeter {
1607         my $self = shift;
1608         my $client = shift;
1609         my $one_reservation = shift;
1610
1611         local $OpenILS::Application::Storage::WRITE = 1;
1612
1613         my $reservations;
1614
1615         try {
1616                 if ($one_reservation) {
1617                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1618                         $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1619                 } else {
1620
1621                         # find all the reservations needing targeting
1622                         $reservations = [
1623                 booking::reservation->search_where(
1624                                         { current_resource => undef,
1625                                           cancel_time => undef,
1626                                           start_time => { '>' => 'now' }
1627                     },
1628                     { order_by => 'start_time' }
1629                 )
1630             ];
1631                 }
1632         } catch Error with {
1633                 my $e = shift;
1634                 die "Could not retrieve reservation requests:\n\n$e\n";
1635         };
1636
1637         my @successes = ();
1638         for my $bresv (@$reservations) {
1639                 try {
1640                         #start a transaction if needed
1641                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1642                                 $log->debug("Cleaning up after previous transaction\n");
1643                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1644                         }
1645                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1646                         $log->info("Processing reservation ".$bresv->id."...\n");
1647
1648                         #first, re-fetch the hold, to make sure it's not captured already
1649                         $bresv->remove_from_object_index();
1650                         $bresv = booking::reservation->retrieve( $bresv->id );
1651
1652                         die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1653
1654                         my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1655                         if (DateTime->compare($end_time, DateTime->now) < 0) {
1656
1657                                 # cancel cause = un-targeted expiration
1658                                 $bresv->update( { cancel_time => 'now' } ); 
1659                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1660
1661                                 # tell A/T the reservation was cancelled
1662                                 my $fm_bresv = $bresv->to_fieldmapper;
1663                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1664                                 $ses->request('open-ils.trigger.event.autocreate', 
1665                                         'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1666
1667                                 die "OK\n";
1668                         }
1669
1670                         my $possible_resources;
1671
1672                         # find all the potential resources
1673                         if (!$bresv->target_resource) {
1674                                 my $filter = { type => $bresv->target_resource_type };
1675                                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1676
1677                                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1678
1679                                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1680                                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1681                                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1682                         } else {
1683                                 $possible_resources = $bresv->target_resource;
1684                         }
1685
1686             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1687                         @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1688
1689
1690             my @good_resources = ();
1691             my %conflicts = ();
1692             for my $res (@$all_resources) {
1693                 unless (isTrue($res->type->catalog_item)) {
1694                     push @good_resources, $res;
1695                     next;
1696                 }
1697
1698                 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1699
1700                 unless ($copy) {
1701                     push @good_resources, $res;
1702                     next;
1703                 }
1704
1705                 # At this point, if we're just targeting one specific
1706                 # resource, just succeed. We don't care about its present
1707                 # copy status.
1708                 if ($bresv->target_resource) {
1709                     push @good_resources, $res;
1710                     next;
1711                 }
1712
1713                 if ($copy->status->id == 0 || $copy->status->id == 7) {
1714                     push @good_resources, $res;
1715                     next;
1716                 }
1717
1718                 if ($copy->status->id == 1) {
1719                     my $circs = [ action::circulation->search_where(
1720                         {target_copy => $copy->id, checkin_time => undef },
1721                         { order_by => 'id DESC' }
1722                     ) ];
1723
1724                     if (@$circs) {
1725                         my $due_date = $circs->[0]->due_date;
1726                                     $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1727                                     my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1728                         if (DateTime->compare($start_time, $due_date) < 0) {
1729                             $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1730                             next;
1731                         }
1732
1733                         push @good_resources, $res;
1734                     }
1735
1736                     next;
1737                 }
1738
1739                 push @good_resources, $res if (isTrue($copy->status->holdable));
1740             }
1741
1742                         # let 'em know we're still working
1743                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1744                         
1745                         # if we have no copies ...
1746                         if (!@good_resources) {
1747                                 $log->info("\tNo resources available for targeting at all!\n");
1748                                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1749
1750
1751                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1752                                 die "OK\n";
1753                         }
1754
1755                         $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1756
1757                         my $prox_list = [];
1758                         $$prox_list[0] =
1759                         [
1760                                 grep {
1761                                         $_->owner == $bresv->pickup_lib
1762                                 } @good_resources
1763                         ];
1764
1765                         $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1766                         # $all_copies is now a list of copies not at the pickup library
1767
1768                         my $best = shift @good_resources;
1769                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1770
1771                         if (!$best) {
1772                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1773
1774                                 $prox_list =
1775                     map  { $_->[1] }
1776                     sort { $a->[0] <=> $b->[0] }
1777                     map  {
1778                         [   actor::org_unit_proximity->search_where(
1779                                 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1780                             )->[0]->prox,
1781                             $_
1782                         ]
1783                     } @$all_resources;
1784
1785                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1786
1787                                 $best = shift @$prox_list
1788                         }
1789
1790                         if ($best) {
1791                                 $bresv->update( { current_resource => ''.$best->id } );
1792                                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1793                         }
1794
1795                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1796                         $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1797
1798                         push @successes,
1799                                 { reservation => $bresv->id,
1800                                   current_resource => ($best ? $best->id : undef) };
1801
1802                 } otherwise {
1803                         my $e = shift;
1804                         if ($e !~ /^OK/o) {
1805                                 $log->error("Processing of bresv failed:  $e");
1806                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1807                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1808                         }
1809                 };
1810         }
1811
1812         return \@successes;
1813 }
1814 __PACKAGE__->register_method(
1815         api_name        => 'open-ils.storage.booking.reservation.resource_targeter',
1816         api_level       => 1,
1817         method          => 'reservation_targeter',
1818 );
1819
1820 my $locations;
1821 my $statuses;
1822 my %cache = (titles => {}, cns => {});
1823
1824 sub copy_hold_capture {
1825         my $self = shift;
1826         my $hold = shift;
1827         my $cps = shift;
1828
1829         if (!defined($cps)) {
1830                 try {
1831                         $cps = [ asset::copy->search( id => $hold->target ) ];
1832                 } catch Error with {
1833                         my $e = shift;
1834                         die "Could not retrieve initial volume list:\n\n$e\n";
1835                 };
1836         }
1837
1838         my @copies = grep { $_->holdable } @$cps;
1839
1840         for (my $i = 0; $i < @$cps; $i++) {
1841                 next unless $$cps[$i];
1842                 
1843                 my $cn = $cache{cns}{$copies[$i]->call_number};
1844                 my $rec = $cache{titles}{$cn->record};
1845                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1846                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1847                 $copies[$i] = undef if (
1848                         !$copies[$i] ||
1849                         !$self->{user_filter}->request(
1850                                 'open-ils.circ.permit_hold',
1851                                 $hold->to_fieldmapper, do {
1852                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1853                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1854                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1855                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1856                                         $cp_fm;
1857                                 },
1858                                 { title => $rec->to_fieldmapper,
1859                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1860                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1861                                 })->gather(1)
1862                 );
1863                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1864         }
1865
1866         @copies = grep { $_ } @copies;
1867
1868         my $count = @copies;
1869
1870         return unless ($count);
1871         
1872         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1873         
1874         my @maps;
1875         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1876         for my $c (@copies) {
1877                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1878         }
1879         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1880
1881         return \@copies;
1882 }
1883
1884
1885 sub choose_nearest_copy {
1886         my $hold = shift;
1887         my $prox_list = shift;
1888
1889         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1890                 next unless (ref $$prox_list[$p]);
1891
1892                 my @capturable = @{ $$prox_list[$p] };
1893                 next unless (@capturable);
1894
1895                 my $rand = int(rand(scalar(@capturable)));
1896                 my %seen = ();
1897                 while (my ($c) = splice(@capturable, $rand, 1)) {
1898                         return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1899                                 { title => $c->call_number->record->to_fieldmapper,
1900                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1901                                   patron => $hold->usr->to_fieldmapper,
1902                                   copy => $c->to_fieldmapper,
1903                                   requestor => $hold->requestor->to_fieldmapper,
1904                                   request_lib => $hold->request_lib->to_fieldmapper,
1905                                   pickup_lib => $hold->pickup_lib->id,
1906                                   retarget => 1
1907                                 }
1908                         ));
1909                         $seen{$c->id}++;
1910
1911                         last unless(@capturable);
1912                         $rand = int(rand(scalar(@capturable)));
1913                 }
1914         }
1915 }
1916
1917 sub create_prox_list {
1918         my $self = shift;
1919         my $lib = shift;
1920         my $copies = shift;
1921
1922         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1923
1924         my @prox_list;
1925         for my $cp (@$copies) {
1926                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1927                 next unless (defined($prox));
1928
1929         my $copy_circ_lib = ''.$cp->circ_lib;
1930                 # Fetch the weighting value for hold targeting, defaulting to 1
1931                 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1932                         'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1933                 )->gather(1);
1934         $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1935         $self->{target_weight}{$copy_circ_lib} ||= 1;
1936
1937                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1938                 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1939                         push @{$prox_list[$prox]}, $cp;
1940                 }
1941         }
1942         return \@prox_list;
1943 }
1944
1945 sub volume_hold_capture {
1946         my $self = shift;
1947         my $hold = shift;
1948         my $vols = shift;
1949
1950         if (!defined($vols)) {
1951                 try {
1952                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1953                         $cache{cns}{$_->id} = $_ for (@$vols);
1954                 } catch Error with {
1955                         my $e = shift;
1956                         die "Could not retrieve initial volume list:\n\n$e\n";
1957                 };
1958         }
1959
1960         my @v_ids = map { $_->id } @$vols;
1961
1962         my $cp_list;
1963         try {
1964                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1965         
1966         } catch Error with {
1967                 my $e = shift;
1968                 warn "Could not retrieve copy list:\n\n$e\n";
1969         };
1970
1971         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1972 }
1973
1974 sub title_hold_capture {
1975         my $self = shift;
1976         my $hold = shift;
1977         my $titles = shift;
1978
1979         if (!defined($titles)) {
1980                 try {
1981                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1982                         $cache{titles}{$_->id} = $_ for (@$titles);
1983                 } catch Error with {
1984                         my $e = shift;
1985                         die "Could not retrieve initial title list:\n\n$e\n";
1986                 };
1987         }
1988
1989         my @t_ids = map { $_->id } @$titles;
1990         my $cn_list;
1991         try {
1992                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1993         
1994         } catch Error with {
1995                 my $e = shift;
1996                 warn "Could not retrieve volume list:\n\n$e\n";
1997         };
1998
1999         $cache{cns}{$_->id} = $_ for (@$cn_list);
2000
2001         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2002 }
2003
2004 sub metarecord_hold_capture {
2005         my $self = shift;
2006         my $hold = shift;
2007
2008         my $titles;
2009         try {
2010                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2011         
2012         } catch Error with {
2013                 my $e = shift;
2014                 die "Could not retrieve initial title list:\n\n$e\n";
2015         };
2016
2017         try {
2018                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
2019
2020                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2021         
2022         } catch Error with {
2023                 my $e = shift;
2024                 die "Could not retrieve format-pruned title list:\n\n$e\n";
2025         };
2026
2027
2028         $cache{titles}{$_->id} = $_ for (@$titles);
2029         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
2030 }
2031
2032 1;