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