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