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