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