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