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