]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
cb6b06a8ee4f25e7bfbea3723a7e7938b61f14e1
[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->remove_from_object_index();
822                         $hold = action::hold_request->retrieve( $hold->id );
823                         die "OK\n" if (!$hold or $hold->capture_time);
824
825                         # remove old auto-targeting maps
826                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
827                         $_->delete for (@oldmaps);
828
829         
830                         my $all_copies = [];
831
832                         # find filters for MR holds
833                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
834
835                         # find all the potential copies
836                         if ($hold->hold_type eq 'M') {
837                                 for my $r ( map
838                                                 {$_->record}
839                                                 metabib::record_descriptor
840                                                         ->search(
841                                                                 record => [
842                                                                         map {
843                                                                                 isTrue($_->deleted) ?  () : ($_->id)
844                                                                         } metabib::metarecord->retrieve($hold->target)->source_records
845                                                                 ],
846                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
847                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
848                                                                 ( $lang    ? (item_lang => $lang)                : () ),
849                                                         )
850                                 ) {
851                                         my ($rtree) = $self
852                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
853                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
854
855                                         for my $cn ( @{ $rtree->call_numbers } ) {
856                                                 push @$all_copies,
857                                                         asset::copy->search_where(
858                                                                 { id => [map {$_->id} @{ $cn->copies }],
859                                                                   deleted => 'f' }
860                                                         ) if ($cn && @{ $cn->copies });
861                                         }
862                                 }
863                         } elsif ($hold->hold_type eq 'T') {
864                                 my ($rtree) = $self
865                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
866                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
867
868                                 unless ($rtree) {
869                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
870                                         die "OK\n";
871                                 }
872
873                                 for my $cn ( @{ $rtree->call_numbers } ) {
874                                         push @$all_copies,
875                                                 asset::copy->search_where(
876                                                         { id => [map {$_->id} @{ $cn->copies }],
877                                                           deleted => 'f' }
878                                                 ) if ($cn && @{ $cn->copies });
879                                 }
880                         } elsif ($hold->hold_type eq 'V') {
881                                 my ($vtree) = $self
882                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
883                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
884
885                                 push @$all_copies,
886                                         asset::copy->search_where(
887                                                 { id => [map {$_->id} @{ $vtree->copies }],
888                                                   deleted => 'f' }
889                                         ) if ($vtree && @{ $vtree->copies });
890                                         
891                         } elsif  ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
892                                 my $_cp = asset::copy->retrieve($hold->target);
893                                 push @$all_copies, $_cp if $_cp;
894                         }
895
896                         # trim unholdables
897                         @$all_copies = grep {   isTrue($_->status->holdable) && 
898                                                 isTrue($_->location->holdable) && 
899                                                 isTrue($_->holdable) &&
900                                                 !isTrue($_->deleted)
901                                         } @$all_copies;
902
903                         # let 'em know we're still working
904                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
905                         
906                         # if we have no copies ...
907                         if (!ref $all_copies || !@$all_copies) {
908                                 $log->info("\tNo copies available for targeting at all!\n");
909                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
910
911                                 $hold->update( { prev_check_time => 'today', current_copy => undef } );
912                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
913                                 die "OK\n";
914                         }
915
916                         my $copy_count = @$all_copies;
917
918                         # map the potentials, so that we can pick up checkins
919                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
920                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
921
922                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
923
924                         my @good_copies;
925                         for my $c (@$all_copies) {
926                                 # current target
927                                 next if ($c->id eq $hold->current_copy);
928
929                                 # circ lib is closed
930                                 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
931
932                                 # target of another hold
933                                 next if (action::hold_request
934                                                 ->search_where(
935                                                         { current_copy => $c->id,
936                                                           fulfillment_time => undef,
937                                                           cancel_time => undef,
938                                                         }
939                                                 )
940                                 );
941
942                                 # we passed all three, keep it
943                                 push @good_copies, $c if ($c);
944                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
945                         }
946
947                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
948
949                         my $old_best = $hold->current_copy;
950                         $hold->update({ current_copy => undef }) if ($old_best);
951         
952                         if (!scalar(@good_copies)) {
953                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
954                                 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
955                                         # the old copy is still available
956                                         $log->debug("\tPushing current_copy back onto the targeting list");
957                                         push @good_copies, $old_best;
958                                 } else {
959                                         # oops, old copy is not available
960                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
961                                         $hold->update( { prev_check_time => 'today' } );
962                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
963                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
964                                         die "OK\n";
965                                 }
966                         }
967
968                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
969                         my $prox_list = [];
970                         $$prox_list[0] =
971                         [
972                                 grep {
973                                         $_->circ_lib == $hold->pickup_lib
974                                 } @good_copies
975                         ];
976
977                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
978
979                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
980                         my $best = choose_nearest_copy($hold, $prox_list);
981                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
982
983                         if (!$best) {
984                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
985                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
986
987                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
988
989                                 $best = choose_nearest_copy($hold, $prox_list);
990                         }
991
992                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
993                         if ($old_best) {
994                                 # hold wasn't fulfilled, record the fact
995                         
996                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
997                                 action::unfulfilled_hold_list->create(
998                                                 { hold => ''.$hold->id,
999                                                   current_copy => ''.$old_best->id,
1000                                                   circ_lib => ''.$old_best->circ_lib,
1001                                                 });
1002                         }
1003
1004                         if ($best) {
1005                                 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1006                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1007                         } elsif (
1008                                 $old_best &&
1009                                 action::hold_request
1010                                         ->search_where(
1011                                                 { current_copy => $old_best->id,
1012                                                   fulfillment_time => undef,
1013                                                   cancel_time => undef,
1014                                                 }       
1015                                         )
1016                         ) {     
1017                                 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1018                                 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1019                         } else {
1020                                 $hold->update( { prev_check_time => 'now' } );
1021                                 $log->info( "\tThere were no targetable copies for the hold" );
1022                         }
1023
1024                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1025                         $log->info("\tProcessing of hold ".$hold->id." complete.");
1026
1027                         push @successes,
1028                                 { hold => $hold->id,
1029                                   old_target => ($old_best ? $old_best->id : undef),
1030                                   eligible_copies => $copy_count,
1031                                   target => ($best ? $best->id : undef) };
1032
1033                 } otherwise {
1034                         my $e = shift;
1035                         if ($e !~ /^OK/o) {
1036                                 $log->error("Processing of hold failed:  $e");
1037                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1038                                 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1039                         }
1040                 };
1041         }
1042
1043         return \@successes;
1044 }
1045 __PACKAGE__->register_method(
1046         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1047         api_level       => 1,
1048         method          => 'new_hold_copy_targeter',
1049 );
1050
1051 my $locations;
1052 my $statuses;
1053 my %cache = (titles => {}, cns => {});
1054 sub hold_copy_targeter {
1055         my $self = shift;
1056         my $client = shift;
1057         my $check_expire = shift;
1058         my $one_hold = shift;
1059
1060         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1061         $self->{user_filter}->connect;
1062         $self->{client} = $client;
1063
1064         my $time = time;
1065         $check_expire ||= '12h';
1066         $check_expire = interval_to_seconds( $check_expire );
1067
1068         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1069         $year += 1900;
1070         $mon += 1;
1071         my $expire_threshold = sprintf(
1072                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1073                 $year, $mon, $mday, $hour, $min, $sec
1074         );
1075
1076
1077         $statuses ||= [ config::copy_status->search(holdable => 't') ];
1078
1079         $locations ||= [ asset::copy_location->search(holdable => 't') ];
1080
1081         my $holds;
1082
1083         %cache = (titles => {}, cns => {});
1084
1085         try {
1086                 if ($one_hold) {
1087                         $holds = [ action::hold_request->search(id => $one_hold) ];
1088                 } else {
1089                         $holds = [ action::hold_request->search_where(
1090                                                         { capture_time => undef,
1091                                                           prev_check_time => { '<=' => $expire_threshold },
1092                                                         },
1093                                                         { order_by => 'request_time,prev_check_time' } ) ];
1094                         push @$holds, action::hold_request->search_where(
1095                                                         { capture_time => undef,
1096                                                           prev_check_time => undef,
1097                                                         },
1098                                                         { order_by => 'request_time' } );
1099                 }
1100         } catch Error with {
1101                 my $e = shift;
1102                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1103         };
1104
1105         for my $hold (@$holds) {
1106                 try {
1107                         #action::hold_request->db_Main->begin_work;
1108                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1109                                 $client->respond("Cleaning up after previous transaction\n");
1110                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1111                         }
1112                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1113                         $client->respond("Processing hold ".$hold->id."...\n");
1114
1115                         my $copies;
1116
1117                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1118                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1119
1120                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1121                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1122                         
1123                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1124                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1125                         
1126                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1127
1128                         unless (ref $copies || !@$copies) {
1129                                 $client->respond("\tNo copies available for targeting at all!\n");
1130                         }
1131
1132                         my @good_copies;
1133                         for my $c (@$copies) {
1134                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1135                                 push @good_copies, $c if ($c);
1136                         }
1137
1138                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1139
1140                         my $old_best = $hold->current_copy;
1141                         $hold->update({ current_copy => undef });
1142         
1143                         if (!scalar(@good_copies)) {
1144                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1145                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
1146                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
1147                                         push @good_copies, asset::copy->retrieve( $old_best );
1148                                 } else {
1149                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1150                                         next;
1151                                 }
1152                         }
1153
1154                         my $prox_list;
1155                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1156                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1157
1158                         my $best = choose_nearest_copy($hold, $prox_list);
1159
1160                         if (!$best) {
1161                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1162                                 $best = choose_nearest_copy($hold, $prox_list);
1163                         }
1164
1165                         if ($old_best) {
1166                                 # hold wasn't fulfilled, record the fact
1167                         
1168                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1169                                 action::unfulfilled_hold_list->create(
1170                                                 { hold => ''.$hold->id,
1171                                                   current_copy => ''.$old_best->id,
1172                                                   circ_lib => ''.$old_best->circ_lib,
1173                                                 });
1174                         }
1175
1176                         if ($best) {
1177                                 $hold->update( { current_copy => ''.$best->id } );
1178                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1179                         }
1180
1181                         $hold->update( { prev_check_time => 'now' } );
1182                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1183
1184                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1185                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
1186
1187                         #action::hold_request->dbi_commit;
1188
1189                 } otherwise {
1190                         my $e = shift;
1191                         $log->error("Processing of hold failed:  $e");
1192                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1193                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1194                         #action::hold_request->dbi_rollback;
1195                 };
1196         }
1197
1198         $self->{user_filter}->disconnect;
1199         $self->{user_filter}->finish;
1200         delete $$self{user_filter};
1201         return undef;
1202 }
1203 __PACKAGE__->register_method(
1204         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1205         api_level       => 0,
1206         stream          => 1,
1207         method          => 'hold_copy_targeter',
1208 );
1209
1210
1211 sub copy_hold_capture {
1212         my $self = shift;
1213         my $hold = shift;
1214         my $cps = shift;
1215
1216         if (!defined($cps)) {
1217                 try {
1218                         $cps = [ asset::copy->search( id => $hold->target ) ];
1219                 } catch Error with {
1220                         my $e = shift;
1221                         die "Could not retrieve initial volume list:\n\n$e\n";
1222                 };
1223         }
1224
1225         my @copies = grep { $_->holdable } @$cps;
1226
1227         for (my $i = 0; $i < @$cps; $i++) {
1228                 next unless $$cps[$i];
1229                 
1230                 my $cn = $cache{cns}{$copies[$i]->call_number};
1231                 my $rec = $cache{titles}{$cn->record};
1232                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1233                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1234                 $copies[$i] = undef if (
1235                         !$copies[$i] ||
1236                         !$self->{user_filter}->request(
1237                                 'open-ils.circ.permit_hold',
1238                                 $hold->to_fieldmapper, do {
1239                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1240                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1241                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1242                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1243                                         $cp_fm;
1244                                 },
1245                                 { title => $rec->to_fieldmapper,
1246                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1247                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1248                                 })->gather(1)
1249                 );
1250                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1251         }
1252
1253         @copies = grep { $_ } @copies;
1254
1255         my $count = @copies;
1256
1257         return unless ($count);
1258         
1259         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1260         
1261         my @maps;
1262         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1263         for my $c (@copies) {
1264                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1265         }
1266         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1267
1268         return \@copies;
1269 }
1270
1271
1272 sub choose_nearest_copy {
1273         my $hold = shift;
1274         my $prox_list = shift;
1275
1276         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1277                 next unless (ref $$prox_list[$p]);
1278
1279                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1280                 next unless (@capturable);
1281
1282                 my $rand = int(rand(scalar(@capturable)));
1283                 while (my ($c) = splice(@capturable,$rand)) {
1284                         return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1285                                 { title => $c->call_number->record->to_fieldmapper,
1286                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1287                                   patron => $hold->usr->to_fieldmapper,
1288                                   copy => $c->to_fieldmapper,
1289                                   requestor => $hold->requestor->to_fieldmapper,
1290                                   request_lib => $hold->request_lib->to_fieldmapper,
1291                                    pickup_lib => $hold->pickup_lib->id,
1292                                 }
1293                         ));
1294
1295                         last unless(@capturable);
1296                         $rand = int(rand(scalar(@capturable)));
1297                 }
1298         }
1299 }
1300
1301 sub create_prox_list {
1302         my $self = shift;
1303         my $lib = shift;
1304         my $copies = shift;
1305
1306         my @prox_list;
1307         for my $cp (@$copies) {
1308                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1309                 next unless (defined($prox));
1310                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1311                 push @{$prox_list[$prox]}, $cp;
1312         }
1313         return \@prox_list;
1314 }
1315
1316 sub volume_hold_capture {
1317         my $self = shift;
1318         my $hold = shift;
1319         my $vols = shift;
1320
1321         if (!defined($vols)) {
1322                 try {
1323                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1324                         $cache{cns}{$_->id} = $_ for (@$vols);
1325                 } catch Error with {
1326                         my $e = shift;
1327                         die "Could not retrieve initial volume list:\n\n$e\n";
1328                 };
1329         }
1330
1331         my @v_ids = map { $_->id } @$vols;
1332
1333         my $cp_list;
1334         try {
1335                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1336         
1337         } catch Error with {
1338                 my $e = shift;
1339                 warn "Could not retrieve copy list:\n\n$e\n";
1340         };
1341
1342         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1343 }
1344
1345 sub title_hold_capture {
1346         my $self = shift;
1347         my $hold = shift;
1348         my $titles = shift;
1349
1350         if (!defined($titles)) {
1351                 try {
1352                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1353                         $cache{titles}{$_->id} = $_ for (@$titles);
1354                 } catch Error with {
1355                         my $e = shift;
1356                         die "Could not retrieve initial title list:\n\n$e\n";
1357                 };
1358         }
1359
1360         my @t_ids = map { $_->id } @$titles;
1361         my $cn_list;
1362         try {
1363                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1364         
1365         } catch Error with {
1366                 my $e = shift;
1367                 warn "Could not retrieve volume list:\n\n$e\n";
1368         };
1369
1370         $cache{cns}{$_->id} = $_ for (@$cn_list);
1371
1372         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1373 }
1374
1375 sub metarecord_hold_capture {
1376         my $self = shift;
1377         my $hold = shift;
1378
1379         my $titles;
1380         try {
1381                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1382         
1383         } catch Error with {
1384                 my $e = shift;
1385                 die "Could not retrieve initial title list:\n\n$e\n";
1386         };
1387
1388         try {
1389                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1390
1391                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1392         
1393         } catch Error with {
1394                 my $e = shift;
1395                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1396         };
1397
1398
1399         $cache{titles}{$_->id} = $_ for (@$titles);
1400         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1401 }
1402
1403 1;