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