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