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