]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/action.pm
d58e213627e40f86ca07e60807da5ac74361f7c0
[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 $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
350     $client->respond( $_ ) for ( $sth->fetchall_arrayref );
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 => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, 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 => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, 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 => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, 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                                 for my $r ( map
1155                                                 {$_->record}
1156                                                 metabib::record_descriptor
1157                                                         ->search(
1158                                                                 record => [
1159                                                                         map {
1160                                                                                 isTrue($_->deleted) ?  () : ($_->id)
1161                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
1162                                                                 ],
1163                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
1164                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
1165                                                                 ( $lang    ? (item_lang => $lang)                                : () ),
1166                                                         )
1167                                 ) {
1168                                         my ($rtree) = $self
1169                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1170                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1171
1172                                         for my $cn ( @{ $rtree->call_numbers } ) {
1173                                                 push @$all_copies,
1174                                                         asset::copy->search_where(
1175                                                                 { id => [map {$_->id} @{ $cn->copies }],
1176                                                                   deleted => 'f' }
1177                                                         ) if ($cn && @{ $cn->copies });
1178                                         }
1179                                 }
1180                         } elsif ($hold->hold_type eq 'T') {
1181                                 my ($rtree) = $self
1182                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1183                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1184
1185                                 unless ($rtree) {
1186                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1187                                         die "OK\n";
1188                                 }
1189
1190                                 for my $cn ( @{ $rtree->call_numbers } ) {
1191                                         push @$all_copies,
1192                                                 asset::copy->search_where(
1193                                                         { id => [map {$_->id} @{ $cn->copies }],
1194                                                           deleted => 'f' }
1195                                                 ) if ($cn && @{ $cn->copies });
1196                                 }
1197                         } elsif ($hold->hold_type eq 'V') {
1198                                 my ($vtree) = $self
1199                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1200                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1201
1202                                 push @$all_copies,
1203                                         asset::copy->search_where(
1204                                                 { id => [map {$_->id} @{ $vtree->copies }],
1205                                                   deleted => 'f' }
1206                                         ) if ($vtree && @{ $vtree->copies });
1207
1208                         } elsif ($hold->hold_type eq 'P') {
1209                                 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1210                                 $all_copies = [
1211                                         asset::copy->search_where(
1212                                                 { id => [map {$_->target_copy} @part_maps],
1213                                                   deleted => 'f' }
1214                                         )
1215                                 ] if (@part_maps);
1216                                         
1217                         } elsif ($hold->hold_type eq 'I') {
1218                                 my ($itree) = $self
1219                                         ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1220                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1221
1222                                 push @$all_copies,
1223                                         asset::copy->search_where(
1224                                                 { id => [map {$_->unit->id} @{ $itree->items }],
1225                                                   deleted => 'f' }
1226                                         ) if ($itree && @{ $itree->items });
1227                                         
1228                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1229                                 my $_cp = asset::copy->retrieve($hold->target);
1230                                 push @$all_copies, $_cp if $_cp;
1231                         }
1232
1233                         # trim unholdables
1234                         @$all_copies = grep {   isTrue($_->status->holdable) && 
1235                                                 isTrue($_->location->holdable) && 
1236                                                 isTrue($_->holdable) &&
1237                                                 !isTrue($_->deleted) &&
1238                                                 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1239                                                 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1240                                         } @$all_copies;
1241
1242                         # let 'em know we're still working
1243                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1244                         
1245                         # if we have no copies ...
1246                         if (!ref $all_copies || !@$all_copies) {
1247                                 $log->info("\tNo copies available for targeting at all!\n");
1248                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1249
1250                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1251                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1252                                 die "OK\n";
1253                         }
1254
1255                         my $copy_count = @$all_copies;
1256             my $found_copy = undef;
1257             $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1258
1259                         # map the potentials, so that we can pick up checkins
1260                         # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1261                         # XXX the potentials list.  If this is the cased, hold_copy_map creation will move down further.
1262                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1263                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1264
1265                         #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1266
1267                         my @good_copies;
1268                         for my $c (@$all_copies) {
1269                                 # current target
1270                                 next if ($c->id eq $hold->current_copy);
1271
1272                                 # skip on circ lib is closed IFF we care
1273                                 my $ignore_closing;
1274
1275                                 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1276                                         $ignore_closing = ou_ancestor_setting_value_or_cache(
1277                         $actor,
1278                                                 ''.$c->circ_lib,
1279                                                 'circ.holds.target_when_closed_if_at_pickup_lib',
1280                                                 $target_when_closed_if_at_pickup_lib
1281                                         ) || 0;
1282                                 }
1283                                 if (not $ignore_closing) {  # one more chance to find a reason
1284                                                                                         # to ignore OU closedness.
1285                                         $ignore_closing = ou_ancestor_setting_value_or_cache(
1286                         $actor,
1287                                                 ''.$c->circ_lib,
1288                                                 'circ.holds.target_when_closed',
1289                                                 $target_when_closed
1290                                         ) || 0;
1291                                 }
1292
1293 #                               $logger->info(
1294 #                                       "For hold " . $hold->id . " and copy with circ_lib " .
1295 #                                       $c->circ_lib . " we " .
1296 #                                       ($ignore_closing ? "ignore" : "respect")
1297 #                                       . " closed dates"
1298 #                               );
1299
1300                                 next if (
1301                                         (not $ignore_closing) and
1302                                         (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1303                                 );
1304
1305                                 # target of another hold
1306                                 next if (action::hold_request
1307                                                 ->search_where(
1308                                                         { current_copy => $c->id,
1309                                                           fulfillment_time => undef,
1310                                                           cancel_time => undef,
1311                                                         }
1312                                                 )
1313                                 );
1314
1315                                 # we passed all three, keep it
1316                                 push @good_copies, $c if ($c);
1317                                 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1318                         }
1319
1320                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1321
1322                         my $old_best = $hold->current_copy;
1323                         $hold->update({ current_copy => undef }) if ($old_best);
1324         
1325                         if (!scalar(@good_copies)) {
1326                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1327                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1328                                         # the old copy is still available
1329                                         $log->debug("\tPushing current_copy back onto the targeting list");
1330                                         push @good_copies, $old_best;
1331                                 } else {
1332                                         # oops, old copy is not available
1333                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1334                                         $hold->update( { prev_check_time => 'today' } );
1335                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1336                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1337                                         die "OK\n";
1338                                 }
1339                         }
1340
1341             my $pu_lib = ''.$hold->pickup_lib;
1342
1343                         my $prox_list = [];
1344                         $$prox_list[0] =
1345                         [
1346                                 grep {
1347                                         ''.$_->circ_lib eq $pu_lib &&
1348                     ( $_->status == 0 || $_->status == 7 )
1349                                 } @good_copies
1350                         ];
1351
1352                         $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1353                         # $all_copies is now a list of copies not at the pickup library
1354
1355                         my $best = choose_nearest_copy($hold, $prox_list);
1356                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1357
1358                         if (!$best) {
1359                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1360
1361                                 $self->{max_loops}{$pu_lib} = $actor->request(
1362                                         'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1363                                 )->gather(1);
1364
1365                                 if (defined($self->{max_loops}{$pu_lib})) {
1366                                         $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1367
1368                                         my %circ_lib_map =  map { (''.$_->circ_lib => 1) } @$all_copies;
1369                                         my $circ_lib_list = [keys %circ_lib_map];
1370         
1371                                         my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1372         
1373                                         # Grab the "biggest" loop for this hold so far
1374                                         my $current_loop = $cstore->request(
1375                                                 'open-ils.cstore.json_query',
1376                                                 { distinct => 1,
1377                                                   select => { aufhmxl => ['max'] },
1378                                                   from => 'aufhmxl',
1379                                                   where => { hold => $hold->id}
1380                                                 }
1381                                         )->gather(1);
1382         
1383                                         $current_loop = $current_loop->{max} if ($current_loop);
1384                                         $current_loop ||= 1;
1385         
1386                                         my $exclude_list = $cstore->request(
1387                                                 'open-ils.cstore.json_query.atomic',
1388                                                 { distinct => 1,
1389                                                   select => { aufhol => ['circ_lib'] },
1390                                                   from => 'aufhol',
1391                                                   where => { hold => $hold->id}
1392                                                 }
1393                                         )->gather(1);
1394         
1395                                         my @keepers;
1396                                         if ($exclude_list && @$exclude_list) {
1397                                                 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1398                                                 # check to see if we've used up every library in the potentials list
1399                                                 for my $l ( @$circ_lib_list ) {
1400                                                         my $keep = 1;
1401                                                         for my $ex ( @$exclude_list ) {
1402                                                                 if ($ex eq $l) {
1403                                                                         $keep = 0;
1404                                                                         last;
1405                                                                 }
1406                                                         }
1407                                                         push(@keepers, $l) if ($keep);
1408                                                 }
1409                                         } else {
1410                                                 @keepers = @$circ_lib_list;
1411                                         }
1412         
1413                                         $current_loop++ if (!@keepers);
1414         
1415                                         if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1416                                                 # We haven't exceeded max_loops yet
1417                                                 my @keeper_copies;
1418                                                 for my $cp ( @$all_copies ) {
1419                                                         push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1420
1421                                                 }
1422                                                 $all_copies = [@keeper_copies];
1423                                         } else {
1424                                                 # We have, and should remove potentials and cancel the hold
1425                                                 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1426                                                 $_->delete for (@oldmaps);
1427
1428                                                 # cancel cause = un-targeted expiration
1429                                                 $hold->update( { cancel_time => 'now', cancel_cause => 1 } ); 
1430                                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1431
1432                                                 # tell A/T the hold was cancelled
1433                                                 my $fm_hold = $hold->to_fieldmapper;
1434                                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1435                                                 $ses->request('open-ils.trigger.event.autocreate', 
1436                                                         'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1437
1438                                                 die "OK\n";
1439                                         }
1440                                 }
1441
1442                                 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1443
1444                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1445
1446                                 $best = choose_nearest_copy($hold, $prox_list);
1447                         }
1448
1449                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1450                         if ($old_best) {
1451                                 # hold wasn't fulfilled, record the fact
1452                         
1453                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1454                                 action::unfulfilled_hold_list->create(
1455                                                 { hold => ''.$hold->id,
1456                                                   current_copy => ''.$old_best->id,
1457                                                   circ_lib => ''.$old_best->circ_lib,
1458                                                 });
1459                         }
1460
1461                         if ($best) {
1462                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1463                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1464                         } elsif (
1465                                 $old_best &&
1466                                 !action::hold_request
1467                                         ->search_where(
1468                                                 { current_copy => $old_best->id,
1469                                                   fulfillment_time => undef,
1470                                                   cancel_time => undef,
1471                                                 }       
1472                                         )
1473                         ) {     
1474                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1475                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1476                         } else {
1477                                 $hold->update( { prev_check_time => 'now' } );
1478                                 $log->info( "\tThere were no targetable copies for the hold" );
1479                                 process_recall($actor, $log, $hold, \@good_copies);
1480                         }
1481
1482                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1483                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1484
1485                         push @successes,
1486                                 { hold => $hold->id,
1487                                   old_target => ($old_best ? $old_best->id : undef),
1488                                   eligible_copies => $copy_count,
1489                                   target => ($best ? $best->id : undef),
1490                   found_copy => $found_copy };
1491
1492                 } otherwise {
1493                         my $e = shift;
1494                         if ($e !~ /^OK/o) {
1495                                 $log->error("Processing of hold failed:  $e");
1496                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1497                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1498                         }
1499                 };
1500         }
1501
1502         return \@successes;
1503 }
1504 __PACKAGE__->register_method(
1505         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1506         api_level       => 1,
1507         method          => 'new_hold_copy_targeter',
1508 );
1509
1510 sub process_recall {
1511     my ($actor, $log, $hold, $good_copies) = @_;
1512
1513     # Bail early if we don't have required settings to avoid spurious requests
1514     my ($recall_threshold, $return_interval, $fine_rules);
1515
1516     my $rv = $actor->request(
1517         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1518     )->gather(1);
1519
1520     if (!$rv) {
1521         $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1522         return;
1523     }
1524     $recall_threshold = $rv->{value};
1525
1526     $rv = $actor->request(
1527         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1528     )->gather(1);
1529
1530     if (!$rv) {
1531         $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1532         return;
1533     }
1534     $return_interval = $rv->{value};
1535
1536     $rv = $actor->request(
1537         'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1538     )->gather(1);
1539
1540     if ($rv) {
1541         $fine_rules = $rv->{value};
1542     }
1543
1544     $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1545
1546     # We want checked out copies (status = 1) at the hold pickup lib
1547     my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1548
1549     my @copy_ids = map { $_->id } @$all_copies;
1550
1551     $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1552
1553     my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1554
1555     # Iterate over the checked-out copies to find a copy with a
1556     # loan period longer than the recall threshold:
1557     my $circs = [ action::circulation->search_where(
1558         { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1559         { order_by => 'due_date ASC' }
1560     )];
1561
1562     # If we have a candidate copy, then:
1563     if (scalar(@$circs)) {
1564         my $circ = $circs->[0];
1565         $log->info("Recalling circ ID : " . $circ->id);
1566
1567         # Give the user a new due date of either a full recall threshold,
1568         # or the return interval, whichever is further in the future
1569         my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1570         if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1571             $return_date = $threshold_date;
1572         }
1573
1574         my $update_fields = {
1575             due_date => $return_date,
1576             renewal_remaining => 0,
1577         };
1578
1579         # If the OU hasn't defined new fine rules for recalls, keep them
1580         # as they were
1581         if ($fine_rules) {
1582             $log->info("Apply recall fine rules: $fine_rules");
1583             my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1584             $update_fields->{recurring_fine} = $rules->[0];
1585             $update_fields->{fine_interval} = $rules->[1];
1586             $update_fields->{max_fine} = $rules->[2];
1587         }
1588
1589         # Adjust circ for current user
1590         $circ->update($update_fields);
1591
1592         # Create trigger event for notifying current user
1593         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1594         $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1595     }
1596
1597     $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1598 }
1599
1600 sub reservation_targeter {
1601         my $self = shift;
1602         my $client = shift;
1603         my $one_reservation = shift;
1604
1605         local $OpenILS::Application::Storage::WRITE = 1;
1606
1607         my $reservations;
1608
1609         try {
1610                 if ($one_reservation) {
1611                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1612                         $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1613                 } else {
1614
1615                         # find all the reservations needing targeting
1616                         $reservations = [
1617                 booking::reservation->search_where(
1618                                         { current_resource => undef,
1619                                           cancel_time => undef,
1620                                           start_time => { '>' => 'now' }
1621                     },
1622                     { order_by => 'start_time' }
1623                 )
1624             ];
1625                 }
1626         } catch Error with {
1627                 my $e = shift;
1628                 die "Could not retrieve reservation requests:\n\n$e\n";
1629         };
1630
1631         my @successes = ();
1632         for my $bresv (@$reservations) {
1633                 try {
1634                         #start a transaction if needed
1635                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1636                                 $log->debug("Cleaning up after previous transaction\n");
1637                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1638                         }
1639                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1640                         $log->info("Processing reservation ".$bresv->id."...\n");
1641
1642                         #first, re-fetch the hold, to make sure it's not captured already
1643                         $bresv->remove_from_object_index();
1644                         $bresv = booking::reservation->retrieve( $bresv->id );
1645
1646                         die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1647
1648                         my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1649                         if (DateTime->compare($end_time, DateTime->now) < 0) {
1650
1651                                 # cancel cause = un-targeted expiration
1652                                 $bresv->update( { cancel_time => 'now' } ); 
1653                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1654
1655                                 # tell A/T the reservation was cancelled
1656                                 my $fm_bresv = $bresv->to_fieldmapper;
1657                                 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1658                                 $ses->request('open-ils.trigger.event.autocreate', 
1659                                         'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1660
1661                                 die "OK\n";
1662                         }
1663
1664                         my $possible_resources;
1665
1666                         # find all the potential resources
1667                         if (!$bresv->target_resource) {
1668                                 my $filter = { type => $bresv->target_resource_type };
1669                                 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1670
1671                                 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1672
1673                                 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1674                                 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1675                                 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1676                         } else {
1677                                 $possible_resources = $bresv->target_resource;
1678                         }
1679
1680             my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1681                         @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1682
1683
1684             my @good_resources = ();
1685             my %conflicts = ();
1686             for my $res (@$all_resources) {
1687                 unless (isTrue($res->type->catalog_item)) {
1688                     push @good_resources, $res;
1689                     next;
1690                 }
1691
1692                 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1693
1694                 unless ($copy) {
1695                     push @good_resources, $res;
1696                     next;
1697                 }
1698
1699                 # At this point, if we're just targeting one specific
1700                 # resource, just succeed. We don't care about its present
1701                 # copy status.
1702                 if ($bresv->target_resource) {
1703                     push @good_resources, $res;
1704                     next;
1705                 }
1706
1707                 if ($copy->status->id == 0 || $copy->status->id == 7) {
1708                     push @good_resources, $res;
1709                     next;
1710                 }
1711
1712                 if ($copy->status->id == 1) {
1713                     my $circs = [ action::circulation->search_where(
1714                         {target_copy => $copy->id, checkin_time => undef },
1715                         { order_by => 'id DESC' }
1716                     ) ];
1717
1718                     if (@$circs) {
1719                         my $due_date = $circs->[0]->due_date;
1720                                     $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1721                                     my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1722                         if (DateTime->compare($start_time, $due_date) < 0) {
1723                             $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1724                             next;
1725                         }
1726
1727                         push @good_resources, $res;
1728                     }
1729
1730                     next;
1731                 }
1732
1733                 push @good_resources, $res if (isTrue($copy->status->holdable));
1734             }
1735
1736                         # let 'em know we're still working
1737                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1738                         
1739                         # if we have no copies ...
1740                         if (!@good_resources) {
1741                                 $log->info("\tNo resources available for targeting at all!\n");
1742                                 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1743
1744
1745                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1746                                 die "OK\n";
1747                         }
1748
1749                         $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1750
1751                         my $prox_list = [];
1752                         $$prox_list[0] =
1753                         [
1754                                 grep {
1755                                         $_->owner == $bresv->pickup_lib
1756                                 } @good_resources
1757                         ];
1758
1759                         $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1760                         # $all_copies is now a list of copies not at the pickup library
1761
1762                         my $best = shift @good_resources;
1763                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1764
1765                         if (!$best) {
1766                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1767
1768                                 $prox_list =
1769                     map  { $_->[1] }
1770                     sort { $a->[0] <=> $b->[0] }
1771                     map  {
1772                         [   actor::org_unit_proximity->search_where(
1773                                 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1774                             )->[0]->prox,
1775                             $_
1776                         ]
1777                     } @$all_resources;
1778
1779                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1780
1781                                 $best = shift @$prox_list
1782                         }
1783
1784                         if ($best) {
1785                                 $bresv->update( { current_resource => ''.$best->id } );
1786                                 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1787                         }
1788
1789                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1790                         $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1791
1792                         push @successes,
1793                                 { reservation => $bresv->id,
1794                                   current_resource => ($best ? $best->id : undef) };
1795
1796                 } otherwise {
1797                         my $e = shift;
1798                         if ($e !~ /^OK/o) {
1799                                 $log->error("Processing of bresv failed:  $e");
1800                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1801                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1802                         }
1803                 };
1804         }
1805
1806         return \@successes;
1807 }
1808 __PACKAGE__->register_method(
1809         api_name        => 'open-ils.storage.booking.reservation.resource_targeter',
1810         api_level       => 1,
1811         method          => 'reservation_targeter',
1812 );
1813
1814 my $locations;
1815 my $statuses;
1816 my %cache = (titles => {}, cns => {});
1817
1818 sub copy_hold_capture {
1819         my $self = shift;
1820         my $hold = shift;
1821         my $cps = shift;
1822
1823         if (!defined($cps)) {
1824                 try {
1825                         $cps = [ asset::copy->search( id => $hold->target ) ];
1826                 } catch Error with {
1827                         my $e = shift;
1828                         die "Could not retrieve initial volume list:\n\n$e\n";
1829                 };
1830         }
1831
1832         my @copies = grep { $_->holdable } @$cps;
1833
1834         for (my $i = 0; $i < @$cps; $i++) {
1835                 next unless $$cps[$i];
1836                 
1837                 my $cn = $cache{cns}{$copies[$i]->call_number};
1838                 my $rec = $cache{titles}{$cn->record};
1839                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1840                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1841                 $copies[$i] = undef if (
1842                         !$copies[$i] ||
1843                         !$self->{user_filter}->request(
1844                                 'open-ils.circ.permit_hold',
1845                                 $hold->to_fieldmapper, do {
1846                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1847                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1848                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1849                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1850                                         $cp_fm;
1851                                 },
1852                                 { title => $rec->to_fieldmapper,
1853                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1854                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1855                                 })->gather(1)
1856                 );
1857                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1858         }
1859
1860         @copies = grep { $_ } @copies;
1861
1862         my $count = @copies;
1863
1864         return unless ($count);
1865         
1866         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1867         
1868         my @maps;
1869         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1870         for my $c (@copies) {
1871                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1872         }
1873         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1874
1875         return \@copies;
1876 }
1877
1878
1879 sub choose_nearest_copy {
1880         my $hold = shift;
1881         my $prox_list = shift;
1882
1883         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1884                 next unless (ref $$prox_list[$p]);
1885
1886                 my @capturable = @{ $$prox_list[$p] };
1887                 next unless (@capturable);
1888
1889                 my $rand = int(rand(scalar(@capturable)));
1890                 my %seen = ();
1891                 while (my ($c) = splice(@capturable, $rand, 1)) {
1892                         return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1893                                 { title => $c->call_number->record->to_fieldmapper,
1894                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1895                                   patron => $hold->usr->to_fieldmapper,
1896                                   copy => $c->to_fieldmapper,
1897                                   requestor => $hold->requestor->to_fieldmapper,
1898                                   request_lib => $hold->request_lib->to_fieldmapper,
1899                                   pickup_lib => $hold->pickup_lib->id,
1900                                   retarget => 1
1901                                 }
1902                         ));
1903                         $seen{$c->id}++;
1904
1905                         last unless(@capturable);
1906                         $rand = int(rand(scalar(@capturable)));
1907                 }
1908         }
1909 }
1910
1911 sub create_prox_list {
1912         my $self = shift;
1913         my $lib = shift;
1914         my $copies = shift;
1915
1916         my $actor = OpenSRF::AppSession->create('open-ils.actor');
1917
1918         my @prox_list;
1919         for my $cp (@$copies) {
1920                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1921                 next unless (defined($prox));
1922
1923         my $copy_circ_lib = ''.$cp->circ_lib;
1924                 # Fetch the weighting value for hold targeting, defaulting to 1
1925                 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1926                         'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1927                 )->gather(1);
1928         $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1929         $self->{target_weight}{$copy_circ_lib} ||= 1;
1930
1931                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1932                 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1933                         push @{$prox_list[$prox]}, $cp;
1934                 }
1935         }
1936         return \@prox_list;
1937 }
1938
1939 sub volume_hold_capture {
1940         my $self = shift;
1941         my $hold = shift;
1942         my $vols = shift;
1943
1944         if (!defined($vols)) {
1945                 try {
1946                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1947                         $cache{cns}{$_->id} = $_ for (@$vols);
1948                 } catch Error with {
1949                         my $e = shift;
1950                         die "Could not retrieve initial volume list:\n\n$e\n";
1951                 };
1952         }
1953
1954         my @v_ids = map { $_->id } @$vols;
1955
1956         my $cp_list;
1957         try {
1958                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1959         
1960         } catch Error with {
1961                 my $e = shift;
1962                 warn "Could not retrieve copy list:\n\n$e\n";
1963         };
1964
1965         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1966 }
1967
1968 sub title_hold_capture {
1969         my $self = shift;
1970         my $hold = shift;
1971         my $titles = shift;
1972
1973         if (!defined($titles)) {
1974                 try {
1975                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1976                         $cache{titles}{$_->id} = $_ for (@$titles);
1977                 } catch Error with {
1978                         my $e = shift;
1979                         die "Could not retrieve initial title list:\n\n$e\n";
1980                 };
1981         }
1982
1983         my @t_ids = map { $_->id } @$titles;
1984         my $cn_list;
1985         try {
1986                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1987         
1988         } catch Error with {
1989                 my $e = shift;
1990                 warn "Could not retrieve volume list:\n\n$e\n";
1991         };
1992
1993         $cache{cns}{$_->id} = $_ for (@$cn_list);
1994
1995         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1996 }
1997
1998 sub metarecord_hold_capture {
1999         my $self = shift;
2000         my $hold = shift;
2001
2002         my $titles;
2003         try {
2004                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2005         
2006         } catch Error with {
2007                 my $e = shift;
2008                 die "Could not retrieve initial title list:\n\n$e\n";
2009         };
2010
2011         try {
2012                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
2013
2014                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2015         
2016         } catch Error with {
2017                 my $e = shift;
2018                 die "Could not retrieve format-pruned title list:\n\n$e\n";
2019         };
2020
2021
2022         $cache{titles}{$_->id} = $_ for (@$titles);
2023         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
2024 }
2025
2026 1;