]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/actor.pm
134821a1105ec149528c1e3ffe280940565842ea
[working/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 OpenSRF::Utils 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(cleanse_ISO8601($c->{close_start})),
267                 end   => $_dt_parser->parse_datetime(cleanse_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 = cleanse_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( cleanse_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( cleanse_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( cleanse_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( cleanse_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 sub org_closed_overlap {
369     my $self = shift;
370     my $client = shift;
371     my $ou = shift;
372     my $date = shift;
373     my $direction = shift || 0;
374     my $no_hoo = shift || 0;
375
376     return undef unless ($date && $ou);
377
378     my $t = actor::org_unit::closed_date->table;
379     my $sql = <<"    SQL";
380         SELECT  *
381           FROM  $t
382           WHERE ? between close_start and close_end
383             AND org_unit = ?
384           ORDER BY close_start ASC, close_end DESC
385           LIMIT 1
386     SQL
387
388     $date = cleanse_ISO8601($date);
389     my ($begin, $end) = ($date,$date);
390
391     my $hoo = actor::org_unit::hours_of_operation->retrieve($ou);
392
393     if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $date, $ou )) {
394         $begin = cleanse_ISO8601($closure->{close_start});
395         $end = cleanse_ISO8601($closure->{close_end});
396
397         if ( $direction <= 0 ) {
398             $before = $_dt_parser->parse_datetime( $begin );
399             $before->subtract( minutes => 1 );
400
401             while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1, 1 ) ) {
402                 $before = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
403             }
404             $begin = cleanse_ISO8601($before->strftime('%FT%T%z'));
405         }
406
407         if ( $direction >= 0 ) {
408             $after = $_dt_parser->parse_datetime( $end );
409             $after->add( minutes => 1 );
410
411             while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1, 1 ) ) {
412                 $after = $_dt_parser->parse_datetime( cleanse_ISO8601($_a->{end}) );
413             }
414             $end = cleanse_ISO8601($after->strftime('%FT%T%z'));
415         }
416     }
417
418     if ( !$no_hoo ) {
419         if ( $hoo ) {
420
421             if ( $direction <= 0 ) {
422                 my $begin_dow = $_dt_parser->parse_datetime( $begin )->day_of_week_0;
423                 my $begin_open_meth = "dow_".$begin_dow."_open";
424                 my $begin_close_meth = "dow_".$begin_dow."_close";
425
426                 my $count = 1;
427                 while ($hoo->$begin_open_meth eq '00:00:00' and $hoo->$begin_close_meth eq '00:00:00') {
428                     $begin = cleanse_ISO8601($_dt_parser->parse_datetime( $begin )->subtract( days => 1)->strftime('%FT%T%z'));
429                     $begin_dow++;
430                     $begin_dow %= 7;
431                     $count++;
432                     last if ($count > 6);
433                     $begin_open_meth = "dow_".$begin_dow."_open";
434                     $begin_close_meth = "dow_".$begin_dow."_close";
435                 }
436
437                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $begin, $ou )) {
438                     $before = $_dt_parser->parse_datetime( $begin );
439                     $before->subtract( minutes => 1 );
440                     while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1 ) ) {
441                         $before = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
442                     }
443                 }
444             }
445     
446             if ( $direction >= 0 ) {
447                 my $end_dow = $_dt_parser->parse_datetime( $end )->day_of_week_0;
448                 my $end_open_meth = "dow_".$end_dow."_open";
449                 my $end_close_meth = "dow_".$end_dow."_close";
450     
451                 $count = 1;
452                 while ($hoo->$end_open_meth eq '00:00:00' and $hoo->$end_close_meth eq '00:00:00') {
453                     $end = cleanse_ISO8601($_dt_parser->parse_datetime( $end )->add( days => 1)->strftime('%FT%T%z'));
454                     $end_dow++;
455                     $end_dow %= 7;
456                     $count++;
457                     last if ($count > 6);
458                     $end_open_meth = "dow_".$end_dow."_open";
459                     $end_close_meth = "dow_".$end_dow."_close";
460                 }
461
462                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $end, $ou )) {
463                     $after = $_dt_parser->parse_datetime( $end );
464                     $after->add( minutes => 1 );
465
466                     while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1 ) ) {
467                         $after = $_dt_parser->parse_datetime( cleanse_ISO8601($_a->{end}) );
468                     }
469                     $end = cleanse_ISO8601($after->strftime('%FT%T%z'));
470                 }
471             }
472
473         }
474     }
475
476     if ($begin eq $date && $end eq $date) {
477         return undef;
478     }
479
480     return { start => $begin, end => $end };
481 }
482 __PACKAGE__->register_method(
483     api_name    => 'open-ils.storage.actor.org_unit.closed_date.overlap',
484     api_level   => 1,
485     method      => 'org_closed_overlap',
486 );
487
488 sub user_by_barcode {
489     my $self = shift;
490     my $client = shift;
491     my @barcodes = shift;
492
493     return undef unless @barcodes;
494
495     for my $card ( actor::card->search( { barcode => @barcodes } ) ) {
496         next unless $card;
497         if (@barcodes == 1) {
498             return $card->usr->to_fieldmapper;
499         }
500         $client->respond( $card->usr->to_fieldmapper);
501     }
502     return undef;
503 }
504 __PACKAGE__->register_method(
505     api_name    => 'open-ils.storage.direct.actor.user.search.barcode',
506     api_level   => 1,
507     method      => 'user_by_barcode',
508     stream      => 1,
509     cachable    => 1,
510 );
511
512 sub lost_barcodes {
513     my $self = shift;
514     my $client = shift;
515
516     my $c = actor::card->table;
517     my $p = actor::user->table;
518
519     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.card <> c.id";
520
521     my $list = actor::user->db_Main->selectcol_arrayref($sql);
522     for my $bc ( @$list ) {
523         $client->respond($bc);
524     }
525     return undef;
526 }
527 __PACKAGE__->register_method(
528     api_name    => 'open-ils.storage.actor.user.lost_barcodes',
529     api_level   => 1,
530     stream      => 1,
531     method      => 'lost_barcodes',
532     signature    => <<'    NOTE',
533         Returns an array of barcodes that belong to lost cards.
534         @return array of barcodes
535     NOTE
536 );
537
538 sub expired_barcodes {
539     my $self = shift;
540     my $client = shift;
541
542     my $c = actor::card->table;
543     my $p = actor::user->table;
544
545     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.expire_date < CURRENT_DATE";
546
547     my $list = actor::user->db_Main->selectcol_arrayref($sql);
548     for my $bc ( @$list ) {
549         $client->respond($bc);
550     }
551     return undef;
552 }
553 __PACKAGE__->register_method(
554     api_name    => 'open-ils.storage.actor.user.expired_barcodes',
555     api_level   => 1,
556     stream      => 1,
557     method      => 'expired_barcodes',
558     signature    => <<'    NOTE',
559         Returns an array of barcodes that are currently expired.
560         @return array of barcodes
561     NOTE
562 );
563
564 sub barred_barcodes {
565     my $self = shift;
566     my $client = shift;
567
568     my $c = actor::card->table;
569     my $p = actor::user->table;
570
571     my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.barred IS TRUE";
572
573     my $list = actor::user->db_Main->selectcol_arrayref($sql);
574     for my $bc ( @$list ) {
575         $client->respond($bc);
576     }
577     return undef;
578 }
579 __PACKAGE__->register_method(
580     api_name    => 'open-ils.storage.actor.user.barred_barcodes',
581     api_level   => 1,
582     stream      => 1,
583     method      => 'barred_barcodes',
584     signature    => <<'    NOTE',
585         Returns an array of barcodes that are currently barred.
586         @return array of barcodes
587     NOTE
588 );
589
590 sub penalized_barcodes {
591     my $self = shift;
592     my $client = shift;
593
594     my $c = actor::card->table;
595     my $p = actor::user_standing_penalty->table;
596
597     my $sql = <<"    SQL";
598         SELECT  DISTINCT c.barcode
599           FROM  $c c
600             JOIN $p p USING (usr)
601             JOIN config.standing_penalty csp ON (csp.id = p.standing_penalty)
602           WHERE csp.block_list IS NOT NULL
603             AND p.set_date < CURRENT_DATE
604             AND (p.stop_date IS NULL OR p.stop_date > CURRENT_DATE);
605     SQL
606
607     my $list = actor::user->db_Main->selectcol_arrayref($sql);
608     for my $bc ( @$list ) {
609         $client->respond($bc);
610     }
611     return undef;
612 }
613 __PACKAGE__->register_method(
614     api_name    => 'open-ils.storage.actor.user.penalized_barcodes',
615     api_level   => 1,
616     stream      => 1,
617     method      => 'penalized_barcodes',
618     signature    => <<'    NOTE',
619         Returns an array of barcodes that have blocking penalties.
620         @return array of barcodes
621     NOTE
622 );
623
624 sub _prepare_name_argument {
625     # Get rid of extra spaces, accents, and regex characters
626     my ($search) = _clean_regex_chars(@_);
627     my $sth = actor::user->db_Main->prepare_cached("SELECT evergreen.unaccent_and_squash(?)");
628     $sth->execute($search);
629     my $r = $sth->fetch;
630     return ($r && @$r) ? $r->[0] : $search;
631 };
632
633 sub _clean_regex_chars {
634     my ($search) = @_;
635
636     # Escape metacharacters for SIMILAR TO 
637     # (http://www.postgresql.org/docs/8.4/interactive/functions-matching.html)
638     $search =~ s/\_/\\_/g;
639     $search =~ s/\%/\\%/g;
640     $search =~ s/\|/\\|/g;
641     $search =~ s/\*/\\*/g;
642     $search =~ s/\+/\\+/g;
643     $search =~ s/\[/\\[/g;
644     $search =~ s/\]/\\]/g;
645     $search =~ s/\(/\\(/g;
646     $search =~ s/\)/\\)/g;
647
648     return $search;
649 }
650
651 sub patron_search {
652     my $self = shift;
653     my $client = shift;
654     my $search = shift;
655     my $limit = shift || 1000;
656     my $sort = shift;
657     my $inactive = shift;
658     my $ws_ou = shift;
659     my $search_org = shift || $ws_ou;
660     my $opt_boundary = shift || 0;
661     my $offset = shift || 0;
662
663     my $penalty_sort = 0;
664
665     my $strict_opt_in = OpenSRF::Utils::SettingsClient->new->config_value( share => user => 'opt_in' );
666
667     $sort = ['family_name','first_given_name'] unless ($$sort[0]);
668     push @$sort,'id';
669
670     if ($$sort[0] eq 'penalties') {
671         shift @$sort;
672         $penalty_sort = 1;
673     }
674
675     # group 0 = user
676     # group 1 = address
677     # group 2 = phone, ident
678     # group 3 = barcode
679     # group 4 = dob
680     # group 5 = profile
681
682     # Treatment of name fields depends on whether the org has 
683     # diacritic_insensitivity turned on or off.
684
685     my $diacritic_insensitive =  $U->ou_ancestor_setting_value($ws_ou, 'circ.patron_search.diacritic_insensitive');
686     # Parse from JSON to Perl boolean (1|0):
687     $diacritic_insensitive = ($diacritic_insensitive) ? $JSON->JSON2perl($diacritic_insensitive) : 0;
688     my $usr;
689     my @usrv;
690     my $dob;
691     my @dobv;
692
693     if ($diacritic_insensitive) {
694        $usr = join ' AND ', map { "evergreen.unaccent_and_squash(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
695        @usrv = map { "^" . _prepare_name_argument($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
696
697     } else {
698        $usr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
699        @usrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
700     }
701
702     while (($key, $value) = each (%$search)) {
703         if($$search{$key}{group} eq '4') {
704             my $tval = $key;
705             $tval =~ s/dob_//g;
706             my $right = "RIGHT('0'|| ";
707             my $end = ", 2)";
708             $end = $right = '' if lc $tval eq 'year';
709             $dob .= $right."CAST(DATE_PART('$tval', dob) AS text)$end ~ ? AND ";
710         }
711     }
712     # Trim the last " AND "
713     $dob = substr($dob,0,-4);
714     @dobv = map { _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '4' } keys %$search;
715     $usr .= ' AND ' if ( $usr && $dob );
716     $usr .= $dob if $dob; # $dob not in-line above in case $usr doesn't have any search vals (only searched for dob)
717     push(@usrv, @dobv) if @dobv;
718
719     my $addr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
720     my @addrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
721
722     # should only be 1 profile sent but this construction makes dealing with the lists simpler.
723     my ($prof) = map { $$search{$_}{value} } grep {''.$$search{$_}{group} eq '5' } keys %$search;
724     $prof = int($prof) if $prof; # int or out
725
726     my $pv = _clean_regex_chars($$search{phone}{value});
727     my $iv = _clean_regex_chars($$search{ident}{value});
728     my $nv = _clean_regex_chars($$search{name}{value});
729     my $cv = _clean_regex_chars($$search{card}{value});
730
731     my $card = '';
732     if ($cv) {
733         $card = 'JOIN (SELECT DISTINCT usr FROM actor.card WHERE evergreen.lowercase(barcode) LIKE ?||\'%\') AS card ON (card.usr = users.id)';
734         unshift(@usrv, $cv);
735     }
736
737     my $phone = '';
738     my @ps;
739     my @phonev;
740     if ($pv) {
741         for my $p ( qw/day_phone evening_phone other_phone/ ) {
742             if ($pv =~ /^\d+$/) {
743                 push @ps, "evergreen.lowercase(REGEXP_REPLACE($p, '[^0-9]', '', 'g')) ~ ?";
744             } else {
745                 push @ps, "evergreen.lowercase($p) ~ ?";
746             }
747             push @phonev, "^$pv";
748         }
749         $phone = '(' . join(' OR ', @ps) . ')';
750     }
751
752     my $ident = '';
753     my @is;
754     my @identv;
755     if ($iv) {
756         for my $i ( qw/ident_value ident_value2/ ) {
757             push @is, "evergreen.lowercase($i) ~ ?";
758             push @identv, "^$iv";
759         }
760         $ident = '(' . join(' OR ', @is) . ')';
761     }
762
763     my $name = '';
764     my @ns;
765     my @namev;
766     if (0 && $nv) {
767         for my $n ( qw/first_given_name second_given_name family_name/ ) {
768             if ($diacritic_insensitive) {
769                 push @ns, "evergreen.unaccent_and_squash($n) ~ ?";
770             } else {
771                 push @ns, "evergreen.lowercase($n) ~ ?";
772             }
773             push @namev, "^$nv";
774         }
775         $name = '(' . join(' OR ', @ns) . ')';
776     }
777
778     my $usr_where = join ' AND ', grep { $_ } ($usr,$phone,$ident,$name);
779     my $addr_where = $addr;
780
781
782     my $u_table = actor::user->table;
783     my $a_table = actor::user_address->table;
784     my $opt_in_table = actor::usr_org_unit_opt_in->table;
785     my $ou_table = actor::org_unit->table;
786
787     my $u_select = "SELECT id as id FROM $u_table u WHERE $usr_where";
788     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";
789
790     my $clone_select = '';
791
792     #$clone_select = "JOIN (SELECT cu.id as id FROM $a_table ca ".
793     #          "JOIN $u_table cu ON (cu.mailing_address = ca.id OR cu.billing_address = ca.id) ".
794     #          "WHERE $addr_where) AS clone ON (clone.id = users.id)" if ($addr_where);
795
796     my $select = '';
797     if ($usr_where) {
798         if ($addr_where) {
799             $select = "$u_select INTERSECT $a_select";
800         } else {
801             $select = $u_select;
802         }
803     } elsif ($addr_where) {
804         $select = "$a_select";
805     }
806
807     return undef if (!$select && !$card);
808
809     my $order_by = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text)) ' . (split / /,$_)[1] } @$sort;
810     my $distinct_list = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text))' } @$sort;
811     my $group_list = $distinct_list;
812
813     if ($inactive) {
814         $inactive = '';
815     } else {
816         $inactive = 'AND users.active = TRUE';
817     }
818
819     if (!$ws_ou) {  # XXX This should be required!!
820         $ws_ou = actor::org_unit->search( { parent_ou => undef } )->next->id;
821     }
822
823     my $descendants = "actor.org_unit_descendants($search_org)";
824     my $profile = "JOIN permission.grp_descendants($prof) p ON (p.id = users.profile)" if $prof;
825
826     my $opt_in_where = '';
827     if (lc($strict_opt_in) eq 'true') {
828         $opt_in_where = "AND (";
829         $opt_in_where .= "EXISTS (select id FROM $opt_in_table ";
830         $opt_in_where .= " WHERE org_unit in (select (actor.org_unit_ancestors($ws_ou)).id)";
831         $opt_in_where .= " AND usr = users.id) ";
832         $opt_in_where .= "OR";
833         $opt_in_where .= " users.home_ou IN (select (actor.org_unit_descendants($ws_ou,$opt_boundary)).id))";
834     }
835
836     my $penalty_join = '';
837     if ($penalty_sort) {
838         $distinct_list = 'COUNT(penalties.id), ' . $distinct_list;
839         $order_by = 'COUNT(penalties.id) DESC, ' . $order_by;
840         unshift @$sort, 'COUNT(penalties.id)';
841         $penalty_join = <<"        SQL";
842             LEFT JOIN actor.usr_standing_penalty penalties
843                 ON (users.id = penalties.usr AND (penalties.stop_date IS NULL OR penalties.stop_date > NOW()))
844         SQL
845     }
846
847     $select = "JOIN ($select) AS search ON (search.id = users.id)" if ($select);
848     $select = <<"    SQL";
849         SELECT  $distinct_list
850           FROM  $u_table AS users $card
851             JOIN $descendants d ON (d.id = users.home_ou)
852             $profile
853             $select
854             $clone_select
855             $penalty_join
856           WHERE users.deleted = FALSE
857             $inactive
858             $opt_in_where
859           GROUP BY $group_list
860           ORDER BY $order_by
861           LIMIT $limit
862           OFFSET $offset
863     SQL
864
865     return actor::user->db_Main->selectcol_arrayref($select, {Columns=>[scalar(@$sort)]}, map {lc($_)} (@usrv,@phonev,@identv,@namev,@addrv));
866 }
867 __PACKAGE__->register_method(
868     api_name    => 'open-ils.storage.actor.user.crazy_search',
869     api_level   => 1,
870     method      => 'patron_search',
871 );
872
873 sub org_unit_list {
874     my $self = shift;
875     my $client = shift;
876
877     my $select =<<"    SQL";
878     SELECT  *
879       FROM  actor.org_unit
880       ORDER BY CASE WHEN parent_ou IS NULL THEN 0 ELSE 1 END, name;
881     SQL
882
883     my $sth = actor::org_unit->db_Main->prepare_cached($select);
884     $sth->execute;
885
886     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
887
888     return undef;
889 }
890 __PACKAGE__->register_method(
891     api_name    => 'open-ils.storage.direct.actor.org_unit.retrieve.all',
892     api_level   => 1,
893     stream      => 1,
894     method      => 'org_unit_list',
895 );
896
897 sub org_unit_type_list {
898     my $self = shift;
899     my $client = shift;
900
901     my $select =<<"    SQL";
902     SELECT  *
903       FROM  actor.org_unit_type
904       ORDER BY depth, name;
905     SQL
906
907     my $sth = actor::org_unit_type->db_Main->prepare_cached($select);
908     $sth->execute;
909
910     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit_type->construct($_) } $sth->fetchall_hash );
911
912     return undef;
913 }
914 __PACKAGE__->register_method(
915     api_name    => 'open-ils.storage.direct.actor.org_unit_type.retrieve.all',
916     api_level   => 1,
917     stream      => 1,
918     method      => 'org_unit_type_list',
919 );
920
921 sub org_unit_full_path {
922     my $self = shift;
923     my $client = shift;
924     my @binds = @_;
925
926     return undef unless (@binds);
927
928     my $func = 'actor.org_unit_full_path(?)';
929     $func = 'actor.org_unit_full_path(?,?)' if (@binds > 1);
930
931     my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
932     $sth->execute(@binds);
933
934     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
935
936     return undef;
937 }
938 __PACKAGE__->register_method(
939     api_name    => 'open-ils.storage.actor.org_unit.full_path',
940     api_level   => 1,
941     stream      => 1,
942     method      => 'org_unit_full_path',
943 );
944
945 sub org_unit_ancestors {
946     my $self = shift;
947     my $client = shift;
948     my $id = shift;
949
950     return undef unless ($id);
951
952     my $func = 'actor.org_unit_ancestors(?)';
953
954     my $sth = actor::org_unit->db_Main->prepare_cached(<<"    SQL");
955         SELECT  f.*
956           FROM  $func f
957             JOIN actor.org_unit_type t ON (f.ou_type = t.id)
958           ORDER BY t.depth, f.name;
959     SQL
960     $sth->execute(''.$id);
961
962     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
963
964     return undef;
965 }
966 __PACKAGE__->register_method(
967     api_name    => 'open-ils.storage.actor.org_unit.ancestors',
968     api_level   => 1,
969     stream      => 1,
970     method      => 'org_unit_ancestors',
971 );
972
973 sub org_unit_descendants {
974     my $self = shift;
975     my $client = shift;
976     my $id = shift;
977     my $depth = shift;
978
979     return undef unless ($id);
980
981     my $func = 'actor.org_unit_descendants(?)';
982     if (defined $depth) {
983         $func = 'actor.org_unit_descendants(?,?)';
984     }
985
986     my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
987     $sth->execute(''.$id, ''.$depth) if (defined $depth);
988     $sth->execute(''.$id) unless (defined $depth);
989
990     $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
991
992     return undef;
993 }
994 __PACKAGE__->register_method(
995     api_name    => 'open-ils.storage.actor.org_unit.descendants',
996     api_level   => 1,
997     stream      => 1,
998     method      => 'org_unit_descendants',
999 );
1000
1001 sub fleshed_actor_stat_cat {
1002         my $self = shift;
1003         my $client = shift;
1004         my @list = @_;
1005         
1006     @list = ($list[0]) unless ($self->api_name =~ /batch/o);
1007
1008     for my $sc (@list) {
1009         my $cat = actor::stat_cat->retrieve($sc);
1010         next unless ($cat);
1011
1012         my $sc_fm = $cat->to_fieldmapper;
1013         $sc_fm->entries( [ map { $_->to_fieldmapper } $cat->entries ] );
1014         $sc_fm->default_entries( [ map { $_->to_fieldmapper } $cat->default_entries ] );
1015
1016         $client->respond( $sc_fm );
1017
1018     }
1019
1020     return undef;
1021 }
1022 __PACKAGE__->register_method(
1023         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve',
1024         api_level       => 1,
1025     argc        => 1,
1026         method          => 'fleshed_actor_stat_cat',
1027 );
1028
1029 __PACKAGE__->register_method(
1030         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve.batch',
1031         api_level       => 1,
1032     argc        => 1,
1033         stream          => 1,
1034         method          => 'fleshed_actor_stat_cat',
1035 );
1036
1037 #XXX Fix stored proc calls
1038 sub ranged_actor_stat_cat_all {
1039         my $self = shift;
1040         my $client = shift;
1041         my $ou = ''.shift();
1042         
1043         return undef unless ($ou);
1044         my $s_table = actor::stat_cat->table;
1045
1046         my $select = <<"        SQL";
1047                 SELECT  s.*
1048                   FROM  $s_table s
1049                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1050           ORDER BY name
1051         SQL
1052
1053     $fleshed = 0;
1054     $fleshed = 1 if ($self->api_name =~ /fleshed/o);
1055
1056         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1057         $sth->execute($ou);
1058
1059         for my $sc ( map { actor::stat_cat->construct($_) } $sth->fetchall_hash ) {
1060         my $sc_fm = $sc->to_fieldmapper;
1061         $sc_fm->entries(
1062             [ $self->method_lookup( 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat' )->run($ou,$sc->id) ]
1063         ) if ($fleshed);
1064         $sc_fm->default_entries(
1065             [ $self->method_lookup( 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve' )->run($ou,$sc->id) ]
1066         ) if ($fleshed);
1067         $client->respond( $sc_fm );
1068     }
1069
1070         return undef;
1071 }
1072 __PACKAGE__->register_method(
1073         api_name        => 'open-ils.storage.ranged.fleshed.actor.stat_cat.all',
1074         api_level       => 1,
1075     argc        => 1,
1076         stream          => 1,
1077         method          => 'ranged_actor_stat_cat_all',
1078 );
1079
1080 __PACKAGE__->register_method(
1081         api_name        => 'open-ils.storage.ranged.actor.stat_cat.all',
1082         api_level       => 1,
1083     argc        => 1,
1084         stream          => 1,
1085         method          => 'ranged_actor_stat_cat_all',
1086 );
1087
1088 #XXX Fix stored proc calls
1089 sub ranged_actor_stat_cat_entry {
1090         my $self = shift;
1091         my $client = shift;
1092         my $ou = ''.shift();
1093         my $sc = ''.shift();
1094         
1095         return undef unless ($ou);
1096         my $s_table = actor::stat_cat_entry->table;
1097
1098         my $select = <<"        SQL";
1099                 SELECT  s.*
1100                   FROM  $s_table s
1101                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1102           WHERE stat_cat = ?
1103           ORDER BY name
1104         SQL
1105
1106         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1107         $sth->execute($ou,$sc);
1108
1109         for my $sce ( map { actor::stat_cat_entry->construct($_) } $sth->fetchall_hash ) {
1110         my $sce_fm = $sce->to_fieldmapper;
1111         $client->respond( $sce_fm );
1112     }
1113
1114         return undef;
1115 }
1116 __PACKAGE__->register_method(
1117         api_name        => 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat',
1118         api_level       => 1,
1119         stream          => 1,
1120         method          => 'ranged_actor_stat_cat_entry',
1121 );
1122
1123 sub actor_stat_cat_entry_default {
1124     my $self = shift;
1125     my $client = shift;
1126     my $ou = ''.shift();
1127     my $sc = ''.shift();
1128         
1129     return undef unless ($ou);
1130     my $s_table = actor::stat_cat_entry_default->table;
1131
1132     my $select = <<"    SQL";
1133          SELECT  s.*
1134          FROM  $s_table s
1135          WHERE owner = ? AND stat_cat = ?
1136     SQL
1137
1138     my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1139     $sth->execute($ou,$sc);
1140
1141     for my $sced ( map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash ) {
1142         $client->respond( $sced->to_fieldmapper );
1143     }
1144
1145     return undef;
1146 }
1147 __PACKAGE__->register_method(
1148     api_name        => 'open-ils.storage.actor.stat_cat_entry_default.retrieve',
1149     api_level       => 1,
1150     stream          => 1,
1151     method          => 'actor_stat_cat_entry_default',
1152 );
1153
1154 sub actor_stat_cat_entry_default_ancestor {
1155     my $self = shift;
1156     my $client = shift;
1157     my $ou = ''.shift();
1158     my $sc = ''.shift();
1159         
1160     return undef unless ($ou);
1161     my $s_table = actor::stat_cat_entry_default->table;
1162
1163     my $select = <<"    SQL";
1164         SELECT  s.*
1165         FROM  $s_table s
1166         JOIN actor.org_unit_ancestors(?) p ON (p.id = s.owner)
1167         WHERE stat_cat = ?
1168     SQL
1169
1170     my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1171     $sth->execute($ou,$sc);
1172
1173     my @sced =  map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash;
1174
1175     my $ancestor_sced = pop @sced;
1176
1177     $client->respond( $ancestor_sced->to_fieldmapper ) if $ancestor_sced;
1178
1179     return undef;
1180 }
1181 __PACKAGE__->register_method(
1182     api_name        => 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve',
1183     api_level       => 1,
1184     stream          => 1,
1185     method          => 'actor_stat_cat_entry_default_ancestor',
1186 );
1187
1188 1;