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