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