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