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