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