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