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