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