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