]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/Publisher/actor.pm
Wrap proximity refreshing in a transaction to avoid timespans where there is no such...
[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
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         $self->method_lookup('open-ils.storage.transaction.begin')->run;
201         actor::org_unit_proximity->db_Main->do($delete_sql);
202         actor::org_unit_proximity->db_Main->do($insert_sql);
203         $self->method_lookup('open-ils.storage.transaction.commit')->run;
204
205         return 1;
206 }
207 __PACKAGE__->register_method(
208         api_name        => 'open-ils.storage.actor.org_unit.refresh_proximity',
209         api_level       => 1,
210         method          => 'calc_proximity',
211 );
212
213 sub make_hoo_spanset {
214     my $hoo = shift;
215     return undef unless $hoo;
216
217     my $today = shift || DateTime->now;
218
219     my $tz = OpenSRF::AppSession->create('open-ils.actor')->request(
220         'open-ils.actor.ou_setting.ancestor_default' => $hoo->id.'' => 'org_unit.timezone'
221     )->gather(1) || DateTime::TimeZone->new( name => 'local' )->name;
222
223     my $current_dow = $today->day_of_week_0;
224
225     my $spanset = DateTime::SpanSet->empty_set;
226     for my $d ( 0 .. 6 ) {
227
228         my $omethod = 'dow_'.$d.'_open';
229         my $cmethod = 'dow_'.$d.'_close';
230
231         my $open = interval_to_seconds($hoo->$omethod());
232         my $close = interval_to_seconds($hoo->$cmethod());
233
234         next if ($open == $close && $open == 0);
235
236         my $dow_offset = ($d - $current_dow) * $one_day;
237         $close += $one_day if ($close <= $open);
238
239         $spanset = $spanset->union(
240             DateTime::Span->new(
241                 start => $today->clone->add( seconds => $dow_offset + $open  ),
242                 end   => $today->clone->add( seconds => $dow_offset + $close )
243             )
244         );
245     }
246
247     return $spanset->complement;
248 }
249
250 sub make_closure_spanset {
251     my $closures = shift;
252     return undef unless $closures;
253
254     my $spanset = DateTime::SpanSet->empty_set;
255     for my $k ( keys %$closures ) {
256         my $c = $$closures{$k};
257
258         $spanset = $spanset->union(
259             DateTime::Span->new(
260                 start => $_dt_parser->parse_datetime(cleanse_ISO8601($c->{close_start})),
261                 end   => $_dt_parser->parse_datetime(cleanse_ISO8601($c->{close_end}))
262             )
263         );
264     }
265
266     return $spanset;
267 }
268
269 sub new_org_closed_overlap {
270         my $self = shift;
271         my $client = shift;
272         my $ou = shift;
273         my $date = shift;
274         my $direction = shift || 0;
275         my $no_hoo = shift || 0;
276
277         return undef unless ($date && $ou);
278
279     # we're given a date and a direction, find any closures that contain the date
280         my $t = actor::org_unit::closed_date->table;
281         my $sql = <<"   SQL";
282                 SELECT  *
283                   FROM  $t
284                   WHERE close_end > ?
285                         AND org_unit = ?
286                   ORDER BY close_start ASC, close_end DESC
287                   LIMIT 1
288         SQL
289
290         $date = cleanse_ISO8601($date);
291
292     my $target_date = $_dt_parser->parse_datetime( $date );
293         my ($begin, $end) = ($target_date, $target_date);
294
295     # create a spanset from the closures that contain the $date
296         my $closure_spanset = make_closure_spanset(
297         actor::org_unit::closed_date->db_Main->selectall_hashref( $sql, 'id', {}, $date, $ou )
298     );
299
300     if ($closure_spanset && $closure_spanset->intersects( $target_date )) {
301         my $closure_intersection = $closure_spanset->intersection( $target_date );
302         $begin = $closure_intersection->min;
303         $end = $closure_intersection->max;
304
305                 if ( $direction <= 0 ) {
306                         $begin->subtract( minutes => 1 );
307
308                         while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1, 1 ) ) {
309                                 $begin = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
310                         }
311                 }
312
313                 if ( $direction >= 0 ) {
314                         $end->add( minutes => 1 );
315
316                         while ( my $_a = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), 1, 1 ) ) {
317                                 $end = $_dt_parser->parse_datetime( cleanse_ISO8601($_a->{end}) );
318                         }
319                 }
320     }
321
322         if ( !$no_hoo ) {
323
324             my $begin_hoo = make_hoo_spanset(actor::org_unit::hours_of_operation->retrieve($ou), $begin);
325             my $end_hoo   = make_hoo_spanset(actor::org_unit::hours_of_operation->retrieve($ou), $end  );
326
327
328         if ( $begin_hoo && $direction <= 0 && $begin_hoo->intersects($begin) ) {
329             my $hoo_intersection = $begin_hoo->intersection( $begin );
330             $begin = $hoo_intersection->min;
331             $begin->subtract( minutes => 1 );
332
333             while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1 ) ) {
334                 $begin = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
335             }
336         }
337         
338         if ( $end_hoo && $direction >= 0 && $end_hoo->intersects($end) ) {
339             my $hoo_intersection = $end_hoo->intersection( $end );
340             $end = $hoo_intersection->max;
341                         $end->add( minutes => 1 );
342
343
344             while ( my $_b = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), -1 ) ) {
345                 $end = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{end}) );
346             }
347         }
348     }
349
350     my $start = $begin->strftime('%FT%T%z');
351     my $stop = $end->strftime('%FT%T%z');
352
353     return undef if ($start eq $stop);
354     return { start => $start, end => $stop };
355 }
356 __PACKAGE__->register_method(
357         api_name        => 'open-ils.storage.actor.org_unit.closed_date.overlap',
358         api_level       => 0,
359         method          => 'new_org_closed_overlap',
360 );
361
362 sub org_closed_overlap {
363     my $self = shift;
364     my $client = shift;
365     my $ou = shift;
366     my $date = shift;
367     my $direction = shift || 0;
368     my $no_hoo = shift || 0;
369
370     return undef unless ($date && $ou);
371
372     my $t = actor::org_unit::closed_date->table;
373     my $sql = <<"    SQL";
374         SELECT  *
375           FROM  $t
376           WHERE ? between close_start and close_end
377             AND org_unit = ?
378           ORDER BY close_start ASC, close_end DESC
379           LIMIT 1
380     SQL
381
382     $date = cleanse_ISO8601($date);
383     my ($begin, $end) = ($date,$date);
384
385     my $hoo = actor::org_unit::hours_of_operation->retrieve($ou);
386
387     if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $date, $ou )) {
388         $begin = cleanse_ISO8601($closure->{close_start});
389         $end = cleanse_ISO8601($closure->{close_end});
390
391         if ( $direction <= 0 ) {
392             $before = $_dt_parser->parse_datetime( $begin );
393             $before->subtract( minutes => 1 );
394
395             while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1, 1 ) ) {
396                 $before = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
397             }
398             $begin = cleanse_ISO8601($before->strftime('%FT%T%z'));
399         }
400
401         if ( $direction >= 0 ) {
402             $after = $_dt_parser->parse_datetime( $end );
403             $after->add( minutes => 1 );
404
405             while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1, 1 ) ) {
406                 $after = $_dt_parser->parse_datetime( cleanse_ISO8601($_a->{end}) );
407             }
408             $end = cleanse_ISO8601($after->strftime('%FT%T%z'));
409         }
410     }
411
412     if ( !$no_hoo ) {
413         if ( $hoo ) {
414
415             if ( $direction <= 0 ) {
416                 my $begin_dow = $_dt_parser->parse_datetime( $begin )->day_of_week_0;
417                 my $begin_open_meth = "dow_".$begin_dow."_open";
418                 my $begin_close_meth = "dow_".$begin_dow."_close";
419
420                 my $count = 1;
421                 while ($hoo->$begin_open_meth eq '00:00:00' and $hoo->$begin_close_meth eq '00:00:00') {
422                     $begin = cleanse_ISO8601($_dt_parser->parse_datetime( $begin )->subtract( days => 1)->strftime('%FT%T%z'));
423                     $begin_dow++;
424                     $begin_dow %= 7;
425                     $count++;
426                     last if ($count > 6);
427                     $begin_open_meth = "dow_".$begin_dow."_open";
428                     $begin_close_meth = "dow_".$begin_dow."_close";
429                 }
430
431                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $begin, $ou )) {
432                     $before = $_dt_parser->parse_datetime( $begin );
433                     $before->subtract( minutes => 1 );
434                     while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1 ) ) {
435                         $before = $_dt_parser->parse_datetime( cleanse_ISO8601($_b->{start}) );
436                     }
437                 }
438             }
439     
440             if ( $direction >= 0 ) {
441                 my $end_dow = $_dt_parser->parse_datetime( $end )->day_of_week_0;
442                 my $end_open_meth = "dow_".$end_dow."_open";
443                 my $end_close_meth = "dow_".$end_dow."_close";
444     
445                 $count = 1;
446                 while ($hoo->$end_open_meth eq '00:00:00' and $hoo->$end_close_meth eq '00:00:00') {
447                     $end = cleanse_ISO8601($_dt_parser->parse_datetime( $end )->add( days => 1)->strftime('%FT%T%z'));
448                     $end_dow++;
449                     $end_dow %= 7;
450                     $count++;
451                     last if ($count > 6);
452                     $end_open_meth = "dow_".$end_dow."_open";
453                     $end_close_meth = "dow_".$end_dow."_close";
454                 }
455
456                 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $end, $ou )) {
457                     $after = $_dt_parser->parse_datetime( $end );
458                     $after->add( minutes => 1 );
459
460                     while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1 ) ) {
461                         $after = $_dt_parser->parse_datetime( cleanse_ISO8601($_a->{end}) );
462                     }
463                     $end = cleanse_ISO8601($after->strftime('%FT%T%z'));
464                 }
465             }
466
467         }
468     }
469
470     if ($begin eq $date && $end eq $date) {
471         return undef;
472     }
473
474     return { start => $begin, end => $end };
475 }
476 __PACKAGE__->register_method(
477         api_name        => 'open-ils.storage.actor.org_unit.closed_date.overlap',
478         api_level       => 1,
479         method          => 'org_closed_overlap',
480 );
481
482 sub user_by_barcode {
483         my $self = shift;
484         my $client = shift;
485         my @barcodes = shift;
486
487         return undef unless @barcodes;
488
489         for my $card ( actor::card->search( { barcode => @barcodes } ) ) {
490                 next unless $card;
491                 if (@barcodes == 1) {
492                         return $card->usr->to_fieldmapper;
493                 }
494                 $client->respond( $card->usr->to_fieldmapper);
495         }
496         return undef;
497 }
498 __PACKAGE__->register_method(
499         api_name        => 'open-ils.storage.direct.actor.user.search.barcode',
500         api_level       => 1,
501         method          => 'user_by_barcode',
502         stream          => 1,
503         cachable        => 1,
504 );
505
506 sub lost_barcodes {
507         my $self = shift;
508         my $client = shift;
509
510         my $c = actor::card->table;
511         my $p = actor::user->table;
512
513         my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.card <> c.id";
514
515         my $list = actor::user->db_Main->selectcol_arrayref($sql);
516         for my $bc ( @$list ) {
517                 $client->respond($bc);
518         }
519         return undef;
520 }
521 __PACKAGE__->register_method(
522         api_name        => 'open-ils.storage.actor.user.lost_barcodes',
523         api_level       => 1,
524         stream          => 1,
525         method          => 'lost_barcodes',
526         signature       => <<'  NOTE',
527                 Returns an array of barcodes that belong to lost cards.
528                 @return array of barcodes
529         NOTE
530 );
531
532 sub expired_barcodes {
533         my $self = shift;
534         my $client = shift;
535
536         my $c = actor::card->table;
537         my $p = actor::user->table;
538
539         my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.expire_date < CURRENT_DATE";
540
541         my $list = actor::user->db_Main->selectcol_arrayref($sql);
542         for my $bc ( @$list ) {
543                 $client->respond($bc);
544         }
545         return undef;
546 }
547 __PACKAGE__->register_method(
548         api_name        => 'open-ils.storage.actor.user.expired_barcodes',
549         api_level       => 1,
550         stream          => 1,
551         method          => 'expired_barcodes',
552         signature       => <<'  NOTE',
553                 Returns an array of barcodes that are currently expired.
554                 @return array of barcodes
555         NOTE
556 );
557
558 sub barred_barcodes {
559         my $self = shift;
560         my $client = shift;
561
562         my $c = actor::card->table;
563         my $p = actor::user->table;
564
565         my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.barred IS TRUE";
566
567         my $list = actor::user->db_Main->selectcol_arrayref($sql);
568         for my $bc ( @$list ) {
569                 $client->respond($bc);
570         }
571         return undef;
572 }
573 __PACKAGE__->register_method(
574         api_name        => 'open-ils.storage.actor.user.barred_barcodes',
575         api_level       => 1,
576         stream          => 1,
577         method          => 'barred_barcodes',
578         signature       => <<'  NOTE',
579                 Returns an array of barcodes that are currently barred.
580                 @return array of barcodes
581         NOTE
582 );
583
584 sub penalized_barcodes {
585         my $self = shift;
586         my $client = shift;
587
588         my $c = actor::card->table;
589         my $p = actor::user_standing_penalty->table;
590
591         my $sql = <<"   SQL";
592                 SELECT  DISTINCT c.barcode
593                   FROM  $c c
594                         JOIN $p p USING (usr)
595                         JOIN config.standing_penalty csp ON (csp.id = p.standing_penalty)
596                   WHERE csp.block_list IS NOT NULL
597                         AND p.set_date < CURRENT_DATE
598                         AND (p.stop_date IS NULL OR p.stop_date > CURRENT_DATE);
599         SQL
600
601         my $list = actor::user->db_Main->selectcol_arrayref($sql);
602         for my $bc ( @$list ) {
603                 $client->respond($bc);
604         }
605         return undef;
606 }
607 __PACKAGE__->register_method(
608         api_name        => 'open-ils.storage.actor.user.penalized_barcodes',
609         api_level       => 1,
610         stream          => 1,
611         method          => 'penalized_barcodes',
612         signature       => <<'  NOTE',
613                 Returns an array of barcodes that have blocking penalties.
614                 @return array of barcodes
615         NOTE
616 );
617
618 sub _clean_regex_chars {
619     my ($search) = @_;
620
621     # Escape metacharacters for SIMILAR TO 
622     # (http://www.postgresql.org/docs/8.4/interactive/functions-matching.html)
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     $search =~ s/\(/\\(/g;
631     $search =~ s/\)/\\)/g;
632
633     return $search;
634 }
635
636 sub patron_search {
637         my $self = shift;
638         my $client = shift;
639         my $search = shift;
640         my $limit = shift || 1000;
641         my $sort = shift;
642         my $inactive = shift;
643         my $ws_ou = shift;
644         my $ws_ou_depth = shift || 0;
645
646     my $penalty_sort = 0;
647
648         my $strict_opt_in = OpenSRF::Utils::SettingsClient->new->config_value( share => user => 'opt_in' );
649
650         $sort = ['family_name','first_given_name'] unless ($$sort[0]);
651         push @$sort,'id';
652
653     if ($$sort[0] eq 'penalties') {
654         shift @$sort;
655         $penalty_sort = 1;
656     }
657
658         # group 0 = user
659         # group 1 = address
660         # group 2 = phone, ident
661         # group 3 = barcode
662
663         my $usr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
664         my @usrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '0' } keys %$search;
665
666         my $addr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
667         my @addrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
668
669         my $pv = _clean_regex_chars($$search{phone}{value});
670         my $iv = _clean_regex_chars($$search{ident}{value});
671         my $nv = _clean_regex_chars($$search{name}{value});
672         my $cv = _clean_regex_chars($$search{card}{value});
673
674         my $card = '';
675         if ($cv) {
676             $card = 'JOIN (SELECT DISTINCT usr FROM actor.card WHERE evergreen.lowercase(barcode) LIKE ?||\'%\') AS card ON (card.usr = users.id)';
677             unshift(@usrv, $cv);
678         }
679
680         my $phone = '';
681         my @ps;
682         my @phonev;
683         if ($pv) {
684                 for my $p ( qw/day_phone evening_phone other_phone/ ) {
685                         if ($pv =~ /^\d+$/) {
686                                 push @ps, "evergreen.lowercase(REGEXP_REPLACE($p, '[^0-9]', '', 'g')) ~ ?";
687                         } else {
688                                 push @ps, "evergreen.lowercase($p) ~ ?";
689                         }
690                         push @phonev, "^$pv";
691                 }
692                 $phone = '(' . join(' OR ', @ps) . ')';
693         }
694
695         my $ident = '';
696         my @is;
697         my @identv;
698         if ($iv) {
699                 for my $i ( qw/ident_value ident_value2/ ) {
700                         push @is, "evergreen.lowercase($i) ~ ?";
701                         push @identv, "^$iv";
702                 }
703                 $ident = '(' . join(' OR ', @is) . ')';
704         }
705
706         my $name = '';
707         my @ns;
708         my @namev;
709         if (0 && $nv) {
710                 for my $n ( qw/first_given_name second_given_name family_name/ ) {
711                         push @ns, "evergreen.lowercase($n) ~ ?";
712                         push @namev, "^$nv";
713                 }
714                 $name = '(' . join(' OR ', @ns) . ')';
715         }
716
717         my $usr_where = join ' AND ', grep { $_ } ($usr,$phone,$ident,$name);
718         my $addr_where = $addr;
719
720
721         my $u_table = actor::user->table;
722         my $a_table = actor::user_address->table;
723         my $opt_in_table = actor::usr_org_unit_opt_in->table;
724         my $ou_table = actor::org_unit->table;
725
726         my $u_select = "SELECT id as id FROM $u_table u WHERE $usr_where";
727         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";
728
729         my $clone_select = '';
730
731         #$clone_select = "JOIN (SELECT cu.id as id FROM $a_table ca ".
732         #                  "JOIN $u_table cu ON (cu.mailing_address = ca.id OR cu.billing_address = ca.id) ".
733         #                  "WHERE $addr_where) AS clone ON (clone.id = users.id)" if ($addr_where);
734
735         my $select = '';
736         if ($usr_where) {
737                 if ($addr_where) {
738                         $select = "$u_select INTERSECT $a_select";
739                 } else {
740                         $select = $u_select;
741                 }
742         } elsif ($addr_where) {
743                 $select = "$a_select";
744         }
745
746         return undef if (!$select && !$card);
747
748         my $order_by = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text)) ' . (split / /,$_)[1] } @$sort;
749         my $distinct_list = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text))' } @$sort;
750     my $group_list = $distinct_list;
751
752         if ($inactive) {
753                 $inactive = '';
754         } else {
755                 $inactive = 'AND users.active = TRUE';
756         }
757
758         if (!$ws_ou) {  # XXX This should be required!!
759                 $ws_ou = actor::org_unit->search( { parent_ou => undef } )->next->id;
760         }
761
762         my $opt_in_join = '';
763         my $opt_in_where = '';
764         if (lc($strict_opt_in) eq 'true') {
765                 $opt_in_join = "LEFT JOIN $opt_in_table oi ON (oi.org_unit = $ws_ou AND users.id = oi.usr)";
766                 $opt_in_where = "AND (oi.id IS NOT NULL OR users.home_ou = $ws_ou)";
767         }
768
769         my $penalty_join = '';
770     if ($penalty_sort) {
771         $distinct_list = 'COUNT(penalties.id), ' . $distinct_list;
772         $order_by = 'COUNT(penalties.id) DESC, ' . $order_by;
773         unshift @$sort, 'COUNT(penalties.id)';
774             $penalty_join = <<"        SQL";
775             LEFT JOIN actor.usr_standing_penalty penalties
776                 ON (users.id = penalties.usr AND (penalties.stop_date IS NULL OR penalties.stop_date > NOW()))
777         SQL
778     }
779
780         my $descendants = "actor.org_unit_descendants($ws_ou, $ws_ou_depth)";
781
782         $select = "JOIN ($select) AS search ON (search.id = users.id)" if ($select);
783         $select = <<"   SQL";
784                 SELECT  $distinct_list
785                   FROM  $u_table AS users $card
786                         JOIN $descendants d ON (d.id = users.home_ou)
787                         $select
788                         $opt_in_join
789                         $clone_select
790             $penalty_join
791                   WHERE users.deleted = FALSE
792                         $inactive
793                         $opt_in_where
794                   GROUP BY $group_list
795                   ORDER BY $order_by
796                   LIMIT $limit
797         SQL
798
799         return actor::user->db_Main->selectcol_arrayref($select, {Columns=>[scalar(@$sort)]}, map {lc($_)} (@usrv,@phonev,@identv,@namev,@addrv));
800 }
801 __PACKAGE__->register_method(
802         api_name        => 'open-ils.storage.actor.user.crazy_search',
803         api_level       => 1,
804         method          => 'patron_search',
805 );
806
807 sub org_unit_list {
808         my $self = shift;
809         my $client = shift;
810
811         my $select =<<" SQL";
812         SELECT  *
813           FROM  actor.org_unit
814           ORDER BY CASE WHEN parent_ou IS NULL THEN 0 ELSE 1 END, name;
815         SQL
816
817         my $sth = actor::org_unit->db_Main->prepare_cached($select);
818         $sth->execute;
819
820         $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
821
822         return undef;
823 }
824 __PACKAGE__->register_method(
825         api_name        => 'open-ils.storage.direct.actor.org_unit.retrieve.all',
826         api_level       => 1,
827         stream          => 1,
828         method          => 'org_unit_list',
829 );
830
831 sub org_unit_type_list {
832         my $self = shift;
833         my $client = shift;
834
835         my $select =<<" SQL";
836         SELECT  *
837           FROM  actor.org_unit_type
838           ORDER BY depth, name;
839         SQL
840
841         my $sth = actor::org_unit_type->db_Main->prepare_cached($select);
842         $sth->execute;
843
844         $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit_type->construct($_) } $sth->fetchall_hash );
845
846         return undef;
847 }
848 __PACKAGE__->register_method(
849         api_name        => 'open-ils.storage.direct.actor.org_unit_type.retrieve.all',
850         api_level       => 1,
851         stream          => 1,
852         method          => 'org_unit_type_list',
853 );
854
855 sub org_unit_full_path {
856         my $self = shift;
857         my $client = shift;
858         my @binds = @_;
859
860         return undef unless (@binds);
861
862         my $func = 'actor.org_unit_full_path(?)';
863         $func = 'actor.org_unit_full_path(?,?)' if (@binds > 1);
864
865         my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
866         $sth->execute(@binds);
867
868         $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
869
870         return undef;
871 }
872 __PACKAGE__->register_method(
873         api_name        => 'open-ils.storage.actor.org_unit.full_path',
874         api_level       => 1,
875         stream          => 1,
876         method          => 'org_unit_full_path',
877 );
878
879 sub org_unit_ancestors {
880         my $self = shift;
881         my $client = shift;
882         my $id = shift;
883
884         return undef unless ($id);
885
886         my $func = 'actor.org_unit_ancestors(?)';
887
888         my $sth = actor::org_unit->db_Main->prepare_cached(<<"  SQL");
889                 SELECT  f.*
890                   FROM  $func f
891                         JOIN actor.org_unit_type t ON (f.ou_type = t.id)
892                   ORDER BY t.depth, f.name;
893         SQL
894         $sth->execute(''.$id);
895
896         $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
897
898         return undef;
899 }
900 __PACKAGE__->register_method(
901         api_name        => 'open-ils.storage.actor.org_unit.ancestors',
902         api_level       => 1,
903         stream          => 1,
904         method          => 'org_unit_ancestors',
905 );
906
907 sub org_unit_descendants {
908         my $self = shift;
909         my $client = shift;
910         my $id = shift;
911         my $depth = shift;
912
913         return undef unless ($id);
914
915         my $func = 'actor.org_unit_descendants(?)';
916         if (defined $depth) {
917                 $func = 'actor.org_unit_descendants(?,?)';
918         }
919
920         my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
921         $sth->execute(''.$id, ''.$depth) if (defined $depth);
922         $sth->execute(''.$id) unless (defined $depth);
923
924         $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
925
926         return undef;
927 }
928 __PACKAGE__->register_method(
929         api_name        => 'open-ils.storage.actor.org_unit.descendants',
930         api_level       => 1,
931         stream          => 1,
932         method          => 'org_unit_descendants',
933 );
934
935 sub fleshed_actor_stat_cat {
936         my $self = shift;
937         my $client = shift;
938         my @list = @_;
939         
940         @list = ($list[0]) unless ($self->api_name =~ /batch/o);
941
942         for my $sc (@list) {
943                 my $cat = actor::stat_cat->retrieve($sc);
944                 next unless ($cat);
945
946                 my $sc_fm = $cat->to_fieldmapper;
947                 $sc_fm->entries( [ map { $_->to_fieldmapper } $cat->entries ] );
948
949                 $client->respond( $sc_fm );
950
951         }
952
953         return undef;
954 }
955 __PACKAGE__->register_method(
956         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve',
957         api_level       => 1,
958         argc            => 1,
959         method          => 'fleshed_actor_stat_cat',
960 );
961
962 __PACKAGE__->register_method(
963         api_name        => 'open-ils.storage.fleshed.actor.stat_cat.retrieve.batch',
964         api_level       => 1,
965         argc            => 1,
966         stream          => 1,
967         method          => 'fleshed_actor_stat_cat',
968 );
969
970 #XXX Fix stored proc calls
971 sub ranged_actor_stat_cat_all {
972         my $self = shift;
973         my $client = shift;
974         my $ou = ''.shift();
975         
976         return undef unless ($ou);
977         my $s_table = actor::stat_cat->table;
978
979         my $select = <<"        SQL";
980                 SELECT  s.*
981                   FROM  $s_table s
982                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
983                   ORDER BY name
984         SQL
985
986         $fleshed = 0;
987         $fleshed = 1 if ($self->api_name =~ /fleshed/o);
988
989         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
990         $sth->execute($ou);
991
992         for my $sc ( map { actor::stat_cat->construct($_) } $sth->fetchall_hash ) {
993                 my $sc_fm = $sc->to_fieldmapper;
994                 $sc_fm->entries(
995                         [ $self->method_lookup( 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat' )->run($ou,$sc->id) ]
996                 ) if ($fleshed);
997                 $client->respond( $sc_fm );
998         }
999
1000         return undef;
1001 }
1002 __PACKAGE__->register_method(
1003         api_name        => 'open-ils.storage.ranged.fleshed.actor.stat_cat.all',
1004         api_level       => 1,
1005         argc            => 1,
1006         stream          => 1,
1007         method          => 'ranged_actor_stat_cat_all',
1008 );
1009
1010 __PACKAGE__->register_method(
1011         api_name        => 'open-ils.storage.ranged.actor.stat_cat.all',
1012         api_level       => 1,
1013         argc            => 1,
1014         stream          => 1,
1015         method          => 'ranged_actor_stat_cat_all',
1016 );
1017
1018 #XXX Fix stored proc calls
1019 sub ranged_actor_stat_cat_entry {
1020         my $self = shift;
1021         my $client = shift;
1022         my $ou = ''.shift();
1023         my $sc = ''.shift();
1024         
1025         return undef unless ($ou);
1026         my $s_table = actor::stat_cat_entry->table;
1027
1028         my $select = <<"        SQL";
1029                 SELECT  s.*
1030                   FROM  $s_table s
1031                         JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1032                   WHERE stat_cat = ?
1033                   ORDER BY name
1034         SQL
1035
1036         my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1037         $sth->execute($ou,$sc);
1038
1039         for my $sce ( map { actor::stat_cat_entry->construct($_) } $sth->fetchall_hash ) {
1040                 $client->respond( $sce->to_fieldmapper );
1041         }
1042
1043         return undef;
1044 }
1045 __PACKAGE__->register_method(
1046         api_name        => 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat',
1047         api_level       => 1,
1048         stream          => 1,
1049         method          => 'ranged_actor_stat_cat_entry',
1050 );
1051
1052
1053 1;