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