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