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