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