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