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