2ad5f6e4b2df4cc3bcc1784e74e72302ac908792
[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                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
458                                 $log->debug("Cleaning up after previous transaction\n");
459                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
460                         }
461                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
462                         $log->info("Processing circ ".$c->id."...\n");
463
464
465                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
466         
467                         my $due = $due_dt->epoch;
468                         my $now = time;
469                         my $fine_interval = interval_to_seconds( $c->fine_interval );
470         
471                         if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {  
472                                 my $tz_offset_s = 0;
473                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
474                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
475                                 }
476         
477                                 $due -= ($due % $fine_interval) + $tz_offset_s;
478                                 $now -= ($now % $fine_interval) + $tz_offset_s;
479                         }
480         
481                         $client->respond(
482                                 "ARG! Overdue circulation ".$c->id.
483                                 " for item ".$c->target_copy.
484                                 " (user ".$c->usr.").\n".
485                                 "\tItem was due on or before: ".localtime($due)."\n");
486         
487                         my @fines = money::billing->search_where(
488                                 { xact => $c->id, billing_type => 'Overdue materials' },
489                                 { order_by => 'billing_ts DESC'}
490                         );
491
492                         my $f_idx = 0;
493                         my $fine = $fines[$f_idx] if (@fines);
494                         if ($overbill) {
495                                 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
496                         }
497
498                         my $current_fine_total = 0;
499                         $current_fine_total += $_->amount for (grep { $_ and !$_->voided } @fines);
500         
501                         my $last_fine;
502                         if ($fine) {
503                                 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
504                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
505                         } else {
506                                 $last_fine = $due;
507
508                                 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
509                                 #$last_fine += $fine_interval * $grace;
510                         }
511         
512                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1; 
513                         if ($pending_fine_count < 1) {
514                                 $client->respond( "\tNo fines to create.  " );
515                                 if ($grace && $now < $due + $fine_interval * $grace) {
516                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
517                                 } else {
518                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
519                                 }
520                                 next;
521                         }
522         
523                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
524         
525                         for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
526         
527                                 if ($current_fine_total > $c->max_fine) {
528                                         $c->update({stop_fines => 'MAXFINES'});
529                                         $client->respond(
530                                                 "\tMaximum fine level of ".$c->max_fine.
531                                                 " reached for this circulation.\n".
532                                                 "\tNo more fines will be generated.\n" );
533                                         last;
534                                 }
535                                 
536                                 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
537
538                                 my $dow = $billing_ts->dow;
539                                 my $dow_open = "dow_${dow}_open";
540                                 my $dow_close = "dow_${dow}_close";
541
542                                 if (my $hoo = actor::org_unit::hours_of_operation->retrieve( $c->circ_lib )) {
543                                         next if ( $hoo->$dow_open eq '00:00:00' and $hoo->$dow_close eq '00:00:00');
544                                 }
545
546                                 my $timestamptz = $billing_ts->strftime('%FT%T%z');
547                                 my @cl = actor::org_unit::closed_date->search_where(
548                                                 { close_start   => { '<=' => $timestamptz },
549                                                   close_end     => { '>=' => $timestamptz },
550                                                   org_unit      => $c->circ_lib }
551                                 );
552                                 next if (@cl);
553         
554                                 my $billing = money::billing->create(
555                                         { xact          => ''.$c->id,
556                                           note          => "System Generated Overdue Fine",
557                                           billing_type  => "Overdue materials",
558                                           amount        => ''.$c->recuring_fine,
559                                           billing_ts    => $timestamptz,
560                                         }
561                                 );
562
563                                 $current_fine_total += $billing->amount;
564         
565                                 $client->respond(
566                                         "\t\tCreating fine of ".$billing->amount." for period starting ".
567                                         localtime(
568                                                 $parser->parse_datetime(
569                                                         clense_ISO8601( $billing->billing_ts )
570                                                 )->epoch
571                                         )."\n" );
572                         }
573
574                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
575
576                         $penalty->request(
577                                 'open-ils.penalty.patron_penalty.calculate',
578                                 { patron        => $c->usr->to_fieldmapper,
579                                   update        => 1,
580                                   background    => 1,
581                                 }
582                         )->gather(1);
583
584                 } catch Error with {
585                         my $e = shift;
586                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
587                         $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
588                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
589                 };
590         }
591 }
592 __PACKAGE__->register_method(
593         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
594         api_level       => 1,
595         stream          => 1,
596         method          => 'generate_fines',
597 );
598
599
600
601 sub new_hold_copy_targeter {
602         my $self = shift;
603         my $client = shift;
604         my $check_expire = shift;
605         my $one_hold = shift;
606
607         local $OpenILS::Application::Storage::WRITE = 1;
608
609         my $holds;
610
611         try {
612                 if ($one_hold) {
613                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
614                 } elsif ( $check_expire ) {
615
616                         my $time = time;
617                         $check_expire ||= '12h';
618                         $check_expire = interval_to_seconds( $check_expire );
619
620                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
621                         $year += 1900;
622                         $mon += 1;
623                         my $expire_threshold = sprintf(
624                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
625                                 $year, $mon, $mday, $hour, $min, $sec
626                         );
627
628                         $holds = [ action::hold_request->search_where(
629                                                         { capture_time => undef,
630                                                           fulfillment_time => undef,
631                                                           cancel_time => undef,
632                                                           prev_check_time => { '<=' => $expire_threshold },
633                                                         },
634                                                         { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
635                         push @$holds, action::hold_request->search(
636                                                         capture_time => undef,
637                                                         fulfillment_time => undef,
638                                                         prev_check_time => undef,
639                                                         cancel_time => undef,
640                                                         { order_by => 'selection_depth DESC, request_time' } );
641                 } else {
642                         $holds = [ action::hold_request->search(
643                                                         capture_time => undef,
644                                                         fulfillment_time => undef,
645                                                         prev_check_time => undef,
646                                                         cancel_time => undef,
647                                                         { order_by => 'selection_depth DESC, request_time' } ) ];
648                 }
649         } catch Error with {
650                 my $e = shift;
651                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
652         };
653
654         my @successes;
655
656         for my $hold (@$holds) {
657                 try {
658                         #action::hold_request->db_Main->begin_work;
659                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
660                                 $log->debug("Cleaning up after previous transaction\n");
661                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
662                         }
663                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
664                         $log->info("Processing hold ".$hold->id."...\n");
665
666                         my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
667                         $_->delete for (@oldmaps);
668
669         
670                         my $all_copies = [];
671
672                         my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
673
674                         # find all the potential copies
675                         if ($hold->hold_type eq 'M') {
676                                 for my $r ( map
677                                                 {$_->record}
678                                                 metabib::record_descriptor
679                                                         ->search(
680                                                                 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
681                                                                 ( $types   ? (item_type => [split '', $types])   : () ),
682                                                                 ( $formats ? (item_form => [split '', $formats]) : () ),
683                                                                 ( $lang    ? (item_lang => $lang)                : () ),
684                                                         )
685                                 ) {
686                                         my ($rtree) = $self
687                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
688                                                 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
689
690                                         for my $cn ( @{ $rtree->call_numbers } ) {
691                                                 push @$all_copies,
692                                                         asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
693                                         }
694                                 }
695                         } elsif ($hold->hold_type eq 'T') {
696                                 my ($rtree) = $self
697                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
698                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
699
700                                 unless ($rtree) {
701                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
702                                         die 'OK';
703                                 }
704
705                                 for my $cn ( @{ $rtree->call_numbers } ) {
706                                         push @$all_copies,
707                                                 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
708                                 }
709                         } elsif ($hold->hold_type eq 'V') {
710                                 my ($vtree) = $self
711                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
712                                         ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
713
714                                 push @$all_copies,
715                                         asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
716                                         
717                         } elsif  ($hold->hold_type eq 'C') {
718
719                                 $all_copies = [asset::copy->retrieve($hold->target)];
720                         }
721
722                         @$all_copies = grep {   $_->status->holdable && 
723                                                 $_->location->holdable && 
724                                                 $_->holdable
725                                         } @$all_copies;
726
727                         # let 'em know we're still working
728                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
729                         
730                         if (!ref $all_copies || !@$all_copies) {
731                                 $log->info("\tNo copies available for targeting at all!\n");
732                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
733                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
734                                 die 'OK';
735                         }
736
737                         my $copy_count = @$all_copies;
738
739                         # map the potentials, so that we can pick up checkins
740                         $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
741                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
742
743                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
744
745                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
746                         $year += 1900;
747                         $mon += 1;
748                         my $today= sprintf( '%s-%0.2d-%0.2d', $year, $mon, $mday );
749
750                         my @closed = actor::org_unit::closed_date->search_where(
751                                 { close_start => { '<=', $today },
752                                   close_end => { '>=', $today } }
753                         );
754
755                         my @good_copies;
756                         for my $c (@$all_copies) {
757                                 next if ($c->id == $hold->current_copy);
758                                 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
759                                 next if (action::hold_request
760                                                 ->search_where(
761                                                         { current_copy => $c->id,
762                                                           capture_time => undef,
763                                                           cancel_time => undef,
764                                                         }
765                                                 )
766                                 );
767                                 push @good_copies, $c if ($c);
768                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
769                         }
770
771                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
772
773                         my $old_best = $hold->current_copy;
774                         $hold->update({ current_copy => undef });
775         
776                         if (!scalar(@good_copies)) {
777                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
778                                 if (
779                                   $old_best &&
780                                   grep { $old_best eq $_ } @$all_copies &&
781                                   !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
782                                 ) {
783                                         $log->debug("\tPushing current_copy back onto the targeting list");
784                                         push @good_copies, $old_best;
785                                 } else {
786                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
787                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
788                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
789                                         die 'OK';
790                                 }
791                         }
792
793                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
794                         my $prox_list = [];
795                         $$prox_list[0] =
796                         [
797                                 grep {
798                                         $_->circ_lib == $hold->pickup_lib
799                                 } @good_copies
800                         ];
801
802                         $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
803
804                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
805                         my $best = choose_nearest_copy($hold, $prox_list);
806                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
807
808                         if (!$best) {
809                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
810                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
811
812                                 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
813
814                                 $best = choose_nearest_copy($hold, $prox_list);
815                         }
816
817                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
818                         if ($old_best) {
819                                 # hold wasn't fulfilled, record the fact
820                         
821                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
822                                 action::unfulfilled_hold_list->create(
823                                                 { hold => ''.$hold->id,
824                                                   current_copy => ''.$old_best->id,
825                                                   circ_lib => ''.$old_best->circ_lib,
826                                                 });
827                         }
828
829                         if ($best) {
830                                 $hold->update( { current_copy => ''.$best->id } );
831                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
832                         } else {
833                                 $log->info( "\tThere were no targetable copies for the hold" );
834                         }
835
836                         $hold->update( { prev_check_time => 'now' } );
837
838                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
839                         $log->info("\tProcessing of hold ".$hold->id." complete.");
840
841                         push @successes,
842                                 { hold => $hold->id,
843                                   old_target => ($old_best ? $old_best->id : undef),
844                                   eligible_copies => $copy_count,
845                                   target => ($best ? $best->id : undef) };
846
847                 } otherwise {
848                         my $e = shift;
849                         if ($e !~ /^OK/o) {
850                                 $log->error("Processing of hold failed:  $e");
851                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
852                         }
853                 };
854         }
855
856         return \@successes;
857 }
858 __PACKAGE__->register_method(
859         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
860         api_level       => 1,
861         method          => 'new_hold_copy_targeter',
862 );
863
864 my $locations;
865 my $statuses;
866 my %cache = (titles => {}, cns => {});
867 sub hold_copy_targeter {
868         my $self = shift;
869         my $client = shift;
870         my $check_expire = shift;
871         my $one_hold = shift;
872
873         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
874         $self->{user_filter}->connect;
875         $self->{client} = $client;
876
877         my $time = time;
878         $check_expire ||= '12h';
879         $check_expire = interval_to_seconds( $check_expire );
880
881         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
882         $year += 1900;
883         $mon += 1;
884         my $expire_threshold = sprintf(
885                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
886                 $year, $mon, $mday, $hour, $min, $sec
887         );
888
889
890         $statuses ||= [ config::copy_status->search(holdable => 't') ];
891
892         $locations ||= [ asset::copy_location->search(holdable => 't') ];
893
894         my $holds;
895
896         %cache = (titles => {}, cns => {});
897
898         try {
899                 if ($one_hold) {
900                         $holds = [ action::hold_request->search(id => $one_hold) ];
901                 } else {
902                         $holds = [ action::hold_request->search_where(
903                                                         { capture_time => undef,
904                                                           prev_check_time => { '<=' => $expire_threshold },
905                                                         },
906                                                         { order_by => 'request_time,prev_check_time' } ) ];
907                         push @$holds, action::hold_request->search_where(
908                                                         { capture_time => undef,
909                                                           prev_check_time => undef,
910                                                         },
911                                                         { order_by => 'request_time' } );
912                 }
913         } catch Error with {
914                 my $e = shift;
915                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
916         };
917
918         for my $hold (@$holds) {
919                 try {
920                         #action::hold_request->db_Main->begin_work;
921                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
922                                 $client->respond("Cleaning up after previous transaction\n");
923                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
924                         }
925                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
926                         $client->respond("Processing hold ".$hold->id."...\n");
927
928                         my $copies;
929
930                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
931                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
932
933                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
934                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
935                         
936                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
937                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
938                         
939                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
940
941                         unless (ref $copies || !@$copies) {
942                                 $client->respond("\tNo copies available for targeting at all!\n");
943                         }
944
945                         my @good_copies;
946                         for my $c (@$copies) {
947                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
948                                 push @good_copies, $c if ($c);
949                         }
950
951                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
952
953                         my $old_best = $hold->current_copy;
954                         $hold->update({ current_copy => undef });
955         
956                         if (!scalar(@good_copies)) {
957                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
958                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
959                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
960                                         push @good_copies, asset::copy->retrieve( $old_best );
961                                 } else {
962                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
963                                         next;
964                                 }
965                         }
966
967                         my $prox_list;
968                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
969                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
970
971                         my $best = choose_nearest_copy($hold, $prox_list);
972
973                         if (!$best) {
974                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
975                                 $best = choose_nearest_copy($hold, $prox_list);
976                         }
977
978                         if ($old_best) {
979                                 # hold wasn't fulfilled, record the fact
980                         
981                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
982                                 action::unfulfilled_hold_list->create(
983                                                 { hold => ''.$hold->id,
984                                                   current_copy => ''.$old_best->id,
985                                                   circ_lib => ''.$old_best->circ_lib,
986                                                 });
987                         }
988
989                         if ($best) {
990                                 $hold->update( { current_copy => ''.$best->id } );
991                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
992                         }
993
994                         $hold->update( { prev_check_time => 'now' } );
995                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
996
997                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
998                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
999
1000                         #action::hold_request->dbi_commit;
1001
1002                 } otherwise {
1003                         my $e = shift;
1004                         $log->error("Processing of hold failed:  $e");
1005                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1006                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1007                         #action::hold_request->dbi_rollback;
1008                 };
1009         }
1010
1011         $self->{user_filter}->disconnect;
1012         $self->{user_filter}->finish;
1013         delete $$self{user_filter};
1014         return undef;
1015 }
1016 __PACKAGE__->register_method(
1017         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
1018         api_level       => 0,
1019         stream          => 1,
1020         method          => 'hold_copy_targeter',
1021 );
1022
1023
1024 sub copy_hold_capture {
1025         my $self = shift;
1026         my $hold = shift;
1027         my $cps = shift;
1028
1029         if (!defined($cps)) {
1030                 try {
1031                         $cps = [ asset::copy->search( id => $hold->target ) ];
1032                 } catch Error with {
1033                         my $e = shift;
1034                         die "Could not retrieve initial volume list:\n\n$e\n";
1035                 };
1036         }
1037
1038         my @copies = grep { $_->holdable } @$cps;
1039
1040         for (my $i = 0; $i < @$cps; $i++) {
1041                 next unless $$cps[$i];
1042                 
1043                 my $cn = $cache{cns}{$copies[$i]->call_number};
1044                 my $rec = $cache{titles}{$cn->record};
1045                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1046                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1047                 $copies[$i] = undef if (
1048                         !$copies[$i] ||
1049                         !$self->{user_filter}->request(
1050                                 'open-ils.circ.permit_hold',
1051                                 $hold->to_fieldmapper, do {
1052                                         my $cp_fm = $copies[$i]->to_fieldmapper;
1053                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1054                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1055                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1056                                         $cp_fm;
1057                                 },
1058                                 { title => $rec->to_fieldmapper,
1059                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1060                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1061                                 })->gather(1)
1062                 );
1063                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1064         }
1065
1066         @copies = grep { $_ } @copies;
1067
1068         my $count = @copies;
1069
1070         return unless ($count);
1071         
1072         action::hold_copy_map->search( hold => $hold->id )->delete_all;
1073         
1074         my @maps;
1075         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1076         for my $c (@copies) {
1077                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1078         }
1079         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1080
1081         return \@copies;
1082 }
1083
1084
1085 sub choose_nearest_copy {
1086         my $hold = shift;
1087         my $prox_list = shift;
1088
1089         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1090                 next unless (ref $$prox_list[$p]);
1091
1092                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1093                 next unless (@capturable);
1094
1095                 my $rand = int(rand(scalar(@capturable)));
1096                 while (my ($c) = splice(@capturable,$rand)) {
1097                         unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1098                                 { title => $c->call_number->record->to_fieldmapper,
1099                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1100                                   patron => $hold->usr->to_fieldmapper,
1101                                   copy => $c->to_fieldmapper,
1102                                   requestor => $hold->requestor->to_fieldmapper,
1103                                   request_lib => $hold->request_lib->to_fieldmapper,
1104                                 }
1105                         )) {
1106                                 last unless(@capturable);
1107                                 $rand = int(rand(scalar(@capturable)));
1108                                 next;
1109                         }
1110                         return $c;
1111                 }
1112         }
1113 }
1114
1115 sub create_prox_list {
1116         my $self = shift;
1117         my $lib = shift;
1118         my $copies = shift;
1119
1120         my @prox_list;
1121         for my $cp (@$copies) {
1122                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1123                 next unless (defined($prox));
1124                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1125                 push @{$prox_list[$prox]}, $cp;
1126         }
1127         return \@prox_list;
1128 }
1129
1130 sub volume_hold_capture {
1131         my $self = shift;
1132         my $hold = shift;
1133         my $vols = shift;
1134
1135         if (!defined($vols)) {
1136                 try {
1137                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1138                         $cache{cns}{$_->id} = $_ for (@$vols);
1139                 } catch Error with {
1140                         my $e = shift;
1141                         die "Could not retrieve initial volume list:\n\n$e\n";
1142                 };
1143         }
1144
1145         my @v_ids = map { $_->id } @$vols;
1146
1147         my $cp_list;
1148         try {
1149                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1150         
1151         } catch Error with {
1152                 my $e = shift;
1153                 warn "Could not retrieve copy list:\n\n$e\n";
1154         };
1155
1156         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1157 }
1158
1159 sub title_hold_capture {
1160         my $self = shift;
1161         my $hold = shift;
1162         my $titles = shift;
1163
1164         if (!defined($titles)) {
1165                 try {
1166                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1167                         $cache{titles}{$_->id} = $_ for (@$titles);
1168                 } catch Error with {
1169                         my $e = shift;
1170                         die "Could not retrieve initial title list:\n\n$e\n";
1171                 };
1172         }
1173
1174         my @t_ids = map { $_->id } @$titles;
1175         my $cn_list;
1176         try {
1177                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1178         
1179         } catch Error with {
1180                 my $e = shift;
1181                 warn "Could not retrieve volume list:\n\n$e\n";
1182         };
1183
1184         $cache{cns}{$_->id} = $_ for (@$cn_list);
1185
1186         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1187 }
1188
1189 sub metarecord_hold_capture {
1190         my $self = shift;
1191         my $hold = shift;
1192
1193         my $titles;
1194         try {
1195                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1196         
1197         } catch Error with {
1198                 my $e = shift;
1199                 die "Could not retrieve initial title list:\n\n$e\n";
1200         };
1201
1202         try {
1203                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1204
1205                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1206         
1207         } catch Error with {
1208                 my $e = shift;
1209                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1210         };
1211
1212
1213         $cache{titles}{$_->id} = $_ for (@$titles);
1214         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1215 }
1216
1217 1;