]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
adding open_noncat_circs method
[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                                 $last_fine += $fine_interval * $grace;
481                         }
482         
483                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
484                         unless($pending_fine_count) {
485                                 $client->respond( "\tNo fines to create.  " );
486                                 if ($grace && $now < $due + $fine_interval * $grace) {
487                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
488                                 } else {
489                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
490                                 }
491                                 next;
492                         }
493         
494                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
495         
496                         for my $bill (1 .. $pending_fine_count) {
497         
498                                 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
499         
500                                 if ($total && $total->balance_owed > $c->max_fine) {
501                                         $c->update({stop_fines => 'MAXFINES'});
502                                         $client->respond(
503                                                 "\tMaximum fine level of ".$c->max_fine.
504                                                 " reached for this circulation.\n".
505                                                 "\tNo more fines will be generated.\n" );
506                                         last;
507                                 }
508         
509                                 my $billing = money::billing->create(
510                                         { xact          => ''.$c->id,
511                                           note          => "Overdue Fine",
512                                           billing_type  => "Overdue materials",
513                                           amount        => ''.$c->recuring_fine,
514                                           billing_ts    => DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
515                                         }
516                                 );
517         
518                                 $client->respond(
519                                         "\t\tCreating fine of ".$billing->amount." for period starting ".
520                                         localtime(
521                                                 $parser->parse_datetime(
522                                                         clense_ISO8601( $billing->billing_ts )
523                                                 )->epoch
524                                         )."\n" );
525                         }
526
527                         $penalty->request(
528                                 'open-ils.penalty.patron_penalty.calculate',
529                                 { patron        => $c->usr->to_fieldmapper,
530                                   update        => 1,
531                                   background    => 1,
532                                 }
533                         )->gather(1);
534
535                 } catch Error with {
536                         my $e = shift;
537                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
538                 };
539         }
540 }
541 __PACKAGE__->register_method(
542         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
543         api_level       => 1,
544         stream          => 1,
545         method          => 'generate_fines',
546 );
547
548
549
550 sub new_hold_copy_targeter {
551         my $self = shift;
552         my $client = shift;
553         my $check_expire = shift;
554         my $one_hold = shift;
555
556         local $OpenILS::Application::Storage::WRITE = 1;
557
558         my $holds;
559
560         try {
561                 if ($one_hold) {
562                         $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef } ) ];
563                 } elsif ( $check_expire ) {
564
565                         my $time = time;
566                         $check_expire ||= '12h';
567                         $check_expire = interval_to_seconds( $check_expire );
568
569                         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
570                         $year += 1900;
571                         $mon += 1;
572                         my $expire_threshold = sprintf(
573                                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
574                                 $year, $mon, $mday, $hour, $min, $sec
575                         );
576
577                         $holds = [ action::hold_request->search_where(
578                                                         { capture_time => undef,
579                                                           fulfillment_time => undef,
580                                                           prev_check_time => { '<=' => $expire_threshold },
581                                                         },
582                                                         { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
583                         push @$holds, action::hold_request->search(
584                                                         capture_time => undef,
585                                                         fulfillment_time => undef,
586                                                         prev_check_time => undef,
587                                                         { order_by => 'selection_depth DESC, request_time' } );
588                 } else {
589                         $holds [ action::hold_request->search(
590                                                         capture_time => undef,
591                                                         fulfillment_time => undef,
592                                                         prev_check_time => undef,
593                                                         { order_by => 'selection_depth DESC, request_time' } ) ];
594                 }
595         } catch Error with {
596                 my $e = shift;
597                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
598         };
599
600         my @successes;
601         for my $hold (@$holds) {
602                 try {
603                         #action::hold_request->db_Main->begin_work;
604                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
605                                 $log->debug("Cleaning up after previous transaction\n");
606                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
607                         }
608                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
609                         $log->info("Processing hold ".$hold->id."...\n");
610
611                         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
612         
613                         my $all_copies = [];
614
615                         # find all the potential copies
616                         if ($hold->hold_type eq 'M') {
617                                 for my $r ( map
618                                                 {$_->record}
619                                                 metabib::record_descriptor
620                                                         ->search(
621                                                                 record => [ map { $_->id } metabib::metarecord
622                                                                                         ->retrieve($hold->target)
623                                                                                         ->source_records ],
624                                                                 item_type => [split '', $hold->holdable_formats]
625                                                         )
626                                 ) {
627                                         my ($rtree) = $self
628                                                 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
629                                                 ->run( $r->id, $hold->usr->selection_ou, $hold->selection_depth );
630
631                                         for my $cn ( @{ $rtree->call_numbers } ) {
632                                                 push @$all_copies,
633                                                         asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
634                                         }
635                                 }
636                         } elsif ($hold->hold_type eq 'T') {
637                                 my ($rtree) = $self
638                                         ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
639                                         ->run( $hold->target, $hold->usr->selection_ou, $hold->selection_depth );
640
641                                 unless ($rtree) {
642                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
643                                         die 'OK';
644                                 }
645
646                                 for my $cn ( @{ $rtree->call_numbers } ) {
647                                         push @$all_copies,
648                                                 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
649                                 }
650                         } elsif ($hold->hold_type eq 'V') {
651                                 my ($vtree) = $self
652                                         ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
653                                         ->run( $hold->target, $hold->usr->selection_ou, $hold->selection_depth );
654
655                                 push @$all_copies,
656                                         asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
657                                         
658                         } elsif  ($hold->hold_type eq 'C') {
659
660                                 $all_copies = [asset::copy->retrieve($hold->target)];
661                         }
662
663                         @$all_copies = grep {   $_->status->holdable && 
664                                                 $_->location->holdable && 
665                                                 $_->holdable
666                                         } @$all_copies;
667
668                         # let 'em know we're still working
669                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
670                         
671                         if (!ref $all_copies || !@$all_copies) {
672                                 $log->info("\tNo copies available for targeting at all!\n");
673                                 $self->method_lookup('open-ils.storage.transaction.commit')->run;
674                                 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
675                                 die 'OK';
676                         }
677
678                         my $copies = [];
679                         for my $c ( @$all_copies ) {
680                                 push @$copies, $c
681                                         if ( OpenILS::Utils::PermitHold::permit_copy_hold(
682                                                 { title => $c->call_number->record->to_fieldmapper,
683                                                   title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
684                                                   patron => $hold->usr->to_fieldmapper,
685                                                   copy => $c->to_fieldmapper,
686                                                   requestor => $hold->requestor->to_fieldmapper,
687                                                   request_lib => $hold->request_lib->to_fieldmapper,
688                                                 } ));
689                         }
690                         my $copy_count = @$copies;
691                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
692
693                         # map the potentials, so that we can pick up checkins
694                         $log->debug( "\tMapping ".scalar(@$copies)." potential copies for hold ".$hold->id);
695                         action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$copies);
696
697                         my @good_copies;
698                         for my $c (@$copies) {
699                                 next if ($c->id == $hold->current_copy);
700                                 push @good_copies, $c if ($c);
701                         }
702
703                         $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
704
705                         my $old_best = $hold->current_copy;
706                         $hold->update({ current_copy => undef });
707         
708                         if (!scalar(@good_copies)) {
709                                 $log->info("\tNo (non-current) copies eligible to fill the hold.");
710                                 if ( $old_best && grep { $old_best == $_ } @$copies ) {
711                                         $log->debug("\tPushing current_copy back onto the targeting list");
712                                         push @good_copies, $old_best;
713                                 } else {
714                                         $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
715                                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
716                                         push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
717                                         die 'OK';
718                                 }
719                         }
720
721                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
722                         my $prox_list = [];
723                         $$prox_list[0] =
724                         [
725                                 grep {
726                                         $_->circ_lib == $hold->pickup_lib
727                                 } @good_copies
728                         ];
729
730                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
731
732                         my $best = choose_nearest_copy($hold, $prox_list);
733
734                         if (!$best) {
735                                 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$copies)." copies");
736                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
737                                 $best = choose_nearest_copy($hold, $prox_list);
738                         }
739
740                         $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
741                         if ($old_best) {
742                                 # hold wasn't fulfilled, record the fact
743                         
744                                 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
745                                 action::unfulfilled_hold_list->create(
746                                                 { hold => ''.$hold->id,
747                                                   current_copy => ''.$old_best->id,
748                                                   circ_lib => ''.$old_best->circ_lib,
749                                                 });
750                         }
751
752                         if ($best) {
753                                 $hold->update( { current_copy => ''.$best->id } );
754                                 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
755                         } else {
756                                 $log->info( "\tThere were no targetable copies for the hold" );
757                         }
758
759                         $hold->update( { prev_check_time => 'now' } );
760
761                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
762                         $log->info("\tProcessing of hold ".$hold->id." complete.");
763
764                         push @successes,
765                                 { hold => $hold->id,
766                                   old_target => ($old_best ? $old_best->id : undef),
767                                   eligible_copies => $copy_count,
768                                   target => ($best ? $best->id : undef) };
769
770                 } otherwise {
771                         my $e = shift;
772                         if ($e !~ /^OK/o) {
773                                 $log->error("Processing of hold failed:  $e");
774                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
775                         }
776                 };
777         }
778
779         return \@successes;
780 }
781 __PACKAGE__->register_method(
782         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
783         api_level       => 1,
784         method          => 'new_hold_copy_targeter',
785 );
786
787 my $locations;
788 my $statuses;
789 my %cache = (titles => {}, cns => {});
790 sub hold_copy_targeter {
791         my $self = shift;
792         my $client = shift;
793         my $check_expire = shift;
794         my $one_hold = shift;
795
796         $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
797         $self->{user_filter}->connect;
798         $self->{client} = $client;
799
800         my $time = time;
801         $check_expire ||= '12h';
802         $check_expire = interval_to_seconds( $check_expire );
803
804         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
805         $year += 1900;
806         $mon += 1;
807         my $expire_threshold = sprintf(
808                 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
809                 $year, $mon, $mday, $hour, $min, $sec
810         );
811
812
813         $statuses ||= [ config::copy_status->search(holdable => 't') ];
814
815         $locations ||= [ asset::copy_location->search(holdable => 't') ];
816
817         my $holds;
818
819         %cache = (titles => {}, cns => {});
820
821         try {
822                 if ($one_hold) {
823                         $holds = [ action::hold_request->search(id => $one_hold) ];
824                 } else {
825                         $holds = [ action::hold_request->search_where(
826                                                         { capture_time => undef,
827                                                           prev_check_time => { '<=' => $expire_threshold },
828                                                         },
829                                                         { order_by => 'request_time,prev_check_time' } ) ];
830                         push @$holds, action::hold_request->search(
831                                                         capture_time => undef,
832                                                         prev_check_time => undef,
833                                                         { order_by => 'request_time' } );
834                 }
835         } catch Error with {
836                 my $e = shift;
837                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
838         };
839
840         for my $hold (@$holds) {
841                 try {
842                         #action::hold_request->db_Main->begin_work;
843                         if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
844                                 $client->respond("Cleaning up after previous transaction\n");
845                                 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
846                         }
847                         $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
848                         $client->respond("Processing hold ".$hold->id."...\n");
849
850                         my $copies;
851
852                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
853                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
854
855                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
856                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
857                         
858                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
859                         $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
860                         
861                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
862
863                         unless (ref $copies || !@$copies) {
864                                 $client->respond("\tNo copies available for targeting at all!\n");
865                         }
866
867                         my @good_copies;
868                         for my $c (@$copies) {
869                                 next if ( grep {$c->id == $hold->current_copy} @good_copies);
870                                 push @good_copies, $c if ($c);
871                         }
872
873                         $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
874
875                         my $old_best = $hold->current_copy;
876                         $hold->update({ current_copy => undef });
877         
878                         if (!scalar(@good_copies)) {
879                                 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
880                                 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
881                                         $client->respond("\tPushing current_copy back onto the targeting list\n");
882                                         push @good_copies, asset::copy->retrieve( $old_best );
883                                 } else {
884                                         $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
885                                         next;
886                                 }
887                         }
888
889                         my $prox_list;
890                         $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
891                         $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
892
893                         my $best = choose_nearest_copy($hold, $prox_list);
894
895                         if (!$best) {
896                                 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
897                                 $best = choose_nearest_copy($hold, $prox_list);
898                         }
899
900                         if ($old_best) {
901                                 # hold wasn't fulfilled, record the fact
902                         
903                                 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
904                                 action::unfulfilled_hold_list->create(
905                                                 { hold => ''.$hold->id,
906                                                   current_copy => ''.$old_best->id,
907                                                   circ_lib => ''.$old_best->circ_lib,
908                                                 });
909                         }
910
911                         if ($best) {
912                                 $hold->update( { current_copy => ''.$best->id } );
913                                 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
914                         }
915
916                         $hold->update( { prev_check_time => 'now' } );
917                         $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
918
919                         $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
920                         $self->method_lookup('open-ils.storage.transaction.commit')->run;
921
922                         #action::hold_request->dbi_commit;
923
924                 } otherwise {
925                         my $e = shift;
926                         $log->error("Processing of hold failed:  $e");
927                         $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
928                         $self->method_lookup('open-ils.storage.transaction.rollback')->run;
929                         #action::hold_request->dbi_rollback;
930                 };
931         }
932
933         $self->{user_filter}->disconnect;
934         $self->{user_filter}->finish;
935         delete $$self{user_filter};
936         return undef;
937 }
938 __PACKAGE__->register_method(
939         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
940         api_level       => 0,
941         stream          => 1,
942         method          => 'hold_copy_targeter',
943 );
944
945
946 sub copy_hold_capture {
947         my $self = shift;
948         my $hold = shift;
949         my $cps = shift;
950
951         if (!defined($cps)) {
952                 try {
953                         $cps = [ asset::copy->search( id => $hold->target ) ];
954                 } catch Error with {
955                         my $e = shift;
956                         die "Could not retrieve initial volume list:\n\n$e\n";
957                 };
958         }
959
960         my @copies = grep { $_->holdable } @$cps;
961
962         for (my $i = 0; $i < @$cps; $i++) {
963                 next unless $$cps[$i];
964                 
965                 my $cn = $cache{cns}{$copies[$i]->call_number};
966                 my $rec = $cache{titles}{$cn->record};
967                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
968                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
969                 $copies[$i] = undef if (
970                         !$copies[$i] ||
971                         !$self->{user_filter}->request(
972                                 'open-ils.circ.permit_hold',
973                                 $hold->to_fieldmapper, do {
974                                         my $cp_fm = $copies[$i]->to_fieldmapper;
975                                         $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
976                                         $cp_fm->location( $copies[$i]->location->to_fieldmapper );
977                                         $cp_fm->status( $copies[$i]->status->to_fieldmapper );
978                                         $cp_fm;
979                                 },
980                                 { title => $rec->to_fieldmapper,
981                                   usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
982                                   requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
983                                 })->gather(1)
984                 );
985                 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
986         }
987
988         @copies = grep { $_ } @copies;
989
990         my $count = @copies;
991
992         return unless ($count);
993         
994         action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
995         
996         my @maps;
997         $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
998         for my $c (@copies) {
999                 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1000         }
1001         $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1002
1003         return \@copies;
1004 }
1005
1006
1007 sub choose_nearest_copy {
1008         my $hold = shift;
1009         my $prox_list = shift;
1010
1011         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1012                 next unless (ref $$prox_list[$p]);
1013                 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1014                 next unless (@capturable);
1015                 return $capturable[rand(scalar(@capturable))];
1016         }
1017 }
1018
1019 sub create_prox_list {
1020         my $self = shift;
1021         my $lib = shift;
1022         my $copies = shift;
1023
1024         my @prox_list;
1025         for my $cp (@$copies) {
1026                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
1027                 next unless (defined($prox));
1028                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1029                 push @{$prox_list[$prox]}, $cp;
1030         }
1031         return \@prox_list;
1032 }
1033
1034 sub volume_hold_capture {
1035         my $self = shift;
1036         my $hold = shift;
1037         my $vols = shift;
1038
1039         if (!defined($vols)) {
1040                 try {
1041                         $vols = [ asset::call_number->search( id => $hold->target ) ];
1042                         $cache{cns}{$_->id} = $_ for (@$vols);
1043                 } catch Error with {
1044                         my $e = shift;
1045                         die "Could not retrieve initial volume list:\n\n$e\n";
1046                 };
1047         }
1048
1049         my @v_ids = map { $_->id } @$vols;
1050
1051         my $cp_list;
1052         try {
1053                 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1054         
1055         } catch Error with {
1056                 my $e = shift;
1057                 warn "Could not retrieve copy list:\n\n$e\n";
1058         };
1059
1060         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1061 }
1062
1063 sub title_hold_capture {
1064         my $self = shift;
1065         my $hold = shift;
1066         my $titles = shift;
1067
1068         if (!defined($titles)) {
1069                 try {
1070                         $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1071                         $cache{titles}{$_->id} = $_ for (@$titles);
1072                 } catch Error with {
1073                         my $e = shift;
1074                         die "Could not retrieve initial title list:\n\n$e\n";
1075                 };
1076         }
1077
1078         my @t_ids = map { $_->id } @$titles;
1079         my $cn_list;
1080         try {
1081                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1082         
1083         } catch Error with {
1084                 my $e = shift;
1085                 warn "Could not retrieve volume list:\n\n$e\n";
1086         };
1087
1088         $cache{cns}{$_->id} = $_ for (@$cn_list);
1089
1090         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1091 }
1092
1093 sub metarecord_hold_capture {
1094         my $self = shift;
1095         my $hold = shift;
1096
1097         my $titles;
1098         try {
1099                 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1100         
1101         } catch Error with {
1102                 my $e = shift;
1103                 die "Could not retrieve initial title list:\n\n$e\n";
1104         };
1105
1106         try {
1107                 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] ); 
1108
1109                 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1110         
1111         } catch Error with {
1112                 my $e = shift;
1113                 die "Could not retrieve format-pruned title list:\n\n$e\n";
1114         };
1115
1116
1117         $cache{titles}{$_->id} = $_ for (@$titles);
1118         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
1119 }
1120
1121 1;