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