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