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