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