]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/action.pm
Avoid checkin capture for CAPTURE-blocked holds
[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, p.prox " :
298                         "p.prox, pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
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                   WHERE a.circ_lib = ?
509                         AND h.capture_time IS NULL
510                         AND h.cancel_time IS NULL
511                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
512                         $status_filter
513                   ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
514                   LIMIT $limit
515                   OFFSET $offset
516         SQL
517
518     if ($count) {
519         $select = <<"        SQL";
520             SELECT    count(*)
521               FROM    $h_table h
522                   JOIN $a_table a ON (h.current_copy = a.id)
523               WHERE    a.circ_lib = ?
524                   AND h.capture_time IS NULL
525                   AND h.cancel_time IS NULL
526                   AND (h.expire_time IS NULL OR h.expire_time > NOW())
527                 $status_filter
528         SQL
529     }
530
531         my $sth = action::survey->db_Main->prepare_cached($select);
532         $sth->execute($ou);
533
534         if ($count) {
535                 $client->respond( $sth->fetchall_arrayref()->[0][0] );
536         } elsif ($idlist) {
537                 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
538         } else {
539                 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
540         }
541
542         return undef;
543 }
544 __PACKAGE__->register_method(
545         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
546         api_level       => 1,
547         stream          => 1,
548         signature       => [
549                 "Returns a count of holds for a specific library's pull list.",
550                 [ [org_unit => "The library's org id", "number"] ],
551                 ['A count of holds for the stated library to pull ', 'number']
552         ],
553         method          => 'hold_pull_list',
554 );
555 __PACKAGE__->register_method(
556         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
557         api_level       => 1,
558         stream          => 1,
559         signature       => [
560                 "Returns a status filtered count of holds for a specific library's pull list.",
561                 [ [org_unit => "The library's org id", "number"] ],
562                 ['A status filtered count of holds for the stated library to pull ', 'number']
563         ],
564         method          => 'hold_pull_list',
565 );
566 __PACKAGE__->register_method(
567         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
568         api_level       => 1,
569         stream          => 1,
570         signature       => [
571                 "Returns the hold ids for a specific library's pull list.",
572                 [ [org_unit => "The library's org id", "number"],
573                   [limit => 'An optional page size, defaults to 10', 'number'],
574                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
575                 ],
576                 ['A list of holds for the stated library to pull for', 'array']
577         ],
578         method          => 'hold_pull_list',
579 );
580 __PACKAGE__->register_method(
581         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
582         api_level       => 1,
583         stream          => 1,
584         signature       => [
585                 "Returns the holds for a specific library's pull list.",
586                 [ [org_unit => "The library's org id", "number"],
587                   [limit => 'An optional page size, defaults to 10', 'number'],
588                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
589                 ],
590                 ['A list of holds for the stated library to pull for', 'array']
591         ],
592         method          => 'hold_pull_list',
593 );
594 __PACKAGE__->register_method(
595         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
596         api_level       => 1,
597         stream          => 1,
598         signature       => [
599                 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
600                 [ [org_unit => "The library's org id", "number"],
601                   [limit => 'An optional page size, defaults to 10', 'number'],
602                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
603                 ],
604                 ['A list of holds for the stated library to pull for', 'array']
605         ],
606         method          => 'hold_pull_list',
607 );
608 __PACKAGE__->register_method(
609         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
610         api_level       => 1,
611         stream          => 1,
612         signature       => [
613                 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
614                 [ [org_unit => "The library's org id", "number"],
615                   [limit => 'An optional page size, defaults to 10', 'number'],
616                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
617                 ],
618                 ['A list of holds for the stated library to pull for', 'array']
619         ],
620         method          => 'hold_pull_list',
621 );
622
623 sub find_optional_surveys {
624         my $self = shift;
625         my $client = shift;
626         my $ou = ''.shift();
627
628         return undef unless ($ou);
629         my $s_table = action::survey->table;
630
631         my $select = <<"        SQL";
632                 SELECT  s.*
633                   FROM  $s_table s
634                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
635                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
636                         AND s.required IS FALSE;
637         SQL
638
639         my $sth = action::survey->db_Main->prepare_cached($select);
640         $sth->execute($ou);
641
642         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
643
644         return undef;
645 }
646 __PACKAGE__->register_method(
647         api_name        => 'open-ils.storage.action.survey.optional',
648         api_level       => 1,
649         stream          => 1,
650         method          => 'find_optional_surveys',
651 );
652
653 sub find_required_surveys {
654         my $self = shift;
655         my $client = shift;
656         my $ou = ''.shift();
657
658         return undef unless ($ou);
659         my $s_table = action::survey->table;
660
661         my $select = <<"        SQL";
662                 SELECT  s.*
663                   FROM  $s_table s
664                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
665                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
666                         AND s.required IS TRUE;
667         SQL
668
669         my $sth = action::survey->db_Main->prepare_cached($select);
670         $sth->execute($ou);
671
672         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
673
674         return undef;
675 }
676 __PACKAGE__->register_method(
677         api_name        => 'open-ils.storage.action.survey.required',
678         api_level       => 1,
679         stream          => 1,
680         method          => 'find_required_surveys',
681 );
682
683 sub find_usr_summary_surveys {
684         my $self = shift;
685         my $client = shift;
686         my $ou = ''.shift();
687
688         return undef unless ($ou);
689         my $s_table = action::survey->table;
690
691         my $select = <<"        SQL";
692                 SELECT  s.*
693                   FROM  $s_table s
694                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
695                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
696                         AND s.usr_summary IS TRUE;
697         SQL
698
699         my $sth = action::survey->db_Main->prepare_cached($select);
700         $sth->execute($ou);
701
702         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
703
704         return undef;
705 }
706 __PACKAGE__->register_method(
707         api_name        => 'open-ils.storage.action.survey.usr_summary',
708         api_level       => 1,
709         stream          => 1,
710         method          => 'find_usr_summary_surveys',
711 );
712
713 sub seconds_to_interval_hash {
714                 my $interval = shift;
715                 my $limit = shift || 's';
716                 $limit =~ s/^(.)/$1/o;
717
718                 my %output;
719
720                 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
721                 my ($year, $month, $week, $day, $hour, $minute, $second) =
722                                 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
723
724                 if ($y = int($interval / (60 * 60 * 24 * 365))) {
725                                 $output{$year} = $y;
726                                 $ym = $interval % (60 * 60 * 24 * 365);
727                 } else {
728                                 $ym = $interval;
729                 }
730                 return %output if ($limit eq 'y');
731
732                 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
733                                 $output{$month} = $M;
734                                 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
735                 } else {
736                                 $Mm = $ym;
737                 }
738                 return %output if ($limit eq 'M');
739
740                 if ($w = int($Mm / 604800)) {
741                                 $output{$week} = $w;
742                                 $wm = $Mm % 604800;
743                 } else {
744                                 $wm = $Mm;
745                 }
746                 return %output if ($limit eq 'w');
747
748                 if ($d = int($wm / 86400)) {
749                                 $output{$day} = $d;
750                                 $dm = $wm % 86400;
751                 } else {
752                                 $dm = $wm;
753                 }
754                 return %output if ($limit eq 'd');
755
756                 if ($h = int($dm / 3600)) {
757                                 $output{$hour} = $h;
758                                 $hm = $dm % 3600;
759                 } else {
760                                 $hm = $dm;
761                 }
762                 return %output if ($limit eq 'h');
763
764                 if ($m = int($hm / 60)) {
765                                 $output{$minute} = $m;
766                                 $mm = $hm % 60;
767                 } else {
768                                 $mm = $hm;
769                 }
770                 return %output if ($limit eq 'm');
771
772                 if ($s = int($mm)) {
773                                 $output{$second} = $s;
774                 } else {
775                                 $output{$second} = 0 unless (keys %output);
776                 }
777                 return %output;
778 }
779
780
781 sub generate_fines {
782         my $self = shift;
783         my $client = shift;
784         my $circ = shift;
785         my $overbill = shift;
786
787         local $OpenILS::Application::Storage::WRITE = 1;
788
789         my @circs;
790         if ($circ) {
791                 push @circs,
792             action::circulation->search_where( { id => $circ, stop_fines => undef } ),
793             booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
794         } else {
795                 push @circs, overdue_circs();
796         }
797
798         my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
799
800         my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
801         for my $c (@circs) {
802
803         my $ctype = ref($c);
804         $ctype =~ s/^.+::(\w+)$/$1/;
805         
806         my $due_date_method = 'due_date';
807         my $target_copy_method = 'target_copy';
808         my $circ_lib_method = 'circ_lib';
809         my $recurring_fine_method = 'recurring_fine';
810         my $is_reservation = 0;
811         if ($ctype eq 'reservation') {
812             $is_reservation = 1;
813             $due_date_method = 'end_time';
814             $target_copy_method = 'current_resource';
815             $circ_lib_method = 'pickup_lib';
816             $recurring_fine_method = 'fine_amount';
817             next unless ($c->fine_interval);
818         }
819         #TODO: reservation grace periods
820         my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
821
822                 try {
823                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
824                                 $log->debug("Cleaning up after previous transaction\n");
825                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
826                         }
827                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
828                         $log->info(
829                                 sprintf("Processing %s %d...",
830                                         ($is_reservation ? "reservation" : "circ"), $c->id
831                                 )
832                         );
833
834
835                         my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
836         
837                         my $due = $due_dt->epoch;
838                         my $now = time;
839
840                         my $fine_interval = $c->fine_interval;
841             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
842                         $fine_interval = interval_to_seconds( $fine_interval );
843         
844             if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
845                 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
846                 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
847                 next;
848             }
849
850                         if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {        
851                                 my $tz_offset_s = 0;
852                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
853                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
854                                 }
855         
856                                 $due -= ($due % $fine_interval) + $tz_offset_s;
857                                 $now -= ($now % $fine_interval) + $tz_offset_s;
858                         }
859         
860                         $client->respond(
861                                 "ARG! Overdue $ctype ".$c->id.
862                                 " for item ".$c->$target_copy_method.
863                                 " (user ".$c->usr.").\n".
864                                 "\tItem was due on or before: ".localtime($due)."\n");
865         
866                         my @fines = money::billing->search_where(
867                                 { xact => $c->id,
868                                   btype => 1,
869                                   billing_ts => { '>' => $c->$due_date_method } },
870                                 { order_by => 'billing_ts DESC'}
871                         );
872
873                         my $f_idx = 0;
874                         my $fine = $fines[$f_idx] if (@fines);
875                         if ($overbill) {
876                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
877                         }
878
879                         my $current_fine_total = 0;
880                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
881         
882                         my $last_fine;
883                         if ($fine) {
884                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
885                                 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
886                         } else {
887                                 $log->info( "Potential first billing for circ ".$c->id );
888                                 $last_fine = $due;
889
890                                 $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});
891                         }
892
893             next if ($last_fine > $now);
894             # Generate fines for each past interval, including the one we are inside
895             my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
896
897             if ( $last_fine == $due                         # we have no fines yet
898                  && $grace_period                           # and we have a grace period
899                  && $now < $due + $grace_period             # and some date math says were are within the grace period
900             ) {
901                 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
902                 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
903                 next;
904             }
905
906             $client->respond( "\t$pending_fine_count pending fine(s)\n" );
907             next unless ($pending_fine_count);
908
909                         my $recurring_fine = int($c->$recurring_fine_method * 100);
910                         my $max_fine = int($c->max_fine * 100);
911
912                         my $skip_closed_check = $U->ou_ancestor_setting_value(
913                                 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
914                         $skip_closed_check = $U->is_true($skip_closed_check);
915
916                         my ($latest_billing_ts, $latest_amount) = ('',0);
917                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
918         
919                                 if ($current_fine_total >= $max_fine) {
920                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
921                                         $client->respond(
922                                                 "\tMaximum fine level of ".$c->max_fine.
923                                                 " reached for this $ctype.\n".
924                                                 "\tNo more fines will be generated.\n" );
925                                         last;
926                                 }
927                                 
928                                 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
929                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
930                                 my $current_bill_count = $bill;
931                                 while ( $current_bill_count ) {
932                                         $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
933                                         $current_bill_count--;
934                                 }
935
936                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
937                                 if (!$skip_closed_check) {
938                                         my $dow = $billing_ts->day_of_week_0();
939                                         my $dow_open = "dow_${dow}_open";
940                                         my $dow_close = "dow_${dow}_close";
941
942                                         if (my $h = $hoo{$c->$circ_lib_method}) {
943                                                 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
944                                         }
945         
946                                         my @cl = actor::org_unit::closed_date->search_where(
947                                                         { close_start   => { '<=' => $timestamptz },
948                                                           close_end     => { '>=' => $timestamptz },
949                                                           org_unit      => $c->$circ_lib_method }
950                                         );
951                                         next if (@cl);
952                                 }
953
954                                 $current_fine_total += $recurring_fine;
955                                 $latest_amount += $recurring_fine;
956                                 $latest_billing_ts = $timestamptz;
957
958                                 money::billing->create(
959                                         { xact          => ''.$c->id,
960                                           note          => "System Generated Overdue Fine",
961                                           billing_type  => "Overdue materials",
962                                           btype         => 1,
963                                           amount        => sprintf('%0.2f', $recurring_fine/100),
964                                           billing_ts    => $timestamptz,
965                                         }
966                                 );
967
968                         }
969
970                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
971                                 if ($latest_billing_ts and $latest_amount);
972
973                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
974
975                         if(1) { 
976
977                 # Caluclate penalties inline
978                                 OpenILS::Utils::Penalty->calculate_penalties(
979                                         undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
980
981                         } else {
982
983                 # Calculate penalties with an aysnc call to the penalty server.  This approach
984                 # may lead to duplicate penalties since multiple penalty processes for a
985                 # given user may be running at the same time. Leave this here for reference 
986                 # in case we later find that asyc calls are needed in some environments.
987                                 $penalty->request(
988                                     'open-ils.penalty.patron_penalty.calculate',
989                                     { patronid  => ''.$c->usr,
990                                     context_org => ''.$c->$circ_lib_method,
991                                     update      => 1,
992                                     background  => 1,
993                                     }
994                             )->gather(1);
995                         }
996
997                 } catch Error with {
998                         my $e = shift;
999                         $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1000                         $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1001                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1002                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1003                 };
1004         }
1005 }
1006 __PACKAGE__->register_method(
1007         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
1008         api_level       => 1,
1009         stream          => 1,
1010         method          => 'generate_fines',
1011 );
1012
1013
1014
1015 sub new_hold_copy_targeter {
1016         my $self = shift;
1017         my $client = shift;
1018         my $check_expire = shift;
1019         my $one_hold = shift;
1020     my $find_copy = shift;
1021
1022         local $OpenILS::Application::Storage::WRITE = 1;
1023
1024         $self->{target_weight} = {};
1025         $self->{max_loops} = {};
1026
1027         my $holds;
1028
1029         try {
1030                 if ($one_hold) {
1031                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1032                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1033                 } elsif ( $check_expire ) {
1034
1035                         # what's the retarget time threashold?
1036                         my $time = time;
1037                         $check_expire ||= '12h';
1038                         $check_expire = interval_to_seconds( $check_expire );
1039
1040                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1041                         $year += 1900;
1042                         $mon += 1;
1043                         my $expire_threshold = sprintf(
1044                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1045                                 $year, $mon, $mday, $hour, $min, $sec
1046                         );
1047
1048                         # find all the holds holds needing retargeting
1049                         $holds = [ action::hold_request->search_where(
1050                                                         { capture_time => undef,
1051                                                           fulfillment_time => undef,
1052                                                           cancel_time => undef,
1053                                                           frozen => 'f',
1054                                                           prev_check_time => { '<=' => $expire_threshold },
1055                                                         },
1056                                                         { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1057
1058                         # find all the holds holds needing first time targeting
1059                         push @$holds, action::hold_request->search(
1060                                                         capture_time => undef,
1061                                                         fulfillment_time => undef,
1062                                                         prev_check_time => undef,
1063                                                         frozen => 'f',
1064                                                         cancel_time => undef,
1065                                                         { order_by => 'selection_depth DESC, request_time' } );
1066                 } else {
1067
1068                         # find all the holds holds needing first time targeting ONLY
1069                         $holds = [ action::hold_request->search(
1070                                                         capture_time => undef,
1071                                                         fulfillment_time => undef,
1072                                                         prev_check_time => undef,
1073                                                         cancel_time => undef,
1074                                                         frozen => 'f',
1075                                                         { order_by => 'selection_depth DESC, request_time' } ) ];
1076                 }
1077         } catch Error with {
1078                 my $e = shift;
1079                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1080         };
1081
1082         my @closed = actor::org_unit::closed_date->search_where(
1083                 { close_start => { '<=', 'now' },
1084                   close_end => { '>=', 'now' } }
1085         );
1086
1087     if ($check_expire) {
1088
1089         # $check_expire, if it exists, was already converted to seconds
1090         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1091             $year += 1900;
1092         $mon += 1;
1093
1094             my $next_check_time = sprintf(
1095                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1096                 $year, $mon, $mday, $hour, $min, $sec
1097         );
1098
1099
1100             my @closed_at_next = actor::org_unit::closed_date->search_where(
1101                     { close_start => { '<=', $next_check_time },
1102                   close_end => { '>=', $next_check_time } }
1103             );
1104
1105         my @new_closed;
1106         for my $c_at_n (@closed_at_next) {
1107             if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1108                 push @new_closed, $c_at_n;
1109             }
1110         }
1111         @closed = @new_closed;
1112     }
1113
1114         my @successes;
1115         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1116
1117         my $target_when_closed = {};
1118         my $target_when_closed_if_at_pickup_lib = {};
1119
1120         for my $hold (@$holds) {
1121                 try {
1122                         #start a transaction if needed
1123                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1124                                 $log->debug("Cleaning up after previous transaction\n");
1125                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1126                         }
1127                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1128                         $log->info("Processing hold ".$hold->id."...\n");
1129
1130                         #first, re-fetch the hold, to make sure it's not captured already
1131                         $hold->remove_from_object_index();
1132                         $hold = action::hold_request->retrieve( $hold->id );
1133
1134                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1135
1136                         # remove old auto-targeting maps
1137                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1138                         $_->delete for (@oldmaps);
1139
1140                         if ($hold->expire_time) {
1141                                 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1142                                 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1143
1144                                         # cancel cause = un-targeted expiration
1145                                         $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1146
1147                                         # refresh fields from the DB while still in the xact
1148                                         my $fm_hold = $hold->to_fieldmapper; 
1149
1150                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1151
1152                                         # tell A/T the hold was cancelled
1153                                         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1154                                         $ses->request('open-ils.trigger.event.autocreate', 
1155                                                 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1156
1157                                         die "OK\n";
1158                                 }
1159                         }
1160
1161                         my $all_copies = [];
1162
1163                         # find filters for MR holds
1164                         my ($types, $formats, $lang);
1165                         if (defined($hold->holdable_formats)) {
1166                                 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1167                         }
1168
1169                         # find all the potential copies
1170                         if ($hold->hold_type eq 'M') {
1171                                 my $records = [
1172                                         map {
1173                                                 isTrue($_->deleted) ?  () : ($_->id)
1174                                         } metabib::metarecord->retrieve($hold->target)->source_records
1175                                 ];
1176                 if(@$records > 0) {
1177                                         for my $r ( map
1178                                                         {$_->record}
1179                                                         metabib::record_descriptor
1180                                                                 ->search(
1181                                                                         record => $records,
1182                                                                         ( $types   ? (item_type => [split '', $types])   : () ),
1183                                                                         ( $formats ? (item_form => [split '', $formats]) : () ),
1184                                                                         ( $lang    ? (item_lang => $lang)                                : () ),
1185                                                                 )
1186                                         ) {
1187                                                 my ($rtree) = $self
1188                                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1189                                                         ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1190
1191                                                 for my $cn ( @{ $rtree->call_numbers } ) {
1192                                                         push @$all_copies,
1193                                                                 asset::copy->search_where(
1194                                                                         { id => [map {$_->id} @{ $cn->copies }],
1195                                                                           deleted => 'f' }
1196                                                                 ) if ($cn && @{ $cn->copies });
1197                                                 }
1198                                         }
1199                                 }
1200                         } elsif ($hold->hold_type eq 'T') {
1201                                 my ($rtree) = $self
1202                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1203                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1204
1205                                 unless ($rtree) {
1206                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1207                                         die "OK\n";
1208                                 }
1209
1210                                 for my $cn ( @{ $rtree->call_numbers } ) {
1211                                         push @$all_copies,
1212                                                 asset::copy->search_where(
1213                                                         { id => [map {$_->id} @{ $cn->copies }],
1214                                                           deleted => 'f' }
1215                                                 ) if ($cn && @{ $cn->copies });
1216                                 }
1217                         } elsif ($hold->hold_type eq 'V') {
1218                                 my ($vtree) = $self
1219                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1220                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1221
1222                                 push @$all_copies,
1223                                         asset::copy->search_where(
1224                                                 { id => [map {$_->id} @{ $vtree->copies }],
1225                                                   deleted => 'f' }
1226                                         ) if ($vtree && @{ $vtree->copies });
1227
1228                         } elsif ($hold->hold_type eq 'P') {
1229                                 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1230                                 $all_copies = [
1231                                         asset::copy->search_where(
1232                                                 { id => [map {$_->target_copy} @part_maps],
1233                                                   deleted => 'f' }
1234                                         )
1235                                 ] if (@part_maps);
1236                                         
1237                         } elsif ($hold->hold_type eq 'I') {
1238                                 my ($itree) = $self
1239                                         ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1240                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1241
1242                                 push @$all_copies,
1243                                         asset::copy->search_where(
1244                                                 { id => [map {$_->unit->id} @{ $itree->items }],
1245                                                   deleted => 'f' }
1246                                         ) if ($itree && @{ $itree->items });
1247                                         
1248                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1249                                 my $_cp = asset::copy->retrieve($hold->target);
1250                                 push @$all_copies, $_cp if $_cp;
1251                         }
1252
1253             # Force and recall holds bypass pretty much everything
1254             if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1255                         # trim unholdables
1256                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1257                                                 isTrue($_->location->holdable) && 
1258                                                 isTrue($_->holdable) &&
1259                                                 !isTrue($_->deleted) &&
1260                                                 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1261                                                     ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1262                                         } @$all_copies;
1263             }
1264
1265                         # let 'em know we're still working
1266                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1267                         
1268                         # if we have no copies ...
1269                         if (!ref $all_copies || !@$all_copies) {
1270                                 $log->info("\tNo copies available for targeting at all!\n");
1271                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1272
1273                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1274                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1275                                 die "OK\n";
1276                         }
1277
1278                         my $copy_count = @$all_copies;
1279             my $found_copy = undef;
1280             $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1281
1282                         # map the potentials, so that we can pick up checkins
1283                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1284                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1285                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1286                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1287
1288                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1289
1290                         my @good_copies;
1291                         for my $c (@$all_copies) {
1292                                 # current target
1293                                 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1294
1295                                 # skip on circ lib is closed IFF we care
1296                                 my $ignore_closing;
1297
1298                                 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1299                                         $ignore_closing = ou_ancestor_setting_value_or_cache(
1300                         $actor,
1301                                                 ''.$c->circ_lib,
1302                                                 'circ.holds.target_when_closed_if_at_pickup_lib',
1303                                                 $target_when_closed_if_at_pickup_lib
1304                                         ) || 0;
1305                                 }
1306                                 if (not $ignore_closing) {  # one more chance to find a reason
1307                                                                                         # to ignore OU closedness.
1308                                         $ignore_closing = ou_ancestor_setting_value_or_cache(
1309                         $actor,
1310                                                 ''.$c->circ_lib,
1311                                                 'circ.holds.target_when_closed',
1312                                                 $target_when_closed
1313                                         ) || 0;
1314                                 }
1315
1316 #                               $logger->info(
1317 #                                       "For hold " . $hold->id . " and copy with circ_lib " .
1318 #                                       $c->circ_lib . " we " .
1319 #                                       ($ignore_closing ? "ignore" : "respect")
1320 #                                       . " closed dates"
1321 #                               );
1322
1323                                 next if (
1324                                         (not $ignore_closing) and
1325                                         (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1326                                 );
1327
1328                                 # target of another hold
1329                                 next if (action::hold_request
1330                                                 ->search_where(
1331                                                         { current_copy => $c->id,
1332                                                           fulfillment_time => undef,
1333                                                           cancel_time => undef,
1334                                                         }
1335                                                 )
1336                                 );
1337
1338                                 # we passed all three, keep it
1339                                 push @good_copies, $c if ($c);
1340                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1341                         }
1342
1343                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1344
1345                         my $old_best = $hold->current_copy;
1346                         my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1347                         $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1348                         $hold->update({ current_copy => undef }) if ($old_best);
1349         
1350                         if (!scalar(@good_copies)) {
1351                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1352                                 if ( $old_best_still_valid ) {
1353                                         # the old copy is still available
1354                                         $log->debug("\tPushing current_copy back onto the targeting list");
1355                                         push @good_copies, $old_best;
1356                                 } else {
1357                                         # oops, old copy is not available
1358                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1359                                         $hold->update( { prev_check_time => 'today' } );
1360                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1361                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1362                                         die "OK\n";
1363                                 }
1364                         }
1365
1366             my $pu_lib = ''.$hold->pickup_lib;
1367
1368                         my $prox_list = [];
1369                         $$prox_list[0] =
1370                         [
1371                                 grep {
1372                                         ''.$_->circ_lib eq $pu_lib &&
1373                     ( $_->status == 0 || $_->status == 7 )
1374                                 } @good_copies
1375                         ];
1376
1377                         $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1378                         # $all_copies is now a list of copies not at the pickup library
1379                         
1380             my $best;
1381             if  ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1382                 $best = $good_copies[0] if(scalar @good_copies);
1383             } else {
1384                 $best = choose_nearest_copy($hold, $prox_list);
1385             }
1386                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1387
1388                         if (!$best) {
1389                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1390
1391                                 $self->{max_loops}{$pu_lib} = $actor->request(
1392                                         'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1393                                 )->gather(1);
1394
1395                                 if (defined($self->{max_loops}{$pu_lib})) {
1396                                         $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1397
1398                                         my %circ_lib_map =  map { (''.$_->circ_lib => 1) } @$all_copies;
1399                                         my $circ_lib_list = [keys %circ_lib_map];
1400         
1401                                         my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1402         
1403                                         # Grab the "biggest" loop for this hold so far
1404                                         my $current_loop = $cstore->request(
1405                                                 'open-ils.cstore.json_query',
1406                                                 { distinct => 1,
1407                                                   select => { aufhmxl => ['max'] },
1408                                                   from => 'aufhmxl',
1409                                                   where => { hold => $hold->id}
1410                                                 }
1411                                         )->gather(1);
1412         
1413                                         $current_loop = $current_loop->{max} if ($current_loop);
1414                                         $current_loop ||= 1;
1415         
1416                                         my $exclude_list = $cstore->request(
1417                                                 'open-ils.cstore.json_query.atomic',
1418                                                 { distinct => 1,
1419                                                   select => { aufhol => ['circ_lib'] },
1420                                                   from => 'aufhol',
1421                                                   where => { hold => $hold->id}
1422                                                 }
1423                                         )->gather(1);
1424         
1425                                         my @keepers;
1426                                         if ($exclude_list && @$exclude_list) {
1427                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1428                                                 # check to see if we've used up every library in the potentials list
1429                                                 for my $l ( @$circ_lib_list ) {
1430                                                         my $keep = 1;
1431                                                         for my $ex ( @$exclude_list ) {
1432                                                                 if ($ex eq $l) {
1433                                                                         $keep = 0;
1434                                                                         last;
1435                                                                 }
1436                                                         }
1437                                                         push(@keepers, $l) if ($keep);
1438                                                 }
1439                                         } else {
1440                                                 @keepers = @$circ_lib_list;
1441                                         }
1442         
1443                                         $current_loop++ if (!@keepers);
1444         
1445                                         if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1446                                                 # We haven't exceeded max_loops yet
1447                                                 my @keeper_copies;
1448                                                 for my $cp ( @$all_copies ) {
1449                                                         push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1450
1451                                                 }
1452                                                 $all_copies = [@keeper_copies];
1453                                         } else {
1454                                                 # We have, and should remove potentials and cancel the hold
1455                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1456                                                 $_->delete for (@oldmaps);
1457
1458                                                 # cancel cause = un-targeted expiration
1459                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1460
1461                                                 # refresh fields from the DB while still in the xact
1462                                                 my $fm_hold = $hold->to_fieldmapper; 
1463
1464                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1465
1466                                                 # tell A/T the hold was cancelled
1467                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1468                                                 $ses->request('open-ils.trigger.event.autocreate', 
1469                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1470
1471                                                 die "OK\n";
1472                                         }
1473                                 }
1474
1475                                 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1476
1477                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1478
1479                                 $best = choose_nearest_copy($hold, $prox_list);
1480                         }
1481
1482                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1483                         if ($old_best) {
1484                                 # hold wasn't fulfilled, record the fact
1485                         
1486                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1487                                 action::unfulfilled_hold_list->create(
1488                                                 { hold => ''.$hold->id,
1489                                                   current_copy => ''.$old_best->id,
1490                                                   circ_lib => ''.$old_best->circ_lib,
1491                                                 });
1492                         }
1493
1494                         if ($best) {
1495                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1496                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1497                         } elsif (
1498                                 $old_best_still_valid &&
1499                                 !action::hold_request
1500                                         ->search_where(
1501                                                 { current_copy => $old_best->id,
1502                                                   fulfillment_time => undef,
1503                                                   cancel_time => undef,
1504                                                 }       
1505                                         ) &&
1506                                 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1507                                         { title => $old_best->call_number->record->to_fieldmapper,
1508                                           title_descriptor => $old_best->call_number->record->record_descriptor->next->to_fieldmapper,
1509                                           patron => $hold->usr->to_fieldmapper,
1510                                           copy => $old_best->to_fieldmapper,
1511                                           requestor => $hold->requestor->to_fieldmapper,
1512                                           request_lib => $hold->request_lib->to_fieldmapper,
1513                                           pickup_lib => $hold->pickup_lib->id,
1514                                           retarget => 1
1515                                         }
1516                                 ))
1517                         ) {     
1518                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1519                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1520                         } else {
1521                                 $hold->update( { prev_check_time => 'now' } );
1522                                 $log->info( "\tThere were no targetable copies for the hold" );
1523                                 process_recall($actor, $log, $hold, \@good_copies);
1524                         }
1525
1526                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1527                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1528
1529                         push @successes,
1530                                 { hold => $hold->id,
1531                                   old_target => ($old_best ? $old_best->id : undef),
1532                                   eligible_copies => $copy_count,
1533                                   target => ($best ? $best->id : undef),
1534                   found_copy => $found_copy };
1535
1536                 } otherwise {
1537                         my $e = shift;
1538                         if ($e !~ /^OK/o) {
1539                                 $log->error("Processing of hold failed:  $e");
1540                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1541                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1542                         }
1543                 };
1544         }
1545
1546         return \@successes;
1547 }
1548 __PACKAGE__->register_method(
1549         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1550         api_level       => 1,
1551         method          => 'new_hold_copy_targeter',
1552 );
1553
1554 sub process_recall {
1555     my ($actor, $log, $hold, $good_copies) = @_;
1556
1557     # Bail early if we don't have required settings to avoid spurious requests
1558     my ($recall_threshold, $return_interval, $fine_rules);
1559
1560     my $rv = $actor->request(
1561         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1562     )->gather(1);
1563
1564     if (!$rv) {
1565         $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1566         return;
1567     }
1568     $recall_threshold = $rv->{value};
1569
1570     $rv = $actor->request(
1571         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1572     )->gather(1);
1573
1574     if (!$rv) {
1575         $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1576         return;
1577     }
1578     $return_interval = $rv->{value};
1579
1580     $rv = $actor->request(
1581         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1582     )->gather(1);
1583
1584     if ($rv) {
1585         $fine_rules = $rv->{value};
1586     }
1587
1588     $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1589
1590     # We want checked out copies (status = 1) at the hold pickup lib
1591     my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1592
1593     my @copy_ids = map { $_->id } @$all_copies;
1594
1595     $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1596
1597     my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1598
1599     # Iterate over the checked-out copies to find a copy with a
1600     # loan period longer than the recall threshold:
1601     my $circs = [ action::circulation->search_where(
1602         { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1603         { order_by => 'due_date ASC' }
1604     )];
1605
1606     # If we have a candidate copy, then:
1607     if (scalar(@$circs)) {
1608         my $circ = $circs->[0];
1609         $log->info("Recalling circ ID : " . $circ->id);
1610
1611         # Give the user a new due date of either a full recall threshold,
1612         # or the return interval, whichever is further in the future
1613         my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1614         if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1615             $return_date = $threshold_date;
1616         }
1617
1618         my $update_fields = {
1619             due_date => $return_date,
1620             renewal_remaining => 0,
1621         };
1622
1623         # If the OU hasn't defined new fine rules for recalls, keep them
1624         # as they were
1625         if ($fine_rules) {
1626             $log->info("Apply recall fine rules: $fine_rules");
1627             my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1628             $update_fields->{recurring_fine} = $rules->[0];
1629             $update_fields->{fine_interval} = $rules->[1];
1630             $update_fields->{max_fine} = $rules->[2];
1631         }
1632
1633         # Adjust circ for current user
1634         $circ->update($update_fields);
1635
1636         # Create trigger event for notifying current user
1637         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1638         $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1639     }
1640
1641     $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1642 }
1643
1644 sub reservation_targeter {
1645         my $self = shift;
1646         my $client = shift;
1647         my $one_reservation = shift;
1648
1649         local $OpenILS::Application::Storage::WRITE = 1;
1650
1651         my $reservations;
1652
1653         try {
1654                 if ($one_reservation) {
1655                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1656                         $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1657                 } else {
1658
1659                         # find all the reservations needing targeting
1660                         $reservations = [
1661                 booking::reservation->search_where(
1662                                         { current_resource => undef,
1663                                           cancel_time => undef,
1664                                           start_time => { '>' => 'now' }
1665                     },
1666                     { order_by => 'start_time' }
1667                 )
1668             ];
1669                 }
1670         } catch Error with {
1671                 my $e = shift;
1672                 die "Could not retrieve reservation requests:\n\n$e\n";
1673         };
1674
1675         my @successes = ();
1676         for my $bresv (@$reservations) {
1677                 try {
1678                         #start a transaction if needed
1679                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1680                                 $log->debug("Cleaning up after previous transaction\n");
1681                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1682                         }
1683                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1684                         $log->info("Processing reservation ".$bresv->id."...\n");
1685
1686                         #first, re-fetch the hold, to make sure it's not captured already
1687                         $bresv->remove_from_object_index();
1688                         $bresv = booking::reservation->retrieve( $bresv->id );
1689
1690                         die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1691
1692                         my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1693                         if (DateTime->compare($end_time, DateTime->now) < 0) {
1694
1695                                 # cancel cause = un-targeted expiration
1696                                 $bresv->update( { cancel_time => 'now' } ); 
1697
1698                                 # refresh fields from the DB while still in the xact
1699                                 my $fm_bresv = $bresv->to_fieldmapper;
1700
1701                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1702
1703                                 # tell A/T the reservation was cancelled
1704                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1705                                 $ses->request('open-ils.trigger.event.autocreate', 
1706                                         'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1707
1708                                 die "OK\n";
1709                         }
1710
1711                         my $possible_resources;
1712
1713                         # find all the potential resources
1714                         if (!$bresv->target_resource) {
1715                                 my $filter = { type => $bresv->target_resource_type };
1716                                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1717
1718                                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1719
1720                                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1721                                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1722                                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1723                         } else {
1724                                 $possible_resources = $bresv->target_resource;
1725                         }
1726
1727             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1728                         @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1729
1730
1731             my @good_resources = ();
1732             my %conflicts = ();
1733             for my $res (@$all_resources) {
1734                 unless (isTrue($res->type->catalog_item)) {
1735                     push @good_resources, $res;
1736                     next;
1737                 }
1738
1739                 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1740
1741                 unless ($copy) {
1742                     push @good_resources, $res;
1743                     next;
1744                 }
1745
1746                 # At this point, if we're just targeting one specific
1747                 # resource, just succeed. We don't care about its present
1748                 # copy status.
1749                 if ($bresv->target_resource) {
1750                     push @good_resources, $res;
1751                     next;
1752                 }
1753
1754                 if ($copy->status->id == 0 || $copy->status->id == 7) {
1755                     push @good_resources, $res;
1756                     next;
1757                 }
1758
1759                 if ($copy->status->id == 1) {
1760                     my $circs = [ action::circulation->search_where(
1761                         {target_copy => $copy->id, checkin_time => undef },
1762                         { order_by => 'id DESC' }
1763                     ) ];
1764
1765                     if (@$circs) {
1766                         my $due_date = $circs->[0]->due_date;
1767                                     $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1768                                     my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1769                         if (DateTime->compare($start_time, $due_date) < 0) {
1770                             $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1771                             next;
1772                         }
1773
1774                         push @good_resources, $res;
1775                     }
1776
1777                     next;
1778                 }
1779
1780                 push @good_resources, $res if (isTrue($copy->status->holdable));
1781             }
1782
1783                         # let 'em know we're still working
1784                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1785                         
1786                         # if we have no copies ...
1787                         if (!@good_resources) {
1788                                 $log->info("\tNo resources available for targeting at all!\n");
1789                                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1790
1791
1792                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1793                                 die "OK\n";
1794                         }
1795
1796                         $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1797
1798                         my $prox_list = [];
1799                         $$prox_list[0] =
1800                         [
1801                                 grep {
1802                                         $_->owner == $bresv->pickup_lib
1803                                 } @good_resources
1804                         ];
1805
1806                         $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1807                         # $all_copies is now a list of copies not at the pickup library
1808
1809                         my $best = shift @good_resources;
1810                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1811
1812                         if (!$best) {
1813                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1814
1815                                 $prox_list =
1816                     map  { $_->[1] }
1817                     sort { $a->[0] <=> $b->[0] }
1818                     map  {
1819                         [   actor::org_unit_proximity->search_where(
1820                                 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1821                             )->[0]->prox,
1822                             $_
1823                         ]
1824                     } @$all_resources;
1825
1826                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1827
1828                                 $best = shift @$prox_list
1829                         }
1830
1831                         if ($best) {
1832                                 $bresv->update( { current_resource => ''.$best->id } );
1833                                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1834                         }
1835
1836                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1837                         $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1838
1839                         push @successes,
1840                                 { reservation => $bresv->id,
1841                                   current_resource => ($best ? $best->id : undef) };
1842
1843                 } otherwise {
1844                         my $e = shift;
1845                         if ($e !~ /^OK/o) {
1846                                 $log->error("Processing of bresv failed:  $e");
1847                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1848                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1849                         }
1850                 };
1851         }
1852
1853         return \@successes;
1854 }
1855 __PACKAGE__->register_method(
1856         api_name        => 'open-ils.storage.booking.reservation.resource_targeter',
1857         api_level       => 1,
1858         method          => 'reservation_targeter',
1859 );
1860
1861 my $locations;
1862 my $statuses;
1863 my %cache = (titles => {}, cns => {});
1864
1865 sub copy_hold_capture {
1866         my $self = shift;
1867         my $hold = shift;
1868         my $cps = shift;
1869
1870         if (!defined($cps)) {
1871                 try {
1872                         $cps = [ asset::copy->search( id => $hold->target ) ];
1873                 } catch Error with {
1874                         my $e = shift;
1875                         die "Could not retrieve initial volume list:\n\n$e\n";
1876                 };
1877         }
1878
1879         my @copies = grep { $_->holdable } @$cps;
1880
1881         for (my $i = 0; $i < @$cps; $i++) {
1882                 next unless $$cps[$i];
1883                 
1884                 my $cn = $cache{cns}{$copies[$i]->call_number};
1885                 my $rec = $cache{titles}{$cn->record};
1886                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1887                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1888                 $copies[$i] = undef if (
1889                         !$copies[$i] ||
1890                         !$self->{user_filter}->request(
1891                                 'open-ils.circ.permit_hold',
1892                                 $hold->to_fieldmapper, do {
1893                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1894                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1895                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1896                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1897                                         $cp_fm;
1898                                 },
1899                                 { title => $rec->to_fieldmapper,
1900                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1901                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1902                                 })->gather(1)
1903                 );
1904                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1905         }
1906
1907         @copies = grep { $_ } @copies;
1908
1909         my $count = @copies;
1910
1911         return unless ($count);
1912         
1913         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1914         
1915         my @maps;
1916         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1917         for my $c (@copies) {
1918                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1919         }
1920         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1921
1922         return \@copies;
1923 }
1924
1925
1926 sub choose_nearest_copy {
1927         my $hold = shift;
1928         my $prox_list = shift;
1929
1930         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1931                 next unless (ref $$prox_list[$p]);
1932
1933                 my @capturable = @{ $$prox_list[$p] };
1934                 next unless (@capturable);
1935
1936                 my $rand = int(rand(scalar(@capturable)));
1937                 my %seen = ();
1938                 while (my ($c) = splice(@capturable, $rand, 1)) {
1939                         return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1940                                 { title => $c->call_number->record->to_fieldmapper,
1941                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1942                                   patron => $hold->usr->to_fieldmapper,
1943                                   copy => $c->to_fieldmapper,
1944                                   requestor => $hold->requestor->to_fieldmapper,
1945                                   request_lib => $hold->request_lib->to_fieldmapper,
1946                                   pickup_lib => $hold->pickup_lib->id,
1947                                   retarget => 1
1948                                 }
1949                         ));
1950                         $seen{$c->id}++;
1951
1952                         last unless(@capturable);
1953                         $rand = int(rand(scalar(@capturable)));
1954                 }
1955         }
1956 }
1957
1958 sub create_prox_list {
1959         my $self = shift;
1960         my $lib = shift;
1961         my $copies = shift;
1962
1963         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1964
1965         my @prox_list;
1966         for my $cp (@$copies) {
1967                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1968                 next unless (defined($prox));
1969
1970         my $copy_circ_lib = ''.$cp->circ_lib;
1971                 # Fetch the weighting value for hold targeting, defaulting to 1
1972                 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1973                         'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1974                 )->gather(1);
1975         $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1976         $self->{target_weight}{$copy_circ_lib} ||= 1;
1977
1978                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1979                 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1980                         push @{$prox_list[$prox]}, $cp;
1981                 }
1982         }
1983         return \@prox_list;
1984 }
1985
1986 sub volume_hold_capture {
1987         my $self = shift;
1988         my $hold = shift;
1989         my $vols = shift;
1990
1991         if (!defined($vols)) {
1992                 try {
1993                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1994                         $cache{cns}{$_->id} = $_ for (@$vols);
1995                 } catch Error with {
1996                         my $e = shift;
1997                         die "Could not retrieve initial volume list:\n\n$e\n";
1998                 };
1999         }
2000
2001         my @v_ids = map { $_->id } @$vols;
2002
2003         my $cp_list;
2004         try {
2005                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2006         
2007         } catch Error with {
2008                 my $e = shift;
2009                 warn "Could not retrieve copy list:\n\n$e\n";
2010         };
2011
2012         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2013 }
2014
2015 sub title_hold_capture {
2016         my $self = shift;
2017         my $hold = shift;
2018         my $titles = shift;
2019
2020         if (!defined($titles)) {
2021                 try {
2022                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2023                         $cache{titles}{$_->id} = $_ for (@$titles);
2024                 } catch Error with {
2025                         my $e = shift;
2026                         die "Could not retrieve initial title list:\n\n$e\n";
2027                 };
2028         }
2029
2030         my @t_ids = map { $_->id } @$titles;
2031         my $cn_list;
2032         try {
2033                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2034         
2035         } catch Error with {
2036                 my $e = shift;
2037                 warn "Could not retrieve volume list:\n\n$e\n";
2038         };
2039
2040         $cache{cns}{$_->id} = $_ for (@$cn_list);
2041
2042         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2043 }
2044
2045 sub metarecord_hold_capture {
2046         my $self = shift;
2047         my $hold = shift;
2048
2049         my $titles;
2050         try {
2051                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2052         
2053         } catch Error with {
2054                 my $e = shift;
2055                 die "Could not retrieve initial title list:\n\n$e\n";
2056         };
2057
2058         try {
2059                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
2060
2061                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2062         
2063         } catch Error with {
2064                 my $e = shift;
2065                 die "Could not retrieve format-pruned title list:\n\n$e\n";
2066         };
2067
2068
2069         $cache{titles}{$_->id} = $_ for (@$titles);
2070         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
2071 }
2072
2073 1;