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