]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/actor.pm
LP1615805 No inputs after submit in patron search (AngularJS)
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / Publisher / actor.pm
1 package OpenILS::Application::Storage::Publisher::actor;
2 use base qw/OpenILS::Application::Storage/;
3 use OpenILS::Application::Storage::CDBI::actor;
4 use OpenSRF::Utils::Logger qw/:level/;
5 use OpenILS::Utils::DateTime qw/:datetime/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenSRF::Utils::SettingsClient;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::Utils::JSON;
10 use DateTime;           
11 use DateTime::Format::ISO8601;  
12 use DateTime::Set;
13 use DateTime::SpanSet;
14
15 my $U = "OpenILS::Application::AppUtils";
16 my $JSON = "OpenSRF::Utils::JSON";
17
18 my $_dt_parser = DateTime::Format::ISO8601->new;    
19
20 my $log = 'OpenSRF::Utils::Logger';
21
22 sub new_usergroup_id {
23     return actor::user->db_Main->selectrow_array("select nextval('actor.usr_usrgroup_seq'::regclass)");
24 }
25 __PACKAGE__->register_method(
26     api_name    => 'open-ils.storage.actor.user.group_id.new',
27     api_level   => 1,
28     method      => 'new_usergroup_id',
29 );
30
31 sub juv_to_adult {
32     my $self = shift;
33     my $client = shift;
34     my $adult_age = shift;
35
36     my $sql = <<"    SQL";
37         UPDATE actor.usr
38             SET juvenile = FALSE
39             WHERE juvenile IS TRUE
40             AND deleted IS FALSE
41             AND AGE(dob) > COALESCE( BTRIM( (
42                     SELECT value FROM actor.org_unit_ancestor_setting(
43                     'global.juvenile_age_threshold', home_ou)),'"' ), ?)::INTERVAL
44     SQL
45
46     my $sth = actor::user->db_Main->prepare_cached($sql);
47     $sth->execute($adult_age);
48
49     return $sth->rows;
50 }
51 __PACKAGE__->register_method(
52     api_name    => 'open-ils.storage.actor.user.juvenile_to_adult',
53     api_level   => 1,
54     method      => 'juv_to_adult',
55 );
56
57 sub usr_total_owed {
58     my $self = shift;
59     my $client = shift;
60     my $usr = shift;
61
62     my $sql = <<"    SQL";
63             SELECT  x.usr,
64                     SUM(COALESCE((SELECT SUM(b.amount) FROM money.billing b WHERE b.voided IS FALSE AND b.xact = x.id),0.0)) -
65                         SUM(COALESCE((SELECT SUM(p.amount) FROM money.payment p WHERE p.voided IS FALSE AND p.xact = x.id),0.0))
66               FROM  money.billable_xact x
67               WHERE x.usr = ? AND x.xact_finish IS NULL
68               GROUP BY 1
69     SQL
70
71     my (undef,$val) = actor::user->db_Main->selectrow_array($sql, {}, $usr);
72
73     return $val;
74 }
75 __PACKAGE__->register_method(
76     api_name    => 'open-ils.storage.actor.user.total_owed',
77     api_level   => 1,
78     method      => 'usr_total_owed',
79 );
80
81 sub usr_breakdown_out {
82     my $self = shift;
83     my $client = shift;
84     my $usr = shift;
85
86     $self->method_lookup('open-ils.storage.transaction.begin')->run();
87
88     my $out_sql = <<"    SQL";
89             SELECT  id
90               FROM  action.circulation
91               WHERE usr = ?
92                     AND checkin_time IS NULL
93                     AND (  (fine_interval >= '1 day' AND due_date >= 'today')
94                         OR (fine_interval < '1 day'  AND due_date > 'now'   ))
95                     AND (stop_fines IS NULL
96                         OR stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE'))
97     SQL
98
99     my $out = actor::user->db_Main->selectcol_arrayref($out_sql, {}, $usr);
100
101     my $od_sql = <<"    SQL";
102             SELECT  id
103               FROM  action.circulation
104               WHERE usr = ?
105                     AND checkin_time IS NULL
106                     AND (  (fine_interval >= '1 day' AND due_date < 'today')
107                         OR (fine_interval < '1 day'  AND due_date < 'now'  ))
108                     AND (stop_fines IS NULL
109                         OR stop_fines NOT IN ('LOST','CLAIMSRETURNED','LONGOVERDUE'))
110     SQL
111
112     my $od = actor::user->db_Main->selectcol_arrayref($od_sql, {}, $usr);
113
114     my $lost_sql = <<"    SQL";
115             SELECT  id
116               FROM  action.circulation
117               WHERE usr = ? AND checkin_time IS NULL AND xact_finish IS NULL AND stop_fines = 'LOST'
118     SQL
119
120     my $lost = actor::user->db_Main->selectcol_arrayref($lost_sql, {}, $usr);
121
122     my $cl_sql = <<"    SQL";
123             SELECT  id
124               FROM  action.circulation
125               WHERE usr = ? AND checkin_time IS NULL AND stop_fines = 'CLAIMSRETURNED'
126     SQL
127
128     my $cl = actor::user->db_Main->selectcol_arrayref($cl_sql, {}, $usr);
129
130     my $lo_sql = <<"    SQL";
131             SELECT  id
132               FROM  action.circulation
133               WHERE usr = ? AND checkin_time IS NULL AND stop_fines = 'LONGOVERDUE'
134     SQL
135
136     my $lo = actor::user->db_Main->selectcol_arrayref($lo_sql, {}, $usr);
137
138     $self->method_lookup('open-ils.storage.transaction.rollback')->run();
139
140     if ($self->api_name =~/count$/o) {
141         return {    total   => scalar(@$out) + scalar(@$od) + scalar(@$lost) + scalar(@$cl) + scalar(@$lo),
142                     out     => scalar(@$out),
143                     overdue => scalar(@$od),
144                     lost    => scalar(@$lost),
145                     claims_returned => scalar(@$cl),
146                     long_overdue        => scalar(@$lo),
147         };
148     }
149
150     return {    out     => $out,
151                 overdue => $od,
152                 lost    => $lost,
153                 claims_returned => $cl,
154                 long_overdue        => $lo,
155     };
156 }
157 __PACKAGE__->register_method(
158     api_name    => 'open-ils.storage.actor.user.checked_out',
159     api_level   => 1,
160     method      => 'usr_breakdown_out',
161 );
162 __PACKAGE__->register_method(
163     api_name    => 'open-ils.storage.actor.user.checked_out.count',
164     api_level   => 1,
165     method      => 'usr_breakdown_out',
166 );
167
168 sub usr_total_out {
169     my $self = shift;
170     my $client = shift;
171     my $usr = shift;
172
173     my $sql = <<"    SQL";
174             SELECT  count(*)
175               FROM  action.circulation
176               WHERE usr = ? AND checkin_time IS NULL
177     SQL
178
179     my ($val) = actor::user->db_Main->selectrow_array($sql, {}, $usr);
180
181     return $val;
182 }
183 __PACKAGE__->register_method(
184     api_name    => 'open-ils.storage.actor.user.total_out',
185     api_level   => 1,
186     method      => 'usr_total_out',
187 );
188
189 sub calc_proximity {
190     my $self = shift;
191     my $client = shift;
192
193     local $OpenILS::Application::Storage::WRITE = 1;
194
195     my $delete_sql = <<"    SQL";
196         DELETE FROM actor.org_unit_proximity;
197     SQL
198
199     my $insert_sql = <<"    SQL";
200         INSERT INTO actor.org_unit_proximity (from_org, to_org, prox)
201             SELECT  l.id,
202                 r.id,
203                 actor.org_unit_proximity(l.id,r.id)
204               FROM  actor.org_unit l,
205                 actor.org_unit r;
206     SQL
207
208     actor::org_unit_proximity->db_Main->do($delete_sql);
209     actor::org_unit_proximity->db_Main->do($insert_sql);
210
211     return 1;
212 }
213 __PACKAGE__->register_method(
214     api_name    => 'open-ils.storage.actor.org_unit.refresh_proximity',
215     api_level   => 1,
216     method      => 'calc_proximity',
217 );
218
219 sub make_hoo_spanset {
220     my $hoo = shift;
221     return undef unless $hoo;
222
223     my $today = shift || DateTime->now;
224
225     my $tz = OpenSRF::AppSession->create('open-ils.actor')->request(
226         'open-ils.actor.ou_setting.ancestor_default' => $hoo->id.'' => 'org_unit.timezone'
227     )->gather(1) || DateTime::TimeZone->new( name => 'local' )->name;
228
229     my $current_dow = $today->day_of_week_0;
230
231     my $spanset = DateTime::SpanSet->empty_set;
232     for my $d ( 0 .. 6 ) {
233
234         my $omethod = 'dow_'.$d.'_open';
235         my $cmethod = 'dow_'.$d.'_close';
236
237         my $open = interval_to_seconds($hoo->$omethod());
238         my $close = interval_to_seconds($hoo->$cmethod());
239
240         next if ($open == $close && $open == 0);
241
242         my $dow_offset = ($d - $current_dow) * $one_day;
243         $close += $one_day if ($close <= $open);
244
245         $spanset = $spanset->union(
246             DateTime::Span->new(
247                 start => $today->clone->add( seconds => $dow_offset + $open  ),
248                 end   => $today->clone->add( seconds => $dow_offset + $close )
249             )
250         );
251     }
252
253     return $spanset->complement;
254 }
255
256 sub make_closure_spanset {
257     my $closures = shift;
258     return undef unless $closures;
259
260     my $spanset = DateTime::SpanSet->empty_set;
261     for my $k ( keys %$closures ) {
262         my $c = $$closures{$k};
263
264         $spanset = $spanset->union(
265             DateTime::Span->new(
266                 start => $_dt_parser->parse_datetime(clean_ISO8601($c->{close_start})),
267                 end   => $_dt_parser->parse_datetime(clean_ISO8601($c->{close_end}))
268             )
269         );
270     }
271
272     return $spanset;
273 }
274
275 sub new_org_closed_overlap {
276     my $self = shift;
277     my $client = shift;
278     my $ou = shift;
279     my $date = shift;
280     my $direction = shift || 0;
281     my $no_hoo = shift || 0;
282
283     return undef unless ($date && $ou);
284
285     # we're given a date and a direction, find any closures that contain the date
286     my $t = actor::org_unit::closed_date->table;
287     my $sql = <<"    SQL";
288         SELECT  *
289           FROM  $t
290           WHERE close_end > ?
291             AND org_unit = ?
292           ORDER BY close_start ASC, close_end DESC
293           LIMIT 1
294     SQL
295
296     $date = clean_ISO8601($date);
297
298     my $target_date = $_dt_parser->parse_datetime( $date );
299     my ($begin, $end) = ($target_date, $target_date);
300
301     # create a spanset from the closures that contain the $date
302     my $closure_spanset = make_closure_spanset(
303         actor::org_unit::closed_date->db_Main->selectall_hashref( $sql, 'id', {}, $date, $ou )
304     );
305
306     if ($closure_spanset && $closure_spanset->intersects( $target_date )) {
307         my $closure_intersection = $closure_spanset->intersection( $target_date );
308         $begin = $closure_intersection->min;
309         $end = $closure_intersection->max;
310
311         if ( $direction <= 0 ) {
312             $begin->subtract( minutes => 1 );
313
314             while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1, 1 ) ) {
315                 $begin = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
316             }
317         }
318
319         if ( $direction >= 0 ) {
320             $end->add( minutes => 1 );
321
322             while ( my $_a = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), 1, 1 ) ) {
323                 $end = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
324             }
325         }
326     }
327
328     if ( !$no_hoo ) {
329
330         my $begin_hoo = make_hoo_spanset(actor::org_unit::hours_of_operation->retrieve($ou), $begin);
331         my $end_hoo   = make_hoo_spanset(actor::org_unit::hours_of_operation->retrieve($ou), $end  );
332
333
334         if ( $begin_hoo && $direction <= 0 && $begin_hoo->intersects($begin) ) {
335             my $hoo_intersection = $begin_hoo->intersection( $begin );
336             $begin = $hoo_intersection->min;
337             $begin->subtract( minutes => 1 );
338
339             while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1 ) ) {
340                 $begin = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
341             }
342         }
343     
344         if ( $end_hoo && $direction >= 0 && $end_hoo->intersects($end) ) {
345             my $hoo_intersection = $end_hoo->intersection( $end );
346             $end = $hoo_intersection->max;
347             $end->add( minutes => 1 );
348
349
350             while ( my $_b = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), -1 ) ) {
351                 $end = $_dt_parser->parse_datetime( clean_ISO8601($_b->{end}) );
352             }
353         }
354     }
355
356     my $start = $begin->strftime('%FT%T%z');
357     my $stop = $end->strftime('%FT%T%z');
358
359     return undef if ($start eq $stop);
360     return { start => $start, end => $stop };
361 }
362 __PACKAGE__->register_method(
363     api_name    => 'open-ils.storage.actor.org_unit.closed_date.overlap',
364     api_level   => 0,
365     method      => 'new_org_closed_overlap',
366 );
367
368 # Check if a set of hours of operation are completely closed.
369 sub are_all_closed{
370     my $hoo = shift;
371
372     for (my $dow = 0; $dow < 7; $dow++)
373     {
374         
375         my $dow_open_meth = "dow_".$dow."_open";
376         my $dow_close_meth = "dow_".$dow."_close";
377         if ($hoo->$dow_open_meth != "00:00:00" || $hoo->$dow_close_meth != "00:00:00")
378             {return  0;}
379     }
380
381     return 1;
382 }
383
384 # Recursive method with two parts: first is checking the closures and second is checking the hours of operation
385 # Direction means whether to check forwards or backwards on the next call. Negative 1 is backwards, positive 1 is forwards - 0 means to check both, backwards then forwards
386 # Recursion terminates when returning undefined - this means stop changing the start and end times instead of meaning exit with an error.
387 sub org_closed_overlap {
388     my $self = shift;
389     my $client = shift;
390     my $ou = shift;
391     my $date = shift;
392     my $direction = shift || 0;
393     my $no_hoo = shift || 0;
394
395     return undef unless ($date && $ou);
396
397
398     my $t = actor::org_unit::closed_date->table;
399     my $sql = <<"    SQL";
400         SELECT  *
401           FROM  $t
402           WHERE ? between close_start and close_end
403             AND org_unit = ?
404           ORDER BY close_start ASC, close_end DESC
405           LIMIT 1
406     SQL
407
408     $date = clean_ISO8601($date);
409     my ($begin, $end) = ($date,$date);
410
411     my $hoo = actor::org_unit::hours_of_operation->retrieve($ou);
412     
413     # This block checks only the closures - does not consider the hours of operation. That's the next block
414     if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $date, $ou )) {
415         $begin = clean_ISO8601($closure->{close_start});
416         $end = clean_ISO8601($closure->{close_end});
417
418         if ( $direction <= 0 ) {
419             $before = $_dt_parser->parse_datetime( $begin );
420             $before->subtract( minutes => 1 );
421
422             while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1, 1 ) ) {
423                 $before = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
424             }
425             $begin = clean_ISO8601($before->strftime('%FT%T%z'));
426         }
427
428         if ( $direction >= 0 ) {
429             $after = $_dt_parser->parse_datetime( $end );
430             $after->add( minutes => 1 );
431
432             while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1, 1 ) ) {
433                 $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
434             }
435             $end = clean_ISO8601($after->strftime('%FT%T%z'));
436         }
437     }
438
439     #This block checks if the org unit's hours are open or not at the given time. If they are, it checks closures.
440     if ( !$no_hoo ) {
441         #Making sure to ignore this and take the only closure hours from the first block if all hours are closed
442         if ( $hoo && !are_all_closed($hoo)) {
443
444             
445             if ( $direction <= 0 ) {
446                 my $begin_dow = $_dt_parser->parse_datetime( $begin )->day_of_week_0;
447                 my $begin_open_meth = "dow_".$begin_dow."_open";
448                 my $begin_close_meth = "dow_".$begin_dow."_close";
449
450                 my $count = 1;
451                 while ($hoo->$begin_open_meth eq '00:00:00' and $hoo->$begin_close_meth eq '00:00:00') {
452                     $begin = clean_ISO8601($_dt_parser->parse_datetime( $begin )->subtract( days => 1)->strftime('%FT%T%z'));
453                     $begin_dow++;
454                     $begin_dow %= 7;
455                     $count++;
456                     last if ($count > 6);
457                     $begin_open_meth = "dow_".$begin_dow."_open";
458                     $begin_close_meth = "dow_".$begin_dow."_close";
459                 }
460
461                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $begin, $ou )) {
462                     $before = $_dt_parser->parse_datetime( $begin );
463                     $before->subtract( minutes => 1 );
464                     while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1 ) ) {
465                         $before = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
466                     }
467                 }
468             }
469     
470             if ( $direction >= 0 ) {
471                 my $end_dow = $_dt_parser->parse_datetime( $end )->day_of_week_0;
472                 my $end_open_meth = "dow_".$end_dow."_open";
473                 my $end_close_meth = "dow_".$end_dow."_close";
474     
475                 $count = 1;
476                 while ($hoo->$end_open_meth eq '00:00:00' and $hoo->$end_close_meth eq '00:00:00') {
477                     $end = clean_ISO8601($_dt_parser->parse_datetime( $end )->add( days => 1)->strftime('%FT%T%z'));
478                     $end_dow++;
479                     $end_dow %= 7;
480                     $count++;
481                     last if ($count > 6);
482                     $end_open_meth = "dow_".$end_dow."_open";
483                     $end_close_meth = "dow_".$end_dow."_close";
484                 }
485
486                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $end, $ou )) {
487                     $after = $_dt_parser->parse_datetime( $end );
488                     $after->add( minutes => 1 );
489
490                     while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1 ) ) {
491                         $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
492                     }
493                     $end = clean_ISO8601($after->strftime('%FT%T%z'));
494                 }
495             }
496
497         }
498     }
499
500     # If there were no changes made to the given date that means no further action should be taken - you've arrived at an acceptable date
501     if ($begin eq $date && $end eq $date) {
502         return undef;
503     }
504
505     return { start => $begin, end => $end };
506 }
507 __PACKAGE__->register_method(
508     api_name    => 'open-ils.storage.actor.org_unit.closed_date.overlap',
509     api_level   => 1,
510     method      => 'org_closed_overlap',
511 );
512
513 sub user_by_barcode {
514     my $self = shift;
515     my $client = shift;
516     my @barcodes = shift;
517
518     return undef unless @barcodes;
519
520     for my $card ( actor::card->search( { barcode => @barcodes } ) ) {
521         next unless $card;
522         if (@barcodes == 1) {
523             return $card->usr->to_fieldmapper;
524         }
525         $client->respond( $card->usr->to_fieldmapper);
526     }
527     return undef;
528 }
529 __PACKAGE__->register_method(
530     api_name    => 'open-ils.storage.direct.actor.user.search.barcode',
531     api_level   => 1,
532     method      => 'user_by_barcode',
533     stream      => 1,
534     cachable    => 1,
535 );
536
537 sub lost_barcodes {
538     my $self = shift;
539     my $client = shift;
540
541     my $c = actor::card->table;
542     my $p = actor::user->table;
543
544     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.card <> c.id";
545
546     my $list = actor::user->db_Main->selectcol_arrayref($sql);
547     for my $bc ( @$list ) {
548         $client->respond($bc);
549     }
550     return undef;
551 }
552 __PACKAGE__->register_method(
553     api_name    => 'open-ils.storage.actor.user.lost_barcodes',
554     api_level   => 1,
555     stream      => 1,
556     method      => 'lost_barcodes',
557     signature    => <<'    NOTE',
558         Returns an array of barcodes that belong to lost cards.
559         @return array of barcodes
560     NOTE
561 );
562
563 sub expired_barcodes {
564     my $self = shift;
565     my $client = shift;
566
567     my $c = actor::card->table;
568     my $p = actor::user->table;
569
570     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.expire_date < CURRENT_DATE";
571
572     my $list = actor::user->db_Main->selectcol_arrayref($sql);
573     for my $bc ( @$list ) {
574         $client->respond($bc);
575     }
576     return undef;
577 }
578 __PACKAGE__->register_method(
579     api_name    => 'open-ils.storage.actor.user.expired_barcodes',
580     api_level   => 1,
581     stream      => 1,
582     method      => 'expired_barcodes',
583     signature    => <<'    NOTE',
584         Returns an array of barcodes that are currently expired.
585         @return array of barcodes
586     NOTE
587 );
588
589 sub barred_barcodes {
590     my $self = shift;
591     my $client = shift;
592
593     my $c = actor::card->table;
594     my $p = actor::user->table;
595
596     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.barred IS TRUE";
597
598     my $list = actor::user->db_Main->selectcol_arrayref($sql);
599     for my $bc ( @$list ) {
600         $client->respond($bc);
601     }
602     return undef;
603 }
604 __PACKAGE__->register_method(
605     api_name    => 'open-ils.storage.actor.user.barred_barcodes',
606     api_level   => 1,
607     stream      => 1,
608     method      => 'barred_barcodes',
609     signature    => <<'    NOTE',
610         Returns an array of barcodes that are currently barred.
611         @return array of barcodes
612     NOTE
613 );
614
615 sub penalized_barcodes {
616     my $self = shift;
617     my $client = shift;
618
619     my $c = actor::card->table;
620     my $p = actor::user_standing_penalty->table;
621
622     my $sql = <<"    SQL";
623         SELECT  DISTINCT c.barcode
624           FROM  $c c
625             JOIN $p p USING (usr)
626             JOIN config.standing_penalty csp ON (csp.id = p.standing_penalty)
627           WHERE csp.block_list IS NOT NULL
628             AND p.set_date < CURRENT_DATE
629             AND (p.stop_date IS NULL OR p.stop_date > CURRENT_DATE);
630     SQL
631
632     my $list = actor::user->db_Main->selectcol_arrayref($sql);
633     for my $bc ( @$list ) {
634         $client->respond($bc);
635     }
636     return undef;
637 }
638 __PACKAGE__->register_method(
639     api_name    => 'open-ils.storage.actor.user.penalized_barcodes',
640     api_level   => 1,
641     stream      => 1,
642     method      => 'penalized_barcodes',
643     signature    => <<'    NOTE',
644         Returns an array of barcodes that have blocking penalties.
645         @return array of barcodes
646     NOTE
647 );
648
649 sub _prepare_name_argument {
650     # Get rid of extra spaces, accents, and regex characters
651     my ($search) = _clean_regex_chars(@_);
652     my $sth = actor::user->db_Main->prepare_cached("SELECT evergreen.unaccent_and_squash(?)");
653     $sth->execute($search);
654     my $r = $sth->fetch;
655     return ($r && @$r) ? $r->[0] : $search;
656 };
657
658 sub _clean_regex_chars {
659     my ($search) = @_;
660
661     # Escape metacharacters for SIMILAR TO 
662     # (http://www.postgresql.org/docs/8.4/interactive/functions-matching.html)
663     $search =~ s/\_/\\_/g;
664     $search =~ s/\%/\\%/g;
665     $search =~ s/\|/\\|/g;
666     $search =~ s/\*/\\*/g;
667     $search =~ s/\+/\\+/g;
668     $search =~ s/\[/\\[/g;
669     $search =~ s/\]/\\]/g;
670     $search =~ s/\(/\\(/g;
671     $search =~ s/\)/\\)/g;
672
673     return $search;
674 }
675
676 sub patron_search {
677     my $self = shift;
678     my $client = shift;
679     my $search = shift;
680     my $limit = shift || 1000;
681     my $sort = shift;
682     my $inactive = shift;
683     my $ws_ou = shift;
684     my $search_org = shift || $ws_ou;
685     my $opt_boundary = shift || 0;
686     my $offset = shift || 0;
687
688     my $penalty_sort = 0;
689
690     my $strict_opt_in = OpenSRF::Utils::SettingsClient->new->config_value( share => user => 'opt_in' );
691
692     $sort = ['family_name','first_given_name'] unless ($$sort[0]);
693     push @$sort,'id';
694
695     if ($$sort[0] eq 'penalties') {
696         shift @$sort;
697         $penalty_sort = 1;
698     }
699
700     # group 0 = user
701     # group 1 = address
702     # group 2 = phone, ident
703     # group 3 = barcode
704     # group 4 = dob
705     # group 5 = profile
706
707     # Treatment of name fields depends on whether the org has 
708     # diacritic_insensitivity turned on or off.
709
710     my $diacritic_insensitive =  $U->ou_ancestor_setting_value($ws_ou, 'circ.patron_search.diacritic_insensitive');
711     # Parse from JSON to Perl boolean (1|0):
712     $diacritic_insensitive = ($diacritic_insensitive) ? $JSON->JSON2perl($diacritic_insensitive) : 0;
713     my $usr;
714     my @usrv;
715     my $dob;
716     my @dobv;
717
718     # Compile the WHERE component of the actor.usr fields.
719     # When a name field is encountered, search both the name field and
720     # the alternate version of the name field.
721     my @name_fields = qw/prefix first_given_name second_given_name family_name suffix/;
722     my @usr_where_parts;
723
724     my @usr_fields = grep { ''.$$search{$_}{group} eq '0' } keys %$search;
725     for my $usr_field (@usr_fields) {
726
727         # sprintf template
728         my $where_func = $diacritic_insensitive ?
729             "evergreen.unaccent_and_squash(CAST(%s AS text)) ~ ?" :
730             "evergreen.lowercase(CAST(%s AS text)) ~ ?";
731
732         my $val = $diacritic_insensitive ?
733             "^" . _prepare_name_argument($$search{$usr_field}{value}) :
734             "^" . _clean_regex_chars($$search{$usr_field}{value});
735
736         if (grep {$_ eq $usr_field} @name_fields) {
737             # When searching a name field include an OR search
738             # on the alternate version of the same field.
739
740             push(@usr_where_parts, sprintf(
741                 "($where_func OR $where_func)", $usr_field, "pref_$usr_field")
742             );
743
744             # search main field and alt name field with same value.
745             push(@usrv, $val);
746             push(@usrv, $val);
747
748         } else {
749
750             push(@usr_where_parts, sprintf($where_func, $usr_field));
751             push(@usrv, $val);
752         }
753     }
754
755     $usr = join ' AND ', @usr_where_parts;
756
757     while (($key, $value) = each (%$search)) {
758         if($$search{$key}{group} eq '4') {
759             my $tval = $key;
760             $tval =~ s/dob_//g;
761             my $right = "RIGHT('0'|| ";
762             my $end = ", 2)";
763             $end = $right = '' if lc $tval eq 'year';
764             $dob .= $right."CAST(DATE_PART('$tval', dob) AS text)$end ~ ? AND ";
765         }
766     }
767     # Trim the last " AND "
768     $dob = substr($dob,0,-4);
769     @dobv = map { _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '4' } keys %$search;
770     $usr .= ' AND ' if ( $usr && $dob );
771     $usr .= $dob if $dob; # $dob not in-line above in case $usr doesn't have any search vals (only searched for dob)
772     push(@usrv, @dobv) if @dobv;
773
774     my $addr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
775     my @addrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
776
777     # should only be 1 profile sent but this construction makes dealing with the lists simpler.
778     my ($prof) = map { $$search{$_}{value} } grep {''.$$search{$_}{group} eq '5' } keys %$search;
779     $prof = int($prof) if $prof; # int or out
780
781     my $pv = _clean_regex_chars($$search{phone}{value});
782     my $iv = _clean_regex_chars($$search{ident}{value});
783     my $nv = _clean_regex_chars($$search{name}{value});
784     my $cv = _clean_regex_chars($$search{card}{value});
785
786     my $card = '';
787     if ($cv) {
788         $card = 'JOIN (SELECT DISTINCT usr FROM actor.card WHERE evergreen.lowercase(barcode) LIKE ?||\'%\') AS card ON (card.usr = users.id)';
789         unshift(@usrv, $cv);
790     }
791
792     my $phone = '';
793     my @ps;
794     my @phonev;
795     if ($pv) {
796         for my $p ( qw/day_phone evening_phone other_phone/ ) {
797             if ($pv =~ /^\d+$/) {
798                 push @ps, "evergreen.lowercase(REGEXP_REPLACE($p, '[^0-9]', '', 'g')) ~ ?";
799             } else {
800                 push @ps, "evergreen.lowercase($p) ~ ?";
801             }
802             push @phonev, "^$pv";
803         }
804         $phone = '(' . join(' OR ', @ps) . ')';
805     }
806
807     my $ident = '';
808     my @is;
809     my @identv;
810     if ($iv) {
811         for my $i ( qw/ident_value ident_value2/ ) {
812             push @is, "evergreen.lowercase($i) ~ ?";
813             push @identv, "^$iv";
814         }
815         $ident = '(' . join(' OR ', @is) . ')';
816     }
817
818     # name keywords search
819     my $name = '';
820     my @ns;
821     my @namev;
822     if ($nv) {
823         $name = "name_kw_tsvector @@ to_tsquery(?)";
824
825         # Remove characters that to_tsquery might treat as operators.
826         # Note using plainto_tsquery to ignore operators won't let us
827         # also do prefix matching.
828         $nv =~ s/[^\w\s\.\-']//g;
829
830         my @parts = split(' ', $nv);
831
832         # tsquery on multiple names joined w/ '&'
833         # Adding :* gives us prefix matching
834         push @namev, join(' & ', map { "$_:*" } @parts);
835     }
836
837     my $profile = '';
838     my @profv = ();
839     if ($prof) {
840         $profile = '(profile IN (SELECT id FROM permission.grp_descendants(?)))';
841         push @profv, $prof;
842     }
843     my $usr_where = join ' AND ', grep { $_ } ($usr,$phone,$ident,$name,$profile);
844     my $addr_where = $addr;
845
846
847     my $u_table = actor::user->table;
848     my $a_table = actor::user_address->table;
849     my $opt_in_table = actor::usr_org_unit_opt_in->table;
850     my $ou_table = actor::org_unit->table;
851
852     my $u_select = "SELECT id as id FROM $u_table u WHERE $usr_where";
853     my $a_select = "SELECT u.id as id FROM $a_table a JOIN $u_table u ON (u.mailing_address = a.id OR u.billing_address = a.id) WHERE $addr_where";
854
855     my $clone_select = '';
856
857     #$clone_select = "JOIN (SELECT cu.id as id FROM $a_table ca ".
858     #          "JOIN $u_table cu ON (cu.mailing_address = ca.id OR cu.billing_address = ca.id) ".
859     #          "WHERE $addr_where) AS clone ON (clone.id = users.id)" if ($addr_where);
860
861     my $select = '';
862     if ($usr_where) {
863         if ($addr_where) {
864             $select = "$u_select INTERSECT $a_select";
865         } else {
866             $select = $u_select;
867         }
868     } elsif ($addr_where) {
869         $select = "$a_select";
870     }
871
872     return undef if (!$select && !$card);
873
874     my $order_by = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text)) ' . (split / /,$_)[1] } @$sort;
875     my $distinct_list = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text))' } @$sort;
876     my $group_list = $distinct_list;
877
878     if ($inactive) {
879         $inactive = '';
880     } else {
881         $inactive = 'AND users.active = TRUE';
882     }
883
884     if (!$ws_ou) {  # XXX This should be required!!
885         $ws_ou = actor::org_unit->search( { parent_ou => undef } )->next->id;
886     }
887
888     my $descendants = "actor.org_unit_descendants($search_org)";
889
890     my $opt_in_where = '';
891     if (lc($strict_opt_in) eq 'true') {
892         $opt_in_where = "AND (";
893         $opt_in_where .= "EXISTS (select id FROM $opt_in_table ";
894         $opt_in_where .= " WHERE org_unit in (select (actor.org_unit_ancestors($ws_ou)).id)";
895         $opt_in_where .= " AND usr = users.id) ";
896         $opt_in_where .= "OR";
897         $opt_in_where .= " users.home_ou IN (select (actor.org_unit_descendants($ws_ou,$opt_boundary)).id))";
898     }
899
900     my $penalty_join = '';
901     if ($penalty_sort) {
902         $distinct_list = 'COUNT(penalties.id), ' . $distinct_list;
903         $order_by = 'COUNT(penalties.id) DESC, ' . $order_by;
904         unshift @$sort, 'COUNT(penalties.id)';
905         $penalty_join = <<"        SQL";
906             LEFT JOIN actor.usr_standing_penalty penalties
907                 ON (users.id = penalties.usr AND (penalties.stop_date IS NULL OR penalties.stop_date > NOW()))
908         SQL
909     }
910
911     $select = "JOIN ($select) AS search ON (search.id = users.id)" if ($select);
912     $select = <<"    SQL";
913         SELECT  $distinct_list
914           FROM  $u_table AS users $card
915             JOIN $descendants d ON (d.id = users.home_ou)
916             $select
917             $clone_select
918             $penalty_join
919           WHERE users.deleted = FALSE
920             $inactive
921             $opt_in_where
922           GROUP BY $group_list
923           ORDER BY $order_by
924           LIMIT $limit
925           OFFSET $offset
926     SQL
927
928     return actor::user->db_Main->selectcol_arrayref($select, {Columns=>[scalar(@$sort)]}, map {lc($_)} (@usrv,@phonev,@identv,@namev,@profv,@addrv));
929 }
930 __PACKAGE__->register_method(
931     api_name    => 'open-ils.storage.actor.user.crazy_search',
932     api_level   => 1,
933     method      => 'patron_search',
934 );
935
936 sub org_unit_list {
937     my $self = shift;
938     my $client = shift;
939
940     my $select =<<"    SQL";
941     SELECT  *
942       FROM  actor.org_unit
943       ORDER BY CASE WHEN parent_ou IS NULL THEN 0 ELSE 1 END, name;
944     SQL
945
946     my $sth = actor::org_unit->db_Main->prepare_cached($select);
947     $sth->execute;
948
949     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
950
951     return undef;
952 }
953 __PACKAGE__->register_method(
954     api_name    => 'open-ils.storage.direct.actor.org_unit.retrieve.all',
955     api_level   => 1,
956     stream      => 1,
957     method      => 'org_unit_list',
958 );
959
960 sub org_unit_type_list {
961     my $self = shift;
962     my $client = shift;
963
964     my $select =<<"    SQL";
965     SELECT  *
966       FROM  actor.org_unit_type
967       ORDER BY depth, name;
968     SQL
969
970     my $sth = actor::org_unit_type->db_Main->prepare_cached($select);
971     $sth->execute;
972
973     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit_type->construct($_) } $sth->fetchall_hash );
974
975     return undef;
976 }
977 __PACKAGE__->register_method(
978     api_name    => 'open-ils.storage.direct.actor.org_unit_type.retrieve.all',
979     api_level   => 1,
980     stream      => 1,
981     method      => 'org_unit_type_list',
982 );
983
984 sub org_unit_full_path {
985     my $self = shift;
986     my $client = shift;
987     my @binds = @_;
988
989     return undef unless (@binds);
990
991     my $func = 'actor.org_unit_full_path(?)';
992     $func = 'actor.org_unit_full_path(?,?)' if (@binds > 1);
993
994     my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
995     $sth->execute(@binds);
996
997     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
998
999     return undef;
1000 }
1001 __PACKAGE__->register_method(
1002     api_name    => 'open-ils.storage.actor.org_unit.full_path',
1003     api_level   => 1,
1004     stream      => 1,
1005     method      => 'org_unit_full_path',
1006 );
1007
1008 sub org_unit_ancestors {
1009     my $self = shift;
1010     my $client = shift;
1011     my $id = shift;
1012
1013     return undef unless ($id);
1014
1015     my $func = 'actor.org_unit_ancestors(?)';
1016
1017     my $sth = actor::org_unit->db_Main->prepare_cached(<<"    SQL");
1018         SELECT  f.*
1019           FROM  $func f
1020             JOIN actor.org_unit_type t ON (f.ou_type = t.id)
1021           ORDER BY t.depth, f.name;
1022     SQL
1023     $sth->execute(''.$id);
1024
1025     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1026
1027     return undef;
1028 }
1029 __PACKAGE__->register_method(
1030     api_name    => 'open-ils.storage.actor.org_unit.ancestors',
1031     api_level   => 1,
1032     stream      => 1,
1033     method      => 'org_unit_ancestors',
1034 );
1035
1036 sub org_unit_descendants {
1037     my $self = shift;
1038     my $client = shift;
1039     my $id = shift;
1040     my $depth = shift;
1041
1042     return undef unless ($id);
1043
1044     my $func = 'actor.org_unit_descendants(?)';
1045     if (defined $depth) {
1046         $func = 'actor.org_unit_descendants(?,?)';
1047     }
1048
1049     my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
1050     $sth->execute(''.$id, ''.$depth) if (defined $depth);
1051     $sth->execute(''.$id) unless (defined $depth);
1052
1053     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1054
1055     return undef;
1056 }
1057 __PACKAGE__->register_method(
1058     api_name    => 'open-ils.storage.actor.org_unit.descendants',
1059     api_level   => 1,
1060     stream      => 1,
1061     method      => 'org_unit_descendants',
1062 );
1063
1064 sub fleshed_actor_stat_cat {
1065         my $self = shift;
1066         my $client = shift;
1067         my @list = @_;
1068         
1069     @list = ($list[0]) unless ($self->api_name =~ /batch/o);
1070
1071     for my $sc (@list) {
1072         my $cat = actor::stat_cat->retrieve($sc);
1073         next unless ($cat);
1074
1075         my $sc_fm = $cat->to_fieldmapper;
1076         $sc_fm->entries( [ map { $_->to_fieldmapper } $cat->entries ] );
1077         $sc_fm->default_entries( [ map { $_->to_fieldmapper } $cat->default_entries ] );
1078
1079         $client->respond( $sc_fm );
1080
1081     }
1082
1083     return undef;
1084 }
1085 __PACKAGE__->register_method(
1086         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve',
1087         api_level       => 1,
1088     argc        => 1,
1089         method          => 'fleshed_actor_stat_cat',
1090 );
1091
1092 __PACKAGE__->register_method(
1093         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve.batch',
1094         api_level       => 1,
1095     argc        => 1,
1096         stream          => 1,
1097         method          => 'fleshed_actor_stat_cat',
1098 );
1099
1100 #XXX Fix stored proc calls
1101 sub ranged_actor_stat_cat_all {
1102         my $self = shift;
1103         my $client = shift;
1104         my $ou = ''.shift();
1105         
1106         return undef unless ($ou);
1107         my $s_table = actor::stat_cat->table;
1108
1109         my $select = <<"        SQL";
1110                 SELECT  s.*
1111                   FROM  $s_table s
1112                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1113           ORDER BY name
1114         SQL
1115
1116     $fleshed = 0;
1117     $fleshed = 1 if ($self->api_name =~ /fleshed/o);
1118
1119         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1120         $sth->execute($ou);
1121
1122         for my $sc ( map { actor::stat_cat->construct($_) } $sth->fetchall_hash ) {
1123         my $sc_fm = $sc->to_fieldmapper;
1124         $sc_fm->entries(
1125             [ $self->method_lookup( 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat' )->run($ou,$sc->id) ]
1126         ) if ($fleshed);
1127         $sc_fm->default_entries(
1128             [ $self->method_lookup( 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve' )->run($ou,$sc->id) ]
1129         ) if ($fleshed);
1130         $client->respond( $sc_fm );
1131     }
1132
1133         return undef;
1134 }
1135 __PACKAGE__->register_method(
1136         api_name        => 'open-ils.storage.ranged.fleshed.actor.stat_cat.all',
1137         api_level       => 1,
1138     argc        => 1,
1139         stream          => 1,
1140         method          => 'ranged_actor_stat_cat_all',
1141 );
1142
1143 __PACKAGE__->register_method(
1144         api_name        => 'open-ils.storage.ranged.actor.stat_cat.all',
1145         api_level       => 1,
1146     argc        => 1,
1147         stream          => 1,
1148         method          => 'ranged_actor_stat_cat_all',
1149 );
1150
1151 #XXX Fix stored proc calls
1152 sub ranged_actor_stat_cat_entry {
1153         my $self = shift;
1154         my $client = shift;
1155         my $ou = ''.shift();
1156         my $sc = ''.shift();
1157         
1158         return undef unless ($ou);
1159         my $s_table = actor::stat_cat_entry->table;
1160
1161         my $select = <<"        SQL";
1162                 SELECT  s.*
1163                   FROM  $s_table s
1164                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1165           WHERE stat_cat = ?
1166           ORDER BY name
1167         SQL
1168
1169         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1170         $sth->execute($ou,$sc);
1171
1172         for my $sce ( map { actor::stat_cat_entry->construct($_) } $sth->fetchall_hash ) {
1173         my $sce_fm = $sce->to_fieldmapper;
1174         $client->respond( $sce_fm );
1175     }
1176
1177         return undef;
1178 }
1179 __PACKAGE__->register_method(
1180         api_name        => 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat',
1181         api_level       => 1,
1182         stream          => 1,
1183         method          => 'ranged_actor_stat_cat_entry',
1184 );
1185
1186 sub actor_stat_cat_entry_default {
1187     my $self = shift;
1188     my $client = shift;
1189     my $ou = ''.shift();
1190     my $sc = ''.shift();
1191         
1192     return undef unless ($ou);
1193     my $s_table = actor::stat_cat_entry_default->table;
1194
1195     my $select = <<"    SQL";
1196          SELECT  s.*
1197          FROM  $s_table s
1198          WHERE owner = ? AND stat_cat = ?
1199     SQL
1200
1201     my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1202     $sth->execute($ou,$sc);
1203
1204     for my $sced ( map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash ) {
1205         $client->respond( $sced->to_fieldmapper );
1206     }
1207
1208     return undef;
1209 }
1210 __PACKAGE__->register_method(
1211     api_name        => 'open-ils.storage.actor.stat_cat_entry_default.retrieve',
1212     api_level       => 1,
1213     stream          => 1,
1214     method          => 'actor_stat_cat_entry_default',
1215 );
1216
1217 sub actor_stat_cat_entry_default_ancestor {
1218     my $self = shift;
1219     my $client = shift;
1220     my $ou = ''.shift();
1221     my $sc = ''.shift();
1222         
1223     return undef unless ($ou);
1224     my $s_table = actor::stat_cat_entry_default->table;
1225
1226     my $select = <<"    SQL";
1227         SELECT  s.*
1228         FROM  $s_table s
1229         JOIN actor.org_unit_ancestors(?) p ON (p.id = s.owner)
1230         WHERE stat_cat = ?
1231     SQL
1232
1233     my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1234     $sth->execute($ou,$sc);
1235
1236     my @sced =  map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash;
1237
1238     my $ancestor_sced = pop @sced;
1239
1240     $client->respond( $ancestor_sced->to_fieldmapper ) if $ancestor_sced;
1241
1242     return undef;
1243 }
1244 __PACKAGE__->register_method(
1245     api_name        => 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve',
1246     api_level       => 1,
1247     stream          => 1,
1248     method          => 'actor_stat_cat_entry_default_ancestor',
1249 );
1250
1251 1;