015d4bc9f50841ca305f2a62c776e3c6fee82314
[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
12 sub isTrue {
13         my $v = shift;
14         return 1 if ($v == 1);
15         return 1 if ($v =~ /^t/io);
16         return 1 if ($v =~ /^y/io);
17         return 0;
18 }
19
20 my $parser = DateTime::Format::ISO8601->new;
21 my $log = 'OpenSRF::Utils::Logger';
22
23 sub open_noncat_circs {
24         my $self = shift;
25         my $client = shift;
26         my $user = shift;
27
28         my $a = action::non_cataloged_circulation->table;
29         my $c = config::non_cataloged_type->table;
30
31         my $sql = <<"   SQL";
32                 SELECT  a.id
33                   FROM  $a a
34                         JOIN $c c ON (a.item_type = c.id)
35                   WHERE a.circ_time + c.circ_duration > current_timestamp
36                         AND a.patron = ?
37         SQL
38
39         return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
40 }
41 __PACKAGE__->register_method(
42         api_name        => 'open-ils.storage.action.open_non_cataloged_circulation.user',
43         api_level       => 1,
44         argc            => 1,
45         method          => 'open_noncat_circs',
46 );
47
48
49 sub ou_hold_requests {
50         my $self = shift;
51         my $client = shift;
52         my $ou = shift;
53
54         my $h_table = action::hold_request->table;
55         my $c_table = asset::copy->table;
56         my $o_table = actor::org_unit->table;
57
58         my $SQL = <<"   SQL";
59                 SELECT  h.id
60                   FROM  $h_table h
61                         JOIN $c_table cp ON (cp.id = h.current_copy)
62                         JOIN $o_table ou ON (ou.id = cp.circ_lib)
63                   WHERE ou.id = ?
64                         AND h.capture_time IS NULL
65                         AND h.cancel_time IS NULL
66                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
67                   ORDER BY h.request_time
68         SQL
69
70         my $sth = action::hold_request->db_Main->prepare_cached($SQL);
71         $sth->execute($ou);
72
73         $client->respond($_) for (
74                 map {
75                         $self
76                                 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
77                                 ->run($_)
78                 } map {
79                         $_->[0]
80                 } @{ $sth->fetchall_arrayref }
81         );
82         return undef;
83 }
84 __PACKAGE__->register_method(
85         api_name        => 'open-ils.storage.action.targeted_hold_request.org_unit',
86         api_level       => 1,
87         argc            => 1,
88         stream          => 1,
89         method          => 'ou_hold_requests',
90 );
91
92
93 sub overdue_circs {
94         my $grace = shift;
95
96         my $c_t = action::circulation->table;
97
98         $grace = " - ($grace * (fine_interval))" if ($grace);
99
100         my $sql = <<"   SQL";
101                 SELECT  *
102                   FROM  $c_t
103                   WHERE stop_fines IS NULL
104                         AND due_date < ( CURRENT_TIMESTAMP $grace)
105         SQL
106
107         my $sth = action::circulation->db_Main->prepare_cached($sql);
108         $sth->execute;
109
110         return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
111
112 }
113
114 sub complete_reshelving {
115         my $self = shift;
116         my $client = shift;
117         my $window = shift;
118
119         local $OpenILS::Application::Storage::WRITE = 1;
120
121         throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
122                 unless (interval_to_seconds( $window ));
123
124         my $circ = action::circulation->table;
125         my $cp = asset::copy->table;
126
127         my $sql = <<"   SQL";
128                 UPDATE  $cp
129                   SET   status = 0
130                   WHERE id IN
131                         ( SELECT id FROM (
132                                 SELECT  cp.id, MAX(circ.checkin_time)
133                                   FROM  $cp cp
134                                         JOIN $circ circ ON (circ.target_copy = cp.id)
135                                   WHERE circ.checkin_time IS NOT NULL
136                                         AND cp.status = 7
137                                   GROUP BY 1
138                                         HAVING MAX(circ.checkin_time) < NOW() - CAST(? AS INTERVAL)
139                           ) AS foo
140                         )
141                         OR id IN
142                         ( SELECT        cp.id
143                             FROM        $cp cp 
144                                         LEFT JOIN $circ circ ON (circ.target_copy = cp.id AND circ.id IS NULL)
145                             WHERE       cp.status = 7
146                                         AND cp.create_date < NOW() - CAST(? AS INTERVAL)
147                         )
148         SQL
149
150         my $sth = action::circulation->db_Main->prepare_cached($sql);
151         $sth->execute($window, $window);
152
153         return $sth->rows;
154
155 }
156 __PACKAGE__->register_method(
157         api_name        => 'open-ils.storage.action.circulation.reshelving.complete',
158         api_level       => 1,
159         stream          => 1,
160         argc            => 1,
161         method          => 'complete_reshelving',
162 );
163
164 sub auto_thaw_frozen_holds {
165         my $self = shift;
166         my $client = shift;
167
168         local $OpenILS::Application::Storage::WRITE = 1;
169
170         my $holds = action::hold_request->table;
171
172         my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
173
174         my $sth = action::hold_request->db_Main->prepare_cached($sql);
175         $sth->execute();
176
177         return $sth->rows;
178
179 }
180 __PACKAGE__->register_method(
181         api_name        => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
182         api_level       => 1,
183         stream          => 0,
184         argc            => 0,
185         method          => 'auto_thaw_frozen_holds',
186 );
187
188 sub grab_overdue {
189         my $self = shift;
190         my $client = shift;
191         my $grace = shift || '';
192
193         $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
194
195         return undef;
196
197 }
198 __PACKAGE__->register_method(
199         api_name        => 'open-ils.storage.action.circulation.overdue',
200         api_level       => 1,
201         stream          => 1,
202         method          => 'grab_overdue',
203 );
204
205 sub nearest_hold {
206         my $self = shift;
207         my $client = shift;
208         my $here = shift;
209         my $cp = shift;
210         my $limit = int(shift()) || 10;
211         my $age = shift() || '0 seconds';
212
213         my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
214                 SELECT  h.id
215                   FROM  action.hold_request h
216                         JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
217                         JOIN action.hold_copy_map hm ON (hm.hold = h.id)
218                   WHERE hm.target_copy = ?
219                         AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
220                         AND h.capture_time IS NULL
221                         AND h.cancel_time IS NULL
222                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
223             AND h.frozen IS FALSE
224                 ORDER BY
225                         p.prox,
226                         h.selection_depth DESC,
227                         h.request_time
228                 LIMIT $limit
229         SQL
230         
231         $client->respond( $_ ) for ( @$ids );
232         return undef;
233 }
234 __PACKAGE__->register_method(
235         api_name        => 'open-ils.storage.action.hold_request.nearest_hold',
236         api_level       => 1,
237         stream          => 1,
238         method          => 'nearest_hold',
239 );
240
241 sub next_resp_group_id {
242         my $self = shift;
243         my $client = shift;
244
245         # XXX This is not replication safe!!!
246
247         my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
248                 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
249         SQL
250         return $id;
251 }
252 __PACKAGE__->register_method(
253         api_name        => 'open-ils.storage.action.survey_response.next_group_id',
254         api_level       => 1,
255         method          => 'next_resp_group_id',
256 );
257
258 sub patron_circ_summary {
259         my $self = shift;
260         my $client = shift;
261         my $id = ''.shift();
262
263         return undef unless ($id);
264         my $c_table = action::circulation->table;
265         my $b_table = money::billing->table;
266
267         $log->debug("Retrieving patron summary for id $id", DEBUG);
268
269         my $select = <<"        SQL";
270                 SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
271                   FROM  $c_table c
272                         LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
273                   WHERE c.usr = ?
274                         AND c.xact_finish IS NULL
275                         AND (
276                                 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
277                                 OR c.stop_fines IS NULL
278                         )
279         SQL
280
281         return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
282 }
283 __PACKAGE__->register_method(
284         api_name        => 'open-ils.storage.action.circulation.patron_summary',
285         api_level       => 1,
286         method          => 'patron_circ_summary',
287 );
288
289 #XXX Fix stored proc calls
290 sub find_local_surveys {
291         my $self = shift;
292         my $client = shift;
293         my $ou = ''.shift();
294
295         return undef unless ($ou);
296         my $s_table = action::survey->table;
297
298         my $select = <<"        SQL";
299                 SELECT  s.*
300                   FROM  $s_table s
301                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
302                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
303         SQL
304
305         my $sth = action::survey->db_Main->prepare_cached($select);
306         $sth->execute($ou);
307
308         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
309
310         return undef;
311 }
312 __PACKAGE__->register_method(
313         api_name        => 'open-ils.storage.action.survey.all',
314         api_level       => 1,
315         stream          => 1,
316         method          => 'find_local_surveys',
317 );
318
319 #XXX Fix stored proc calls
320 sub find_opac_surveys {
321         my $self = shift;
322         my $client = shift;
323         my $ou = ''.shift();
324
325         return undef unless ($ou);
326         my $s_table = action::survey->table;
327
328         my $select = <<"        SQL";
329                 SELECT  s.*
330                   FROM  $s_table s
331                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
332                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
333                         AND s.opac IS TRUE;
334         SQL
335
336         my $sth = action::survey->db_Main->prepare_cached($select);
337         $sth->execute($ou);
338
339         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
340
341         return undef;
342 }
343 __PACKAGE__->register_method(
344         api_name        => 'open-ils.storage.action.survey.opac',
345         api_level       => 1,
346         stream          => 1,
347         method          => 'find_opac_surveys',
348 );
349
350 sub hold_pull_list {
351         my $self = shift;
352         my $client = shift;
353         my $ou = shift;
354         my $limit = shift || 10;
355         my $offset = shift || 0;
356
357         return undef unless ($ou);
358         my $h_table = action::hold_request->table;
359         my $a_table = asset::copy->table;
360
361         my $idlist = 1 if ($self->api_name =~/id_list/o);
362
363         my $status_filter = '';
364         $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
365
366         my $select = <<"        SQL";
367                 SELECT  h.*
368                   FROM  $h_table h
369                         JOIN $a_table a ON (h.current_copy = a.id)
370                   WHERE a.circ_lib = ?
371                         AND h.capture_time IS NULL
372                         AND h.cancel_time IS NULL
373                         AND (h.expire_time IS NULL OR h.expire_time > NOW())
374                         $status_filter
375                   ORDER BY h.request_time ASC
376                   LIMIT $limit
377                   OFFSET $offset
378         SQL
379
380         my $sth = action::survey->db_Main->prepare_cached($select);
381         $sth->execute($ou);
382
383         if ($idlist) {
384                 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
385         } else {
386                 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
387         }
388
389         return undef;
390 }
391 __PACKAGE__->register_method(
392         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
393         api_level       => 1,
394         stream          => 1,
395         signature       => [
396                 "Returns the hold ids for a specific library's pull list.",
397                 [ [org_unit => "The library's org id", "number"],
398                   [limit => 'An optional page size, defaults to 10', 'number'],
399                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
400                 ],
401                 ['A list of holds for the stated library to pull for', 'array']
402         ],
403         method          => 'hold_pull_list',
404 );
405 __PACKAGE__->register_method(
406         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
407         api_level       => 1,
408         stream          => 1,
409         signature       => [
410                 "Returns the holds for a specific library's pull list.",
411                 [ [org_unit => "The library's org id", "number"],
412                   [limit => 'An optional page size, defaults to 10', 'number'],
413                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
414                 ],
415                 ['A list of holds for the stated library to pull for', 'array']
416         ],
417         method          => 'hold_pull_list',
418 );
419 __PACKAGE__->register_method(
420         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
421         api_level       => 1,
422         stream          => 1,
423         signature       => [
424                 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
425                 [ [org_unit => "The library's org id", "number"],
426                   [limit => 'An optional page size, defaults to 10', 'number'],
427                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
428                 ],
429                 ['A list of holds for the stated library to pull for', 'array']
430         ],
431         method          => 'hold_pull_list',
432 );
433 __PACKAGE__->register_method(
434         api_name        => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
435         api_level       => 1,
436         stream          => 1,
437         signature       => [
438                 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
439                 [ [org_unit => "The library's org id", "number"],
440                   [limit => 'An optional page size, defaults to 10', 'number'],
441                   [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
442                 ],
443                 ['A list of holds for the stated library to pull for', 'array']
444         ],
445         method          => 'hold_pull_list',
446 );
447
448 sub find_optional_surveys {
449         my $self = shift;
450         my $client = shift;
451         my $ou = ''.shift();
452
453         return undef unless ($ou);
454         my $s_table = action::survey->table;
455
456         my $select = <<"        SQL";
457                 SELECT  s.*
458                   FROM  $s_table s
459                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
460                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
461                         AND s.required IS FALSE;
462         SQL
463
464         my $sth = action::survey->db_Main->prepare_cached($select);
465         $sth->execute($ou);
466
467         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
468
469         return undef;
470 }
471 __PACKAGE__->register_method(
472         api_name        => 'open-ils.storage.action.survey.optional',
473         api_level       => 1,
474         stream          => 1,
475         method          => 'find_optional_surveys',
476 );
477
478 sub find_required_surveys {
479         my $self = shift;
480         my $client = shift;
481         my $ou = ''.shift();
482
483         return undef unless ($ou);
484         my $s_table = action::survey->table;
485
486         my $select = <<"        SQL";
487                 SELECT  s.*
488                   FROM  $s_table s
489                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
490                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
491                         AND s.required IS TRUE;
492         SQL
493
494         my $sth = action::survey->db_Main->prepare_cached($select);
495         $sth->execute($ou);
496
497         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
498
499         return undef;
500 }
501 __PACKAGE__->register_method(
502         api_name        => 'open-ils.storage.action.survey.required',
503         api_level       => 1,
504         stream          => 1,
505         method          => 'find_required_surveys',
506 );
507
508 sub find_usr_summary_surveys {
509         my $self = shift;
510         my $client = shift;
511         my $ou = ''.shift();
512
513         return undef unless ($ou);
514         my $s_table = action::survey->table;
515
516         my $select = <<"        SQL";
517                 SELECT  s.*
518                   FROM  $s_table s
519                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
520                   WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
521                         AND s.usr_summary IS TRUE;
522         SQL
523
524         my $sth = action::survey->db_Main->prepare_cached($select);
525         $sth->execute($ou);
526
527         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
528
529         return undef;
530 }
531 __PACKAGE__->register_method(
532         api_name        => 'open-ils.storage.action.survey.usr_summary',
533         api_level       => 1,
534         stream          => 1,
535         method          => 'find_usr_summary_surveys',
536 );
537
538
539 sub generate_fines {
540         my $self = shift;
541         my $client = shift;
542         my $grace = shift;
543         my $circ = shift;
544         my $overbill = shift;
545
546         local $OpenILS::Application::Storage::WRITE = 1;
547
548         my @circs;
549         if ($circ) {
550                 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
551         } else {
552                 push @circs, overdue_circs($grace);
553         }
554
555         my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
556
557         my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
558         for my $c (@circs) {
559         
560                 try {
561                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
562                                 $log->debug("Cleaning up after previous transaction\n");
563                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
564                         }
565                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
566                         $log->info("Processing circ ".$c->id."...\n");
567
568
569                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
570         
571                         my $due = $due_dt->epoch;
572                         my $now = time;
573
574                         my $fine_interval = $c->fine_interval;
575             $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
576                         $fine_interval = interval_to_seconds( $fine_interval );
577         
578                         if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {  
579                                 my $tz_offset_s = 0;
580                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
581                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
582                                 }
583         
584                                 $due -= ($due % $fine_interval) + $tz_offset_s;
585                                 $now -= ($now % $fine_interval) + $tz_offset_s;
586                         }
587         
588                         $client->respond(
589                                 "ARG! Overdue circulation ".$c->id.
590                                 " for item ".$c->target_copy.
591                                 " (user ".$c->usr.").\n".
592                                 "\tItem was due on or before: ".localtime($due)."\n");
593         
594                         my @fines = money::billing->search_where(
595                                 { xact => $c->id,
596                                   billing_type => 'Overdue materials',
597                                   billing_ts => { '>' => $c->due_date } },
598                                 { order_by => 'billing_ts DESC'}
599                         );
600
601                         my $f_idx = 0;
602                         my $fine = $fines[$f_idx] if (@fines);
603                         if ($overbill) {
604                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
605                         }
606
607                         my $current_fine_total = 0;
608                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
609         
610                         my $last_fine;
611                         if ($fine) {
612                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
613                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
614                         } else {
615                                 $log->info( "Potential first billing for circ ".$c->id );
616                                 $last_fine = $due;
617
618                                 if (0) {
619                                         if (my $h = $hoo{$c->circ_lib}) { 
620
621                                                 $log->info( "Circ lib has an hours-of-operation entry" );
622                                                 # find the day after the due date...
623                                                 $due_dt = $due_dt->add( days => 1 );
624
625                                                 # get the day of the week for that day...
626                                                 my $dow = $due_dt->day_of_week_0;
627                                                 my $dow_open = "dow_${dow}_open";
628                                                 my $dow_close = "dow_${dow}_close";
629
630                                                 my $count = 0;
631                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
632                                                         # if the circ lib is closed, add a day to the grace period...
633
634                                                         $grace++;
635                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
636                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
637
638                                                         $due_dt = $due_dt->add( days => 1 );
639                                                         $dow = $due_dt->day_of_week_0;
640                                                         $dow_open = "dow_${dow}_open";
641                                                         $dow_close = "dow_${dow}_close";
642
643                                                         $count++;
644
645                                                         # and check for up to a week
646                                                         last if ($count > 6);
647                                                 }
648                                         }
649                                 }
650                         }
651
652
653                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
654                         if ($pending_fine_count < 1 + $grace) {
655                                 $client->respond( "\tNo fines to create.  " );
656                                 if ($grace && $now < $due + $fine_interval * $grace) {
657                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
658                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
659                                 } else {
660                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
661                                 }
662                                 next;
663                         }
664         
665                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
666
667                         my $recuring_fine = int($c->recuring_fine * 100);
668                         my $max_fine = int($c->max_fine * 100);
669
670                         my ($latest_billing_ts, $latest_amount) = ('',0);
671                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
672         
673                                 if ($current_fine_total >= $max_fine) {
674                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
675                                         $client->respond(
676                                                 "\tMaximum fine level of ".$c->max_fine.
677                                                 " reached for this circulation.\n".
678                                                 "\tNo more fines will be generated.\n" );
679                                         last;
680                                 }
681                                 
682                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
683
684                                 my $dow = $billing_ts->day_of_week_0();
685                                 my $dow_open = "dow_${dow}_open";
686                                 my $dow_close = "dow_${dow}_close";
687
688                                 if (my $h = $hoo{$c->circ_lib}) {
689                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
690                                 }
691
692                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
693                                 my @cl = actor::org_unit::closed_date->search_where(
694                                                 { close_start   => { '<=' => $timestamptz },
695                                                   close_end     => { '>=' => $timestamptz },
696                                                   org_unit      => $c->circ_lib }
697                                 );
698                                 next if (@cl);
699         
700                                 $current_fine_total += $recuring_fine;
701                                 $latest_amount += $recuring_fine;
702                                 $latest_billing_ts = $timestamptz;
703
704                                 money::billing->create(
705                                         { xact          => ''.$c->id,
706                                           note          => "System Generated Overdue Fine",
707                                           billing_type  => "Overdue materials",
708                                           amount        => sprintf('%0.2f', $recuring_fine/100),
709                                           billing_ts    => $timestamptz,
710                                         }
711                                 );
712
713                         }
714
715                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
716                                 if ($latest_billing_ts and $latest_amount);
717
718                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
719
720                         $penalty->request(
721                                 'open-ils.penalty.patron_penalty.calculate',
722                                 { patron        => $c->usr->to_fieldmapper,
723                                   update        => 1,
724                                   background    => 1,
725                                 }
726                         )->gather(1);
727
728                 } catch Error with {
729                         my $e = shift;
730                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
731                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
732                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
733                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
734                 };
735         }
736 }
737 __PACKAGE__->register_method(
738         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
739         api_level       => 1,
740         stream          => 1,
741         method          => 'generate_fines',
742 );
743
744
745
746 sub new_hold_copy_targeter {
747         my $self = shift;
748         my $client = shift;
749         my $check_expire = shift;
750         my $one_hold = shift;
751
752         local $OpenILS::Application::Storage::WRITE = 1;
753
754         my $holds;
755
756         try {
757                 if ($one_hold) {
758                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
759                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
760                 } elsif ( $check_expire ) {
761
762                         # what's the retarget time threashold?
763                         my $time = time;
764                         $check_expire ||= '12h';
765                         $check_expire = interval_to_seconds( $check_expire );
766
767                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
768                         $year += 1900;
769                         $mon += 1;
770                         my $expire_threshold = sprintf(
771                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
772                                 $year, $mon, $mday, $hour, $min, $sec
773                         );
774
775                         # find all the holds holds needing retargeting
776                         $holds = [ action::hold_request->search_where(
777                                                         { capture_time => undef,
778                                                           fulfillment_time => undef,
779                                                           cancel_time => undef,
780                                                           frozen => 'f',
781                                                           prev_check_time => { '<=' => $expire_threshold },
782                                                         },
783                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
784
785                         # find all the holds holds needing first time targeting
786                         push @$holds, action::hold_request->search(
787                                                         capture_time => undef,
788                                                         fulfillment_time => undef,
789                                                         prev_check_time => undef,
790                                                         frozen => 'f',
791                                                         cancel_time => undef,
792                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
793                 } else {
794
795                         # find all the holds holds needing first time targeting ONLY
796                         $holds = [ action::hold_request->search(
797                                                         capture_time => undef,
798                                                         fulfillment_time => undef,
799                                                         prev_check_time => undef,
800                                                         cancel_time => undef,
801                                                         frozen => 'f',
802                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
803                 }
804         } catch Error with {
805                 my $e = shift;
806                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
807         };
808
809         my @closed = actor::org_unit::closed_date->search_where(
810                 { close_start => { '<=', 'now' },
811                   close_end => { '>=', 'now' } }
812         );
813
814
815         my @successes;
816
817         for my $hold (@$holds) {
818                 try {
819                         #start a transaction if needed
820                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
821                                 $log->debug("Cleaning up after previous transaction\n");
822                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
823                         }
824                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
825                         $log->info("Processing hold ".$hold->id."...\n");
826
827                         #first, re-fetch the hold, to make sure it's not captured already
828                         $hold->remove_from_object_index();
829                         $hold = action::hold_request->retrieve( $hold->id );
830
831                         # remove old auto-targeting maps
832                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
833                         $_->delete for (@oldmaps);
834
835                         if ($hold->expire_time) {
836                                 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
837                                 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
838                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
839                         }
840
841                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
842
843                         my $all_copies = [];
844
845                         # find filters for MR holds
846                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
847
848                         # find all the potential copies
849                         if ($hold->hold_type eq 'M') {
850                                 for my $r ( map
851                                                 {$_->record}
852                                                 metabib::record_descriptor
853                                                         ->search(
854                                                                 record => [
855                                                                         map {
856                                                                                 isTrue($_->deleted) ?  () : ($_->id)
857                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
858                                                                 ],
859                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
860                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
861                                                                 ( $lang    ? (item_lang => $lang)                : () ),
862                                                         )
863                                 ) {
864                                         my ($rtree) = $self
865                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
866                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
867
868                                         for my $cn ( @{ $rtree->call_numbers } ) {
869                                                 push @$all_copies,
870                                                         asset::copy->search_where(
871                                                                 { id => [map {$_->id} @{ $cn->copies }],
872                                                                   deleted => 'f' }
873                                                         ) if ($cn && @{ $cn->copies });
874                                         }
875                                 }
876                         } elsif ($hold->hold_type eq 'T') {
877                                 my ($rtree) = $self
878                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
879                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
880
881                                 unless ($rtree) {
882                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
883                                         die "OK\n";
884                                 }
885
886                                 for my $cn ( @{ $rtree->call_numbers } ) {
887                                         push @$all_copies,
888                                                 asset::copy->search_where(
889                                                         { id => [map {$_->id} @{ $cn->copies }],
890                                                           deleted => 'f' }
891                                                 ) if ($cn && @{ $cn->copies });
892                                 }
893                         } elsif ($hold->hold_type eq 'V') {
894                                 my ($vtree) = $self
895                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
896                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
897
898                                 push @$all_copies,
899                                         asset::copy->search_where(
900                                                 { id => [map {$_->id} @{ $vtree->copies }],
901                                                   deleted => 'f' }
902                                         ) if ($vtree && @{ $vtree->copies });
903                                         
904                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
905                                 my $_cp = asset::copy->retrieve($hold->target);
906                                 push @$all_copies, $_cp if $_cp;
907                         }
908
909                         # trim unholdables
910                         @$all_copies = grep {   isTrue($_->status->holdable) && 
911                                                 isTrue($_->location->holdable) && 
912                                                 isTrue($_->holdable) &&
913                                                 !isTrue($_->deleted)
914                                         } @$all_copies;
915
916                         # let 'em know we're still working
917                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
918                         
919                         # if we have no copies ...
920                         if (!ref $all_copies || !@$all_copies) {
921                                 $log->info("\tNo copies available for targeting at all!\n");
922                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
923
924                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
925                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
926                                 die "OK\n";
927                         }
928
929                         my $copy_count = @$all_copies;
930
931                         # map the potentials, so that we can pick up checkins
932                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
933                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
934
935                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
936
937                         my @good_copies;
938                         for my $c (@$all_copies) {
939                                 # current target
940                                 next if ($c->id eq $hold->current_copy);
941
942                                 # circ lib is closed
943                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
944
945                                 # target of another hold
946                                 next if (action::hold_request
947                                                 ->search_where(
948                                                         { current_copy => $c->id,
949                                                           fulfillment_time => undef,
950                                                           cancel_time => undef,
951                                                         }
952                                                 )
953                                 );
954
955                                 # we passed all three, keep it
956                                 push @good_copies, $c if ($c);
957                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
958                         }
959
960                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
961
962                         my $old_best = $hold->current_copy;
963                         $hold->update({ current_copy => undef }) if ($old_best);
964         
965                         if (!scalar(@good_copies)) {
966                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
967                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
968                                         # the old copy is still available
969                                         $log->debug("\tPushing current_copy back onto the targeting list");
970                                         push @good_copies, $old_best;
971                                 } else {
972                                         # oops, old copy is not available
973                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
974                                         $hold->update( { prev_check_time => 'today' } );
975                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
976                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
977                                         die "OK\n";
978                                 }
979                         }
980
981                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
982                         my $prox_list = [];
983                         $$prox_list[0] =
984                         [
985                                 grep {
986                                         $_->circ_lib == $hold->pickup_lib
987                                 } @good_copies
988                         ];
989
990                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
991
992                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
993                         my $best = choose_nearest_copy($hold, $prox_list);
994                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
995
996                         if (!$best) {
997                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
998                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
999
1000                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1001
1002                                 $best = choose_nearest_copy($hold, $prox_list);
1003                         }
1004
1005                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1006                         if ($old_best) {
1007                                 # hold wasn't fulfilled, record the fact
1008                         
1009                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1010                                 action::unfulfilled_hold_list->create(
1011                                                 { hold => ''.$hold->id,
1012                                                   current_copy => ''.$old_best->id,
1013                                                   circ_lib => ''.$old_best->circ_lib,
1014                                                 });
1015                         }
1016
1017                         if ($best) {
1018                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1019                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1020                         } elsif (
1021                                 $old_best &&
1022                                 action::hold_request
1023                                         ->search_where(
1024                                                 { current_copy => $old_best->id,
1025                                                   fulfillment_time => undef,
1026                                                   cancel_time => undef,
1027                                                 }       
1028                                         )
1029                         ) {     
1030                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1031                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1032                         } else {
1033                                 $hold->update( { prev_check_time => 'now' } );
1034                                 $log->info( "\tThere were no targetable copies for the hold" );
1035                         }
1036
1037                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1038                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1039
1040                         push @successes,
1041                                 { hold => $hold->id,
1042                                   old_target => ($old_best ? $old_best->id : undef),
1043                                   eligible_copies => $copy_count,
1044                                   target => ($best ? $best->id : undef) };
1045
1046                 } otherwise {
1047                         my $e = shift;
1048                         if ($e !~ /^OK/o) {
1049                                 $log->error("Processing of hold failed:  $e");
1050                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1051                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1052                         }
1053                 };
1054         }
1055
1056         return \@successes;
1057 }
1058 __PACKAGE__->register_method(
1059         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1060         api_level       => 1,
1061         method          => 'new_hold_copy_targeter',
1062 );
1063
1064 my $locations;
1065 my $statuses;
1066 my %cache = (titles => {}, cns => {});
1067 sub hold_copy_targeter {
1068         my $self = shift;
1069         my $client = shift;
1070         my $check_expire = shift;
1071         my $one_hold = shift;
1072
1073         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1074         $self->{user_filter}->connect;
1075         $self->{client} = $client;
1076
1077         my $time = time;
1078         $check_expire ||= '12h';
1079         $check_expire = interval_to_seconds( $check_expire );
1080
1081         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1082         $year += 1900;
1083         $mon += 1;
1084         my $expire_threshold = sprintf(
1085                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1086                 $year, $mon, $mday, $hour, $min, $sec
1087         );
1088
1089
1090         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1091
1092         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1093
1094         my $holds;
1095
1096         %cache = (titles => {}, cns => {});
1097
1098         try {
1099                 if ($one_hold) {
1100                         $holds = [ action::hold_request->search(id => $one_hold) ];
1101                 } else {
1102                         $holds = [ action::hold_request->search_where(
1103                                                         { capture_time => undef,
1104                                                           prev_check_time => { '<=' => $expire_threshold },
1105                                                         },
1106                                                         { order_by => 'request_time,prev_check_time' } ) ];
1107                         push @$holds, action::hold_request->search_where(
1108                                                         { capture_time => undef,
1109                                                           prev_check_time => undef,
1110                                                         },
1111                                                         { order_by => 'request_time' } );
1112                 }
1113         } catch Error with {
1114                 my $e = shift;
1115                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1116         };
1117
1118         for my $hold (@$holds) {
1119                 try {
1120                         #action::hold_request->db_Main->begin_work;
1121                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1122                                 $client->respond("Cleaning up after previous transaction\n");
1123                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1124                         }
1125                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1126                         $client->respond("Processing hold ".$hold->id."...\n");
1127
1128                         my $copies;
1129
1130                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1131                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1132
1133                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1134                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1135                         
1136                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1137                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1138                         
1139                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1140
1141                         unless (ref $copies || !@$copies) {
1142                                 $client->respond("\tNo copies available for targeting at all!\n");
1143                         }
1144
1145                         my @good_copies;
1146                         for my $c (@$copies) {
1147                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1148                                 push @good_copies, $c if ($c);
1149                         }
1150
1151                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1152
1153                         my $old_best = $hold->current_copy;
1154                         $hold->update({ current_copy => undef });
1155         
1156                         if (!scalar(@good_copies)) {
1157                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1158                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1159                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1160                                         push @good_copies, asset::copy->retrieve( $old_best );
1161                                 } else {
1162                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1163                                         next;
1164                                 }
1165                         }
1166
1167                         my $prox_list;
1168                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1169                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1170
1171                         my $best = choose_nearest_copy($hold, $prox_list);
1172
1173                         if (!$best) {
1174                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1175                                 $best = choose_nearest_copy($hold, $prox_list);
1176                         }
1177
1178                         if ($old_best) {
1179                                 # hold wasn't fulfilled, record the fact
1180                         
1181                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1182                                 action::unfulfilled_hold_list->create(
1183                                                 { hold => ''.$hold->id,
1184                                                   current_copy => ''.$old_best->id,
1185                                                   circ_lib => ''.$old_best->circ_lib,
1186                                                 });
1187                         }
1188
1189                         if ($best) {
1190                                 $hold->update( { current_copy => ''.$best->id } );
1191                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1192                         }
1193
1194                         $hold->update( { prev_check_time => 'now' } );
1195                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1196
1197                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1198                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1199
1200                         #action::hold_request->dbi_commit;
1201
1202                 } otherwise {
1203                         my $e = shift;
1204                         $log->error("Processing of hold failed:  $e");
1205                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1206                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1207                         #action::hold_request->dbi_rollback;
1208                 };
1209         }
1210
1211         $self->{user_filter}->disconnect;
1212         $self->{user_filter}->finish;
1213         delete $$self{user_filter};
1214         return undef;
1215 }
1216 __PACKAGE__->register_method(
1217         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1218         api_level       => 0,
1219         stream          => 1,
1220         method          => 'hold_copy_targeter',
1221 );
1222
1223
1224 sub copy_hold_capture {
1225         my $self = shift;
1226         my $hold = shift;
1227         my $cps = shift;
1228
1229         if (!defined($cps)) {
1230                 try {
1231                         $cps = [ asset::copy->search( id => $hold->target ) ];
1232                 } catch Error with {
1233                         my $e = shift;
1234                         die "Could not retrieve initial volume list:\n\n$e\n";
1235                 };
1236         }
1237
1238         my @copies = grep { $_->holdable } @$cps;
1239
1240         for (my $i = 0; $i < @$cps; $i++) {
1241                 next unless $$cps[$i];
1242                 
1243                 my $cn = $cache{cns}{$copies[$i]->call_number};
1244                 my $rec = $cache{titles}{$cn->record};
1245                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1246                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1247                 $copies[$i] = undef if (
1248                         !$copies[$i] ||
1249                         !$self->{user_filter}->request(
1250                                 'open-ils.circ.permit_hold',
1251                                 $hold->to_fieldmapper, do {
1252                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1253                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1254                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1255                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1256                                         $cp_fm;
1257                                 },
1258                                 { title => $rec->to_fieldmapper,
1259                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1260                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1261                                 })->gather(1)
1262                 );
1263                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1264         }
1265
1266         @copies = grep { $_ } @copies;
1267
1268         my $count = @copies;
1269
1270         return unless ($count);
1271         
1272         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1273         
1274         my @maps;
1275         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1276         for my $c (@copies) {
1277                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1278         }
1279         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1280
1281         return \@copies;
1282 }
1283
1284
1285 sub choose_nearest_copy {
1286         my $hold = shift;
1287         my $prox_list = shift;
1288
1289         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1290                 next unless (ref $$prox_list[$p]);
1291
1292                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1293                 next unless (@capturable);
1294
1295                 my $rand = int(rand(scalar(@capturable)));
1296                 while (my ($c) = splice(@capturable,$rand)) {
1297                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1298                                 { title => $c->call_number->record->to_fieldmapper,
1299                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1300                                   patron => $hold->usr->to_fieldmapper,
1301                                   copy => $c->to_fieldmapper,
1302                                   requestor => $hold->requestor->to_fieldmapper,
1303                                   request_lib => $hold->request_lib->to_fieldmapper,
1304                                    pickup_lib => $hold->pickup_lib->id,
1305                                 }
1306                         ));
1307
1308                         last unless(@capturable);
1309                         $rand = int(rand(scalar(@capturable)));
1310                 }
1311         }
1312 }
1313
1314 sub create_prox_list {
1315         my $self = shift;
1316         my $lib = shift;
1317         my $copies = shift;
1318
1319         my @prox_list;
1320         for my $cp (@$copies) {
1321                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1322                 next unless (defined($prox));
1323                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1324                 push @{$prox_list[$prox]}, $cp;
1325         }
1326         return \@prox_list;
1327 }
1328
1329 sub volume_hold_capture {
1330         my $self = shift;
1331         my $hold = shift;
1332         my $vols = shift;
1333
1334         if (!defined($vols)) {
1335                 try {
1336                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1337                         $cache{cns}{$_->id} = $_ for (@$vols);
1338                 } catch Error with {
1339                         my $e = shift;
1340                         die "Could not retrieve initial volume list:\n\n$e\n";
1341                 };
1342         }
1343
1344         my @v_ids = map { $_->id } @$vols;
1345
1346         my $cp_list;
1347         try {
1348                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1349         
1350         } catch Error with {
1351                 my $e = shift;
1352                 warn "Could not retrieve copy list:\n\n$e\n";
1353         };
1354
1355         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1356 }
1357
1358 sub title_hold_capture {
1359         my $self = shift;
1360         my $hold = shift;
1361         my $titles = shift;
1362
1363         if (!defined($titles)) {
1364                 try {
1365                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1366                         $cache{titles}{$_->id} = $_ for (@$titles);
1367                 } catch Error with {
1368                         my $e = shift;
1369                         die "Could not retrieve initial title list:\n\n$e\n";
1370                 };
1371         }
1372
1373         my @t_ids = map { $_->id } @$titles;
1374         my $cn_list;
1375         try {
1376                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1377         
1378         } catch Error with {
1379                 my $e = shift;
1380                 warn "Could not retrieve volume list:\n\n$e\n";
1381         };
1382
1383         $cache{cns}{$_->id} = $_ for (@$cn_list);
1384
1385         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1386 }
1387
1388 sub metarecord_hold_capture {
1389         my $self = shift;
1390         my $hold = shift;
1391
1392         my $titles;
1393         try {
1394                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1395         
1396         } catch Error with {
1397                 my $e = shift;
1398                 die "Could not retrieve initial title list:\n\n$e\n";
1399         };
1400
1401         try {
1402                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1403
1404                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1405         
1406         } catch Error with {
1407                 my $e = shift;
1408                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1409         };
1410
1411
1412         $cache{titles}{$_->id} = $_ for (@$titles);
1413         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1414 }
1415
1416 1;