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