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