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