]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Storage/Publisher/action.pm
moving the hold copy targeter into the storage server (speed and convenience)
[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/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::EX qw/:try/;
6 use OpenILS::Utils::Fieldmapper;
7 use DateTime;
8 use DateTime::Format::ISO8601;
9
10 my $parser = DateTime::Format::ISO8601->new;
11 my $log = 'OpenSRF::Utils::Logger';
12
13 sub grab_overdue {
14         my $self = shift;
15         my $client = shift;
16         my $grace = shift || '';
17
18         my $c_t = action::circulation->table;
19
20         $grace = " - ($grace * (fine_interval))" if ($grace);
21
22         my $sql = <<"   SQL";
23                 SELECT  *
24                   FROM  $c_t
25                   WHERE stop_fines IS NULL
26                         AND due_date < ( CURRENT_TIMESTAMP $grace)
27         SQL
28
29         my $sth = action::circulation->db_Main->prepare_cached($sql);
30         $sth->execute;
31
32         $client->respond( $_->to_fieldmapper ) for ( map { action::circulation->construct($_) } $sth->fetchall_hash );
33
34         return undef;
35
36 }
37 __PACKAGE__->register_method(
38         api_name        => 'open-ils.storage.action.circulation.overdue',
39         api_level       => 1,
40         stream          => 1,
41         method          => 'grab_overdue',
42 );
43
44 sub nearest_hold {
45         my $self = shift;
46         my $client = shift;
47         my $pl = shift;
48         my $cp = shift;
49
50         my ($id) = action::hold_request->db_Main->selectrow_array(<<"   SQL", {}, $pl,$cp);
51                 SELECT  h.id
52                   FROM  action.hold_request h
53                         JOIN action.hold_copy_map hm ON (hm.hold = h.id)
54                   WHERE h.pickup_lib = ?
55                         AND hm.target_copy = ?
56                         AND h.capture_time IS NULL
57                 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.request_time
58                 LIMIT 1
59         SQL
60         return $id;
61 }
62 __PACKAGE__->register_method(
63         api_name        => 'open-ils.storage.action.hold_request.nearest_hold',
64         api_level       => 1,
65         method          => 'nearest_hold',
66 );
67
68 sub next_resp_group_id {
69         my $self = shift;
70         my $client = shift;
71
72         # XXX This is not replication safe!!!
73
74         my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
75                 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
76         SQL
77         return $id;
78 }
79 __PACKAGE__->register_method(
80         api_name        => 'open-ils.storage.action.survey_response.next_group_id',
81         api_level       => 1,
82         method          => 'next_resp_group_id',
83 );
84
85 sub patron_circ_summary {
86         my $self = shift;
87         my $client = shift;
88         my $id = ''.shift();
89
90         return undef unless ($id);
91         my $c_table = action::circulation->table;
92         my $b_table = money::billing->table;
93
94         my $select = <<"        SQL";
95                 SELECT  COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
96                   FROM  $c_table c
97                         LEFT OUTER JOIN $b_table b ON (c.id = b.xact)
98                   WHERE c.usr = ?
99                         AND c.xact_finish IS NULL
100                         AND c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
101         SQL
102
103         return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
104 }
105 __PACKAGE__->register_method(
106         api_name        => 'open-ils.storage.action.circulation.patron_summary',
107         api_level       => 1,
108         method          => 'patron_circ_summary',
109 );
110
111 #XXX Fix stored proc calls
112 sub find_local_surveys {
113         my $self = shift;
114         my $client = shift;
115         my $ou = ''.shift();
116
117         return undef unless ($ou);
118         my $s_table = action::survey->table;
119
120         my $select = <<"        SQL";
121                 SELECT  s.*
122                   FROM  $s_table s
123                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
124                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
125         SQL
126
127         my $sth = action::survey->db_Main->prepare_cached($select);
128         $sth->execute($ou);
129
130         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
131
132         return undef;
133 }
134 __PACKAGE__->register_method(
135         api_name        => 'open-ils.storage.action.survey.all',
136         api_level       => 1,
137         stream          => 1,
138         method          => 'find_local_surveys',
139 );
140
141 #XXX Fix stored proc calls
142 sub find_opac_surveys {
143         my $self = shift;
144         my $client = shift;
145         my $ou = ''.shift();
146
147         return undef unless ($ou);
148         my $s_table = action::survey->table;
149
150         my $select = <<"        SQL";
151                 SELECT  s.*
152                   FROM  $s_table s
153                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
154                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
155                         AND s.opac IS TRUE;
156         SQL
157
158         my $sth = action::survey->db_Main->prepare_cached($select);
159         $sth->execute($ou);
160
161         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
162
163         return undef;
164 }
165 __PACKAGE__->register_method(
166         api_name        => 'open-ils.storage.action.survey.opac',
167         api_level       => 1,
168         stream          => 1,
169         method          => 'find_opac_surveys',
170 );
171
172 sub find_optional_surveys {
173         my $self = shift;
174         my $client = shift;
175         my $ou = ''.shift();
176
177         return undef unless ($ou);
178         my $s_table = action::survey->table;
179
180         my $select = <<"        SQL";
181                 SELECT  s.*
182                   FROM  $s_table s
183                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
184                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
185                         AND s.required IS FALSE;
186         SQL
187
188         my $sth = action::survey->db_Main->prepare_cached($select);
189         $sth->execute($ou);
190
191         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
192
193         return undef;
194 }
195 __PACKAGE__->register_method(
196         api_name        => 'open-ils.storage.action.survey.optional',
197         api_level       => 1,
198         stream          => 1,
199         method          => 'find_optional_surveys',
200 );
201
202 sub find_required_surveys {
203         my $self = shift;
204         my $client = shift;
205         my $ou = ''.shift();
206
207         return undef unless ($ou);
208         my $s_table = action::survey->table;
209
210         my $select = <<"        SQL";
211                 SELECT  s.*
212                   FROM  $s_table s
213                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
214                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
215                         AND s.required IS TRUE;
216         SQL
217
218         my $sth = action::survey->db_Main->prepare_cached($select);
219         $sth->execute($ou);
220
221         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
222
223         return undef;
224 }
225 __PACKAGE__->register_method(
226         api_name        => 'open-ils.storage.action.survey.required',
227         api_level       => 1,
228         stream          => 1,
229         method          => 'find_required_surveys',
230 );
231
232 sub find_usr_summary_surveys {
233         my $self = shift;
234         my $client = shift;
235         my $ou = ''.shift();
236
237         return undef unless ($ou);
238         my $s_table = action::survey->table;
239
240         my $select = <<"        SQL";
241                 SELECT  s.*
242                   FROM  $s_table s
243                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
244                   WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
245                         AND s.usr_summary IS TRUE;
246         SQL
247
248         my $sth = action::survey->db_Main->prepare_cached($select);
249         $sth->execute($ou);
250
251         $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
252
253         return undef;
254 }
255 __PACKAGE__->register_method(
256         api_name        => 'open-ils.storage.action.survey.usr_summary',
257         api_level       => 1,
258         stream          => 1,
259         method          => 'find_usr_summary_surveys',
260 );
261
262
263 sub generate_fines {
264         my $self = shift;
265         my $client = shift;
266         my $grace = shift;
267         my $circ = shift;
268         
269         
270         my @circs;
271         if ($circ) {
272                 push @circs,
273                         $self->method_lookup(
274                                 'open-ils.storage.direct.action.circulation.search_where'
275                         )->run( { id => $circ, stop_fines => undef } );
276         } else {
277                 push @circs, $self->method_lookup('open-ils.storage.action.circulation.overdue')->run( $grace );
278         }
279
280         for my $c (@circs) {
281         
282                 try {
283                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
284         
285                         my $due = $due_dt->epoch;
286                         my $now = time;
287                         my $fine_interval = interval_to_seconds( $c->fine_interval );
288         
289                         if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {  
290                                 my $tz_offset_s = 0;;
291                                 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
292                                         $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m"); 
293                                 }
294         
295                                 $due -= ($due % $fine_interval) + $tz_offset_s;
296                                 $now -= ($now % $fine_interval) + $tz_offset_s;
297                         }
298         
299                         $client->respond(
300                                 "ARG! Overdue circulation ".$c->id.
301                                 " for item ".$c->target_copy.
302                                 " (user ".$c->usr.").\n".
303                                 "\tItem was due on or before: ".localtime($due)."\n");
304         
305                         my ($fine) = $self->method_lookup('open-ils.storage.direct.money.billing.search')->run(
306                                 { xact => $c->id, voided => 'f' },
307                                 { order_by => 'billing_ts DESC', limit => '1' }
308                         );
309         
310                         my $last_fine;
311                         if ($fine) {
312                                 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
313                         } else {
314                                 $last_fine = $due;
315                                 $last_fine += $fine_interval * $grace;
316                         }
317         
318                         my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ); 
319                         unless($pending_fine_count) {
320                                 $client->respond( "\tNo fines to create.  " );
321                                 if ($grace && $now < $due + $fine_interval * $grace) {
322                                         $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
323                                 } else {
324                                         $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
325                                 }
326                                 next;
327                         }
328         
329                         $client->respond( "\t$pending_fine_count pending fine(s)\n" );
330         
331                         for my $bill (1 .. $pending_fine_count) {
332         
333                                 my ($total) = $self->method_lookup('open-ils.storage.direct.money.billable_transaction_summary.retrieve')->run( $c->id );
334         
335                                 if ($total && $total->balance_owed > $c->max_fine) {
336                                         $c->stop_fines('MAXFINES');
337                                         $self->method_lookup('open-ils.storage.direct.action.circulation.update')->run( $c );
338                                         $client->respond(
339                                                 "\tMaximum fine level of ".$c->max_fine.
340                                                 " reached for this circulation.\n".
341                                                 "\tNo more fines will be generated.\n" );
342                                         last;
343                                 }
344         
345                                 my $billing = new Fieldmapper::money::billing;
346                                 $billing->xact( $c->id );
347                                 $billing->note( "Overdue Fine" );
348                                 $billing->amount( $c->recuring_fine );
349         
350                                 $billing->billing_ts(
351                                         DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
352                                 );
353         
354                                 $client->respond(
355                                         "\t\tCreating fine of ".$billing->amount." for period starting ".
356                                         localtime(
357                                                 $parser->parse_datetime(
358                                                         clense_ISO8601( $billing->billing_ts )
359                                                 )->epoch
360                                         )."\n" );
361         
362                                 $self->method_lookup('open-ils.storage.direct.money.billing.create')->run( $billing );
363                         }
364                 } catch Error with {
365                         my $e = shift;
366                         $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
367                 };
368         }
369 }
370 __PACKAGE__->register_method(
371         api_name        => 'open-ils.storage.action.circulation.overdue.generate_fines',
372         api_level       => 1,
373         stream          => 1,
374         method          => 'generate_fines',
375 );
376
377
378
379 my $locations;
380 my $statuses;
381 my $user_filter;
382 my %cache = (titles => {}, cns => {});
383 sub hold_copy_targeter {
384         my $self = shift;
385         my $client = shift;
386         my $check_expire = shift;
387         my $one_hold = shift;
388
389         $user_filter ||= $self->method_lookup('open-ils.circ.permit_hold');
390
391         my $time = time;
392         $check_expire ||= '12h';
393         $check_expire = interval_to_seconds( $check_expire );
394
395         my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time - $check_expire);
396         $year += 1900;
397         $mon += 1;
398         my $expire_threshold = sprintf(
399                 '%s-%0.2d-%0.2dT%s:%0.2d:%0.s2-00',
400                 $year, $mon, $mday, $hour, $min, $sec
401         );
402
403         ($statuses) = $self->method_lookup('open-ils.storage.direct.config.copy_status.search.holdable.atomic')->run('t');
404
405         ($locations) = $self->method_lookup('open-ils.storage.direct.asset.copy_location.search.holdable.atomic')->run('t');
406
407         my $holds;
408
409         %cache = (titles => {}, cns => {});
410
411         try {
412                 if ($one_hold) {
413                         ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search.atomic')
414                                                 ->run(id => $one_hold);
415                 } else {
416                         ($holds) = $self->method_lookup('open-ils.storage.direct.action.hold_request.search_where.atomic')
417                                                 ->run(
418                                                         { capture_time => undef,
419                                                           prev_check_time => { '<=' => $expire_threshold },
420                                                         },
421                                                         { order_by => 'request_time,prev_check_time' } );
422                         push @$holds, @{
423                                 $self->method_lookup('open-ils.storage.direct.action.hold_request.search.atomic')
424                                                 ->run(
425                                                         { capture_time => undef,
426                                                           prev_check_time => undef },
427                                                         { order_by => 'request_time' } ) };
428                 }
429         } catch Error with {
430                 my $e = shift;
431                 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
432         };
433
434         $_->clear_current_copy for (@$holds);
435
436         for my $hold (@$holds) {
437                 my $copies;
438
439                 my @captured_copies = [ map {$_->current_copy} @$holds ];
440
441                 if (0) { # hold isn't check-expired
442                         # get the copies from the hold-map
443                         # and filter on "avialable"
444                 } else {
445                         $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
446                         $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
447                         $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
448                         $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
449                 }
450
451                 next unless (ref $copies);
452
453                 my @good_copies;
454                 for my $c (@$copies) {
455                         next if ( grep {$c->id == $_} @captured_copies);
456                         push @good_copies, $c;
457                 }
458
459                 my $prox_list;
460                 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @$copies];
461                 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @$copies];
462
463                 my $best = $self->choose_nearest_copy($hold, $prox_list);
464
465                 if (!$best) {
466                         $prox_list = $self->create_prox_list( $hold->pickup_lib, $copies );
467                         $best = $self->choose_nearest_copy($hold, $prox_list);
468                 }
469
470                 if ($best) {
471                         $hold->current_copy( $best->id );
472                 }
473
474                 $hold->prev_check_time( 'now');
475                 my ($r) = $self->method_lookup('open-ils.storage.direct.action.hold_request.update')->run( $hold );
476
477                 $client->respond("Processed hold ".$hold->id.".  ".
478                         do{ $hold->current_copy ? "Targeting copy ".$hold->current_copy." for capture." : ''; }.
479                         "\n"
480                 );
481         }
482         return undef;
483 }
484 __PACKAGE__->register_method(
485         api_name        => 'open-ils.storage.action.hold_request.copy_targeter',
486         api_level       => 1,
487         stream          => 1,
488         method          => 'hold_copy_targeter',
489 );
490
491
492
493 sub copy_hold_capture {
494         my $self = shift;
495         my $hold = shift;
496         my $cps = shift;
497
498         if (!defined($cps)) {
499                 try {
500                         ($cps) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.id.atomic')
501                                                 ->run( $hold->target );
502         
503                 } catch Error with {
504                         my $e = shift;
505                         die "Could not retrieve initial volume list:\n\n$e\n";
506                 };
507         }
508
509         my @copies = grep { $_->holdable == 1  and $_->ref == 0 } @$cps;
510
511         for (my $i = 0; $i < @copies; $i++) {
512                 
513                 my $cn = $cache{cns}{$copies[0]->call_number};
514                 my $rec = $cache{titles}{$cn->record};
515                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
516                 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
517                 $copies[$i] = undef if (
518                         $copies[$i] &&
519                         !($user_filter->run( $hold, $copies[$i], { title => $rec, call_number => $cn } ))[0]
520                 );
521         }
522
523         @copies = grep { defined $_ } @copies;
524
525         my $count = @copies;
526
527         return unless ($count);
528         
529         my ($old_maps) = $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.search.hold.atomic')->run( $hold->id );
530
531         $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.delete')->run(@$old_maps );
532         
533         my @maps;
534         for my $c (@copies) {
535                 my $m = new Fieldmapper::action::hold_copy_map;
536                 $m->hold( $hold->id );
537                 $m->target_copy( $c->id );
538                 $m->isnew( 1 );
539                 push @maps, $m;
540         }
541
542         $self->method_lookup('open-ils.storage.direct.action.hold_copy_map.batch.create')->run( @maps );
543
544         return \@copies;
545 }
546
547
548 sub choose_nearest_copy {
549         my $self = shift;
550         my $hold = shift;
551         my $prox_list = shift;
552
553         for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
554                 next unless (ref $$prox_list[$p]);
555                 my @capturable = grep { $_->status == 0 } @{ $$prox_list[$p] };
556                 next unless (@capturable);
557                 return $capturable[rand(scalar(@capturable))];
558         }
559 }
560
561 sub create_prox_list {
562         my $self = shift;
563         my $lib = shift;
564         my $copies = shift;
565
566         my @prox_list;
567         for my $cp (@$copies) {
568                 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
569                 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
570                 push @{$prox_list[$prox]}, $cp;
571         }
572         return \@prox_list;
573 }
574
575 sub volume_hold_capture {
576         my $self = shift;
577         my $hold = shift;
578         my $vols = shift;
579
580         if (!defined($vols)) {
581                 try {
582                         ($vols) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.id.atomic')->run( $hold->target );
583         
584                         $cache{cns}{$_->id} = $_ for (@$vols);
585
586                 } catch Error with {
587                         my $e = shift;
588                         die "Could not retrieve initial volume list:\n\n$e\n";
589                 };
590         }
591
592         my @v_ids = map { $_->id } @$vols;
593
594         my $cp_list;
595         try {
596                 ($cp_list) = $self->method_lookup('open-ils.storage.direct.asset.copy.search.call_number.atomic')->run( \@v_ids );
597         
598         } catch Error with {
599                 my $e = shift;
600                 warn "Could not retrieve copy list:\n\n$e\n";
601         };
602
603         $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
604 }
605
606 sub title_hold_capture {
607         my $self = shift;
608         my $hold = shift;
609         my $titles = shift;
610
611         if (!defined($titles)) {
612                 try {
613                         ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( $hold->target );
614         
615                         $cache{titles}{$_->id} = $_ for (@$titles);
616         
617                 } catch Error with {
618                         my $e = shift;
619                         die "Could not retrieve initial title list:\n\n$e\n";
620                 };
621         }
622
623         my @t_ids = map { $_->id } @$titles;
624         my $cn_list;
625         try {
626                 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
627         
628         } catch Error with {
629                 my $e = shift;
630                 warn "Could not retrieve volume list:\n\n$e\n";
631         };
632
633         $cache{cns}{$_->id} = $_ for (@$cn_list);
634
635         $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
636 }
637
638 sub metarecord_hold_capture {
639         my $self = shift;
640         my $hold = shift;
641
642         my $titles;
643         try {
644                 ($titles) = $self->method_lookup('open-ils.storage.ordered.metabib.metarecord.records.atomic')->run( $hold->target );
645         
646         } catch Error with {
647                 my $e = shift;
648                 die "Could not retrieve initial title list:\n\n$e\n";
649         };
650
651         try {
652                 my @recs = map {$_->record}
653                                 @{$self->method_lookup('open-ils.storage.direct.metabib.record_descriptor.search.atomic')
654                                                 ->run( record => $titles, item_type => [split '', $hold->holdable_formats] )}; 
655
656                 $titles = [];
657                 ($titles) = $self->method_lookup('open-ils.storage.direct.biblio.record_entry.search.id.atomic')->run( \@recs );
658         
659         } catch Error with {
660                 my $e = shift;
661                 die "Could not retrieve format-pruned title list:\n\n$e\n";
662         };
663
664
665         $cache{titles}{$_->id} = $_ for (@$titles);
666
667         $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);
668 }
669
670 1;