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