e77eefc5f956039b17c67b6457efff6ae0362951
[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                         my $fine_interval = interval_to_seconds( $c->fine_interval );
574         
575                         if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {  
576                                 my $tz_offset_s = 0;
577                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
578                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
579                                 }
580         
581                                 $due -= ($due % $fine_interval) + $tz_offset_s;
582                                 $now -= ($now % $fine_interval) + $tz_offset_s;
583                         }
584         
585                         $client->respond(
586                                 "ARG! Overdue circulation ".$c->id.
587                                 " for item ".$c->target_copy.
588                                 " (user ".$c->usr.").\n".
589                                 "\tItem was due on or before: ".localtime($due)."\n");
590         
591                         my @fines = money::billing->search_where(
592                                 { xact => $c->id,
593                                   billing_type => 'Overdue materials',
594                                   billing_ts => { '>' => $c->due_date } },
595                                 { order_by => 'billing_ts DESC'}
596                         );
597
598                         my $f_idx = 0;
599                         my $fine = $fines[$f_idx] if (@fines);
600                         if ($overbill) {
601                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
602                         }
603
604                         my $current_fine_total = 0;
605                         $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
606         
607                         my $last_fine;
608                         if ($fine) {
609                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
610                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
611                         } else {
612                                 $log->info( "Potential first billing for circ ".$c->id );
613                                 $last_fine = $due;
614
615                                 if (0) {
616                                         if (my $h = $hoo{$c->circ_lib}) { 
617
618                                                 $log->info( "Circ lib has an hours-of-operation entry" );
619                                                 # find the day after the due date...
620                                                 $due_dt = $due_dt->add( days => 1 );
621
622                                                 # get the day of the week for that day...
623                                                 my $dow = $due_dt->day_of_week_0;
624                                                 my $dow_open = "dow_${dow}_open";
625                                                 my $dow_close = "dow_${dow}_close";
626
627                                                 my $count = 0;
628                                                 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
629                                                         # if the circ lib is closed, add a day to the grace period...
630
631                                                         $grace++;
632                                                         $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
633                                                         $log->info( "Day of week $dow open $dow_open, close $dow_close" );
634
635                                                         $due_dt = $due_dt->add( days => 1 );
636                                                         $dow = $due_dt->day_of_week_0;
637                                                         $dow_open = "dow_${dow}_open";
638                                                         $dow_close = "dow_${dow}_close";
639
640                                                         $count++;
641
642                                                         # and check for up to a week
643                                                         last if ($count > 6);
644                                                 }
645                                         }
646                                 }
647                         }
648
649
650                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
651                         if ($pending_fine_count < 1 + $grace) {
652                                 $client->respond( "\tNo fines to create.  " );
653                                 if ($grace && $now < $due + $fine_interval * $grace) {
654                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
655                                         $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
656                                 } else {
657                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
658                                 }
659                                 next;
660                         }
661         
662                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
663
664                         my $recuring_fine = int($c->recuring_fine * 100);
665                         my $max_fine = int($c->max_fine * 100);
666
667                         my ($latest_billing_ts, $latest_amount) = ('',0);
668                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
669         
670                                 if ($current_fine_total >= $max_fine) {
671                                         $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
672                                         $client->respond(
673                                                 "\tMaximum fine level of ".$c->max_fine.
674                                                 " reached for this circulation.\n".
675                                                 "\tNo more fines will be generated.\n" );
676                                         last;
677                                 }
678                                 
679                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
680
681                                 my $dow = $billing_ts->day_of_week_0();
682                                 my $dow_open = "dow_${dow}_open";
683                                 my $dow_close = "dow_${dow}_close";
684
685                                 if (my $h = $hoo{$c->circ_lib}) {
686                                         next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
687                                 }
688
689                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
690                                 my @cl = actor::org_unit::closed_date->search_where(
691                                                 { close_start   => { '<=' => $timestamptz },
692                                                   close_end     => { '>=' => $timestamptz },
693                                                   org_unit      => $c->circ_lib }
694                                 );
695                                 next if (@cl);
696         
697                                 $current_fine_total += $recuring_fine;
698                                 $latest_amount += $recuring_fine;
699                                 $latest_billing_ts = $timestamptz;
700
701                                 money::billing->create(
702                                         { xact          => ''.$c->id,
703                                           note          => "System Generated Overdue Fine",
704                                           billing_type  => "Overdue materials",
705                                           amount        => sprintf('%0.2f', $recuring_fine/100),
706                                           billing_ts    => $timestamptz,
707                                         }
708                                 );
709
710                         }
711
712                         $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
713                                 if ($latest_billing_ts and $latest_amount);
714
715                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
716
717                         $penalty->request(
718                                 'open-ils.penalty.patron_penalty.calculate',
719                                 { patron        => $c->usr->to_fieldmapper,
720                                   update        => 1,
721                                   background    => 1,
722                                 }
723                         )->gather(1);
724
725                 } catch Error with {
726                         my $e = shift;
727                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
728                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
729                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
730                         throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
731                 };
732         }
733 }
734 __PACKAGE__->register_method(
735         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
736         api_level       => 1,
737         stream          => 1,
738         method          => 'generate_fines',
739 );
740
741
742
743 sub new_hold_copy_targeter {
744         my $self = shift;
745         my $client = shift;
746         my $check_expire = shift;
747         my $one_hold = shift;
748
749         local $OpenILS::Application::Storage::WRITE = 1;
750
751         my $holds;
752
753         try {
754                 if ($one_hold) {
755                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
756                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
757                 } elsif ( $check_expire ) {
758
759                         # what's the retarget time threashold?
760                         my $time = time;
761                         $check_expire ||= '12h';
762                         $check_expire = interval_to_seconds( $check_expire );
763
764                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
765                         $year += 1900;
766                         $mon += 1;
767                         my $expire_threshold = sprintf(
768                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
769                                 $year, $mon, $mday, $hour, $min, $sec
770                         );
771
772                         # find all the holds holds needing retargeting
773                         $holds = [ action::hold_request->search_where(
774                                                         { capture_time => undef,
775                                                           fulfillment_time => undef,
776                                                           cancel_time => undef,
777                                                           frozen => 'f',
778                                                           prev_check_time => { '<=' => $expire_threshold },
779                                                         },
780                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
781
782                         # find all the holds holds needing first time targeting
783                         push @$holds, action::hold_request->search(
784                                                         capture_time => undef,
785                                                         fulfillment_time => undef,
786                                                         prev_check_time => undef,
787                                                         frozen => 'f',
788                                                         cancel_time => undef,
789                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
790                 } else {
791
792                         # find all the holds holds needing first time targeting ONLY
793                         $holds = [ action::hold_request->search(
794                                                         capture_time => undef,
795                                                         fulfillment_time => undef,
796                                                         prev_check_time => undef,
797                                                         cancel_time => undef,
798                                                         frozen => 'f',
799                                                         { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
800                 }
801         } catch Error with {
802                 my $e = shift;
803                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
804         };
805
806         my @closed = actor::org_unit::closed_date->search_where(
807                 { close_start => { '<=', 'now' },
808                   close_end => { '>=', 'now' } }
809         );
810
811
812         my @successes;
813
814         for my $hold (@$holds) {
815                 try {
816                         #start a transaction if needed
817                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
818                                 $log->debug("Cleaning up after previous transaction\n");
819                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
820                         }
821                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
822                         $log->info("Processing hold ".$hold->id."...\n");
823
824                         #first, re-fetch the hold, to make sure it's not captured already
825                         $hold->remove_from_object_index();
826                         $hold = action::hold_request->retrieve( $hold->id );
827
828                         # remove old auto-targeting maps
829                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
830                         $_->delete for (@oldmaps);
831
832                         if ($hold->expire_time) {
833                                 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
834                                 $hold->update( { cancel_time => 'now' } ) if ( DateTime->compare($ex_time, DateTime->now) < 0 );
835                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
836                         }
837
838                         die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
839
840                         my $all_copies = [];
841
842                         # find filters for MR holds
843                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
844
845                         # find all the potential copies
846                         if ($hold->hold_type eq 'M') {
847                                 for my $r ( map
848                                                 {$_->record}
849                                                 metabib::record_descriptor
850                                                         ->search(
851                                                                 record => [
852                                                                         map {
853                                                                                 isTrue($_->deleted) ?  () : ($_->id)
854                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
855                                                                 ],
856                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
857                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
858                                                                 ( $lang    ? (item_lang => $lang)                : () ),
859                                                         )
860                                 ) {
861                                         my ($rtree) = $self
862                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
863                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
864
865                                         for my $cn ( @{ $rtree->call_numbers } ) {
866                                                 push @$all_copies,
867                                                         asset::copy->search_where(
868                                                                 { id => [map {$_->id} @{ $cn->copies }],
869                                                                   deleted => 'f' }
870                                                         ) if ($cn && @{ $cn->copies });
871                                         }
872                                 }
873                         } elsif ($hold->hold_type eq 'T') {
874                                 my ($rtree) = $self
875                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
876                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
877
878                                 unless ($rtree) {
879                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
880                                         die "OK\n";
881                                 }
882
883                                 for my $cn ( @{ $rtree->call_numbers } ) {
884                                         push @$all_copies,
885                                                 asset::copy->search_where(
886                                                         { id => [map {$_->id} @{ $cn->copies }],
887                                                           deleted => 'f' }
888                                                 ) if ($cn && @{ $cn->copies });
889                                 }
890                         } elsif ($hold->hold_type eq 'V') {
891                                 my ($vtree) = $self
892                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
893                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
894
895                                 push @$all_copies,
896                                         asset::copy->search_where(
897                                                 { id => [map {$_->id} @{ $vtree->copies }],
898                                                   deleted => 'f' }
899                                         ) if ($vtree && @{ $vtree->copies });
900                                         
901                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
902                                 my $_cp = asset::copy->retrieve($hold->target);
903                                 push @$all_copies, $_cp if $_cp;
904                         }
905
906                         # trim unholdables
907                         @$all_copies = grep {   isTrue($_->status->holdable) && 
908                                                 isTrue($_->location->holdable) && 
909                                                 isTrue($_->holdable) &&
910                                                 !isTrue($_->deleted)
911                                         } @$all_copies;
912
913                         # let 'em know we're still working
914                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
915                         
916                         # if we have no copies ...
917                         if (!ref $all_copies || !@$all_copies) {
918                                 $log->info("\tNo copies available for targeting at all!\n");
919                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
920
921                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
922                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
923                                 die "OK\n";
924                         }
925
926                         my $copy_count = @$all_copies;
927
928                         # map the potentials, so that we can pick up checkins
929                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
930                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
931
932                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
933
934                         my @good_copies;
935                         for my $c (@$all_copies) {
936                                 # current target
937                                 next if ($c->id eq $hold->current_copy);
938
939                                 # circ lib is closed
940                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
941
942                                 # target of another hold
943                                 next if (action::hold_request
944                                                 ->search_where(
945                                                         { current_copy => $c->id,
946                                                           fulfillment_time => undef,
947                                                           cancel_time => undef,
948                                                         }
949                                                 )
950                                 );
951
952                                 # we passed all three, keep it
953                                 push @good_copies, $c if ($c);
954                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
955                         }
956
957                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
958
959                         my $old_best = $hold->current_copy;
960                         $hold->update({ current_copy => undef }) if ($old_best);
961         
962                         if (!scalar(@good_copies)) {
963                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
964                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
965                                         # the old copy is still available
966                                         $log->debug("\tPushing current_copy back onto the targeting list");
967                                         push @good_copies, $old_best;
968                                 } else {
969                                         # oops, old copy is not available
970                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
971                                         $hold->update( { prev_check_time => 'today' } );
972                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
973                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
974                                         die "OK\n";
975                                 }
976                         }
977
978                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
979                         my $prox_list = [];
980                         $$prox_list[0] =
981                         [
982                                 grep {
983                                         $_->circ_lib == $hold->pickup_lib
984                                 } @good_copies
985                         ];
986
987                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
988
989                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
990                         my $best = choose_nearest_copy($hold, $prox_list);
991                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
992
993                         if (!$best) {
994                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
995                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
996
997                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
998
999                                 $best = choose_nearest_copy($hold, $prox_list);
1000                         }
1001
1002                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1003                         if ($old_best) {
1004                                 # hold wasn't fulfilled, record the fact
1005                         
1006                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1007                                 action::unfulfilled_hold_list->create(
1008                                                 { hold => ''.$hold->id,
1009                                                   current_copy => ''.$old_best->id,
1010                                                   circ_lib => ''.$old_best->circ_lib,
1011                                                 });
1012                         }
1013
1014                         if ($best) {
1015                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1016                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1017                         } elsif (
1018                                 $old_best &&
1019                                 action::hold_request
1020                                         ->search_where(
1021                                                 { current_copy => $old_best->id,
1022                                                   fulfillment_time => undef,
1023                                                   cancel_time => undef,
1024                                                 }       
1025                                         )
1026                         ) {     
1027                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1028                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1029                         } else {
1030                                 $hold->update( { prev_check_time => 'now' } );
1031                                 $log->info( "\tThere were no targetable copies for the hold" );
1032                         }
1033
1034                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1035                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1036
1037                         push @successes,
1038                                 { hold => $hold->id,
1039                                   old_target => ($old_best ? $old_best->id : undef),
1040                                   eligible_copies => $copy_count,
1041                                   target => ($best ? $best->id : undef) };
1042
1043                 } otherwise {
1044                         my $e = shift;
1045                         if ($e !~ /^OK/o) {
1046                                 $log->error("Processing of hold failed:  $e");
1047                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1048                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1049                         }
1050                 };
1051         }
1052
1053         return \@successes;
1054 }
1055 __PACKAGE__->register_method(
1056         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1057         api_level       => 1,
1058         method          => 'new_hold_copy_targeter',
1059 );
1060
1061 my $locations;
1062 my $statuses;
1063 my %cache = (titles => {}, cns => {});
1064 sub hold_copy_targeter {
1065         my $self = shift;
1066         my $client = shift;
1067         my $check_expire = shift;
1068         my $one_hold = shift;
1069
1070         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1071         $self->{user_filter}->connect;
1072         $self->{client} = $client;
1073
1074         my $time = time;
1075         $check_expire ||= '12h';
1076         $check_expire = interval_to_seconds( $check_expire );
1077
1078         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1079         $year += 1900;
1080         $mon += 1;
1081         my $expire_threshold = sprintf(
1082                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1083                 $year, $mon, $mday, $hour, $min, $sec
1084         );
1085
1086
1087         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1088
1089         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1090
1091         my $holds;
1092
1093         %cache = (titles => {}, cns => {});
1094
1095         try {
1096                 if ($one_hold) {
1097                         $holds = [ action::hold_request->search(id => $one_hold) ];
1098                 } else {
1099                         $holds = [ action::hold_request->search_where(
1100                                                         { capture_time => undef,
1101                                                           prev_check_time => { '<=' => $expire_threshold },
1102                                                         },
1103                                                         { order_by => 'request_time,prev_check_time' } ) ];
1104                         push @$holds, action::hold_request->search_where(
1105                                                         { capture_time => undef,
1106                                                           prev_check_time => undef,
1107                                                         },
1108                                                         { order_by => 'request_time' } );
1109                 }
1110         } catch Error with {
1111                 my $e = shift;
1112                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1113         };
1114
1115         for my $hold (@$holds) {
1116                 try {
1117                         #action::hold_request->db_Main->begin_work;
1118                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1119                                 $client->respond("Cleaning up after previous transaction\n");
1120                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1121                         }
1122                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1123                         $client->respond("Processing hold ".$hold->id."...\n");
1124
1125                         my $copies;
1126
1127                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1128                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1129
1130                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1131                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1132                         
1133                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1134                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1135                         
1136                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1137
1138                         unless (ref $copies || !@$copies) {
1139                                 $client->respond("\tNo copies available for targeting at all!\n");
1140                         }
1141
1142                         my @good_copies;
1143                         for my $c (@$copies) {
1144                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1145                                 push @good_copies, $c if ($c);
1146                         }
1147
1148                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1149
1150                         my $old_best = $hold->current_copy;
1151                         $hold->update({ current_copy => undef });
1152         
1153                         if (!scalar(@good_copies)) {
1154                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1155                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1156                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1157                                         push @good_copies, asset::copy->retrieve( $old_best );
1158                                 } else {
1159                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1160                                         next;
1161                                 }
1162                         }
1163
1164                         my $prox_list;
1165                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1166                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1167
1168                         my $best = choose_nearest_copy($hold, $prox_list);
1169
1170                         if (!$best) {
1171                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1172                                 $best = choose_nearest_copy($hold, $prox_list);
1173                         }
1174
1175                         if ($old_best) {
1176                                 # hold wasn't fulfilled, record the fact
1177                         
1178                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1179                                 action::unfulfilled_hold_list->create(
1180                                                 { hold => ''.$hold->id,
1181                                                   current_copy => ''.$old_best->id,
1182                                                   circ_lib => ''.$old_best->circ_lib,
1183                                                 });
1184                         }
1185
1186                         if ($best) {
1187                                 $hold->update( { current_copy => ''.$best->id } );
1188                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1189                         }
1190
1191                         $hold->update( { prev_check_time => 'now' } );
1192                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1193
1194                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1195                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1196
1197                         #action::hold_request->dbi_commit;
1198
1199                 } otherwise {
1200                         my $e = shift;
1201                         $log->error("Processing of hold failed:  $e");
1202                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1203                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1204                         #action::hold_request->dbi_rollback;
1205                 };
1206         }
1207
1208         $self->{user_filter}->disconnect;
1209         $self->{user_filter}->finish;
1210         delete $$self{user_filter};
1211         return undef;
1212 }
1213 __PACKAGE__->register_method(
1214         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1215         api_level       => 0,
1216         stream          => 1,
1217         method          => 'hold_copy_targeter',
1218 );
1219
1220
1221 sub copy_hold_capture {
1222         my $self = shift;
1223         my $hold = shift;
1224         my $cps = shift;
1225
1226         if (!defined($cps)) {
1227                 try {
1228                         $cps = [ asset::copy->search( id => $hold->target ) ];
1229                 } catch Error with {
1230                         my $e = shift;
1231                         die "Could not retrieve initial volume list:\n\n$e\n";
1232                 };
1233         }
1234
1235         my @copies = grep { $_->holdable } @$cps;
1236
1237         for (my $i = 0; $i < @$cps; $i++) {
1238                 next unless $$cps[$i];
1239                 
1240                 my $cn = $cache{cns}{$copies[$i]->call_number};
1241                 my $rec = $cache{titles}{$cn->record};
1242                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1243                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1244                 $copies[$i] = undef if (
1245                         !$copies[$i] ||
1246                         !$self->{user_filter}->request(
1247                                 'open-ils.circ.permit_hold',
1248                                 $hold->to_fieldmapper, do {
1249                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1250                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1251                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1252                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1253                                         $cp_fm;
1254                                 },
1255                                 { title => $rec->to_fieldmapper,
1256                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1257                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1258                                 })->gather(1)
1259                 );
1260                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1261         }
1262
1263         @copies = grep { $_ } @copies;
1264
1265         my $count = @copies;
1266
1267         return unless ($count);
1268         
1269         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1270         
1271         my @maps;
1272         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1273         for my $c (@copies) {
1274                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1275         }
1276         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1277
1278         return \@copies;
1279 }
1280
1281
1282 sub choose_nearest_copy {
1283         my $hold = shift;
1284         my $prox_list = shift;
1285
1286         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1287                 next unless (ref $$prox_list[$p]);
1288
1289                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1290                 next unless (@capturable);
1291
1292                 my $rand = int(rand(scalar(@capturable)));
1293                 while (my ($c) = splice(@capturable,$rand)) {
1294                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1295                                 { title => $c->call_number->record->to_fieldmapper,
1296                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1297                                   patron => $hold->usr->to_fieldmapper,
1298                                   copy => $c->to_fieldmapper,
1299                                   requestor => $hold->requestor->to_fieldmapper,
1300                                   request_lib => $hold->request_lib->to_fieldmapper,
1301                                    pickup_lib => $hold->pickup_lib->id,
1302                                 }
1303                         ));
1304
1305                         last unless(@capturable);
1306                         $rand = int(rand(scalar(@capturable)));
1307                 }
1308         }
1309 }
1310
1311 sub create_prox_list {
1312         my $self = shift;
1313         my $lib = shift;
1314         my $copies = shift;
1315
1316         my @prox_list;
1317         for my $cp (@$copies) {
1318                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1319                 next unless (defined($prox));
1320                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1321                 push @{$prox_list[$prox]}, $cp;
1322         }
1323         return \@prox_list;
1324 }
1325
1326 sub volume_hold_capture {
1327         my $self = shift;
1328         my $hold = shift;
1329         my $vols = shift;
1330
1331         if (!defined($vols)) {
1332                 try {
1333                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1334                         $cache{cns}{$_->id} = $_ for (@$vols);
1335                 } catch Error with {
1336                         my $e = shift;
1337                         die "Could not retrieve initial volume list:\n\n$e\n";
1338                 };
1339         }
1340
1341         my @v_ids = map { $_->id } @$vols;
1342
1343         my $cp_list;
1344         try {
1345                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1346         
1347         } catch Error with {
1348                 my $e = shift;
1349                 warn "Could not retrieve copy list:\n\n$e\n";
1350         };
1351
1352         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1353 }
1354
1355 sub title_hold_capture {
1356         my $self = shift;
1357         my $hold = shift;
1358         my $titles = shift;
1359
1360         if (!defined($titles)) {
1361                 try {
1362                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1363                         $cache{titles}{$_->id} = $_ for (@$titles);
1364                 } catch Error with {
1365                         my $e = shift;
1366                         die "Could not retrieve initial title list:\n\n$e\n";
1367                 };
1368         }
1369
1370         my @t_ids = map { $_->id } @$titles;
1371         my $cn_list;
1372         try {
1373                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1374         
1375         } catch Error with {
1376                 my $e = shift;
1377                 warn "Could not retrieve volume list:\n\n$e\n";
1378         };
1379
1380         $cache{cns}{$_->id} = $_ for (@$cn_list);
1381
1382         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1383 }
1384
1385 sub metarecord_hold_capture {
1386         my $self = shift;
1387         my $hold = shift;
1388
1389         my $titles;
1390         try {
1391                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1392         
1393         } catch Error with {
1394                 my $e = shift;
1395                 die "Could not retrieve initial title list:\n\n$e\n";
1396         };
1397
1398         try {
1399                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1400
1401                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1402         
1403         } catch Error with {
1404                 my $e = shift;
1405                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1406         };
1407
1408
1409         $cache{titles}{$_->id} = $_ for (@$titles);
1410         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1411 }
1412
1413 1;