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