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