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