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