1 package OpenILS::Application::Storage::Publisher::actor;
2 use base qw/OpenILS::Application::Storage/;
3 use OpenILS::Application::Storage::CDBI::actor;
4 use OpenSRF::Utils::Logger qw/:level/;
5 use OpenILS::Utils::DateTime qw/:datetime/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenSRF::Utils::SettingsClient;
8 use OpenILS::Application::AppUtils;
9 use OpenSRF::Utils::JSON;
11 use DateTime::Format::ISO8601;
13 use DateTime::SpanSet;
15 my $U = "OpenILS::Application::AppUtils";
16 my $JSON = "OpenSRF::Utils::JSON";
18 my $_dt_parser = DateTime::Format::ISO8601->new;
20 my $log = 'OpenSRF::Utils::Logger';
22 sub new_usergroup_id {
23 return actor::user->db_Main->selectrow_array("select nextval('actor.usr_usrgroup_seq'::regclass)");
25 __PACKAGE__->register_method(
26 api_name => 'open-ils.storage.actor.user.group_id.new',
28 method => 'new_usergroup_id',
34 my $adult_age = shift;
39 WHERE juvenile IS TRUE
41 AND AGE(dob) > COALESCE( BTRIM( (
42 SELECT value FROM actor.org_unit_ancestor_setting(
43 'global.juvenile_age_threshold', home_ou)),'"' ), ?)::INTERVAL
46 my $sth = actor::user->db_Main->prepare_cached($sql);
47 $sth->execute($adult_age);
51 __PACKAGE__->register_method(
52 api_name => 'open-ils.storage.actor.user.juvenile_to_adult',
54 method => 'juv_to_adult',
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
71 my (undef,$val) = actor::user->db_Main->selectrow_array($sql, {}, $usr);
75 __PACKAGE__->register_method(
76 api_name => 'open-ils.storage.actor.user.total_owed',
78 method => 'usr_total_owed',
81 sub usr_breakdown_out {
86 $self->method_lookup('open-ils.storage.transaction.begin')->run();
88 my $out_sql = <<" SQL";
90 FROM action.circulation
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'))
99 my $out = actor::user->db_Main->selectcol_arrayref($out_sql, {}, $usr);
101 my $od_sql = <<" SQL";
103 FROM action.circulation
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'))
112 my $od = actor::user->db_Main->selectcol_arrayref($od_sql, {}, $usr);
114 my $lost_sql = <<" SQL";
116 FROM action.circulation
117 WHERE usr = ? AND checkin_time IS NULL AND xact_finish IS NULL AND stop_fines = 'LOST'
120 my $lost = actor::user->db_Main->selectcol_arrayref($lost_sql, {}, $usr);
122 my $cl_sql = <<" SQL";
124 FROM action.circulation
125 WHERE usr = ? AND checkin_time IS NULL AND stop_fines = 'CLAIMSRETURNED'
128 my $cl = actor::user->db_Main->selectcol_arrayref($cl_sql, {}, $usr);
130 my $lo_sql = <<" SQL";
132 FROM action.circulation
133 WHERE usr = ? AND checkin_time IS NULL AND stop_fines = 'LONGOVERDUE'
136 my $lo = actor::user->db_Main->selectcol_arrayref($lo_sql, {}, $usr);
138 $self->method_lookup('open-ils.storage.transaction.rollback')->run();
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),
150 return { out => $out,
153 claims_returned => $cl,
157 __PACKAGE__->register_method(
158 api_name => 'open-ils.storage.actor.user.checked_out',
160 method => 'usr_breakdown_out',
162 __PACKAGE__->register_method(
163 api_name => 'open-ils.storage.actor.user.checked_out.count',
165 method => 'usr_breakdown_out',
175 FROM action.circulation
176 WHERE usr = ? AND checkin_time IS NULL
179 my ($val) = actor::user->db_Main->selectrow_array($sql, {}, $usr);
183 __PACKAGE__->register_method(
184 api_name => 'open-ils.storage.actor.user.total_out',
186 method => 'usr_total_out',
193 local $OpenILS::Application::Storage::WRITE = 1;
195 my $delete_sql = <<" SQL";
196 DELETE FROM actor.org_unit_proximity;
199 my $insert_sql = <<" SQL";
200 INSERT INTO actor.org_unit_proximity (from_org, to_org, prox)
203 actor.org_unit_proximity(l.id,r.id)
204 FROM actor.org_unit l,
208 actor::org_unit_proximity->db_Main->do($delete_sql);
209 actor::org_unit_proximity->db_Main->do($insert_sql);
213 __PACKAGE__->register_method(
214 api_name => 'open-ils.storage.actor.org_unit.refresh_proximity',
216 method => 'calc_proximity',
219 sub make_hoo_spanset {
221 return undef unless $hoo;
223 my $today = shift || DateTime->now;
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;
229 my $current_dow = $today->day_of_week_0;
231 my $spanset = DateTime::SpanSet->empty_set;
232 for my $d ( 0 .. 6 ) {
234 my $omethod = 'dow_'.$d.'_open';
235 my $cmethod = 'dow_'.$d.'_close';
237 my $open = interval_to_seconds($hoo->$omethod());
238 my $close = interval_to_seconds($hoo->$cmethod());
240 next if ($open == $close && $open == 0);
242 my $dow_offset = ($d - $current_dow) * $one_day;
243 $close += $one_day if ($close <= $open);
245 $spanset = $spanset->union(
247 start => $today->clone->add( seconds => $dow_offset + $open ),
248 end => $today->clone->add( seconds => $dow_offset + $close )
253 return $spanset->complement;
256 sub make_closure_spanset {
257 my $closures = shift;
258 return undef unless $closures;
260 my $spanset = DateTime::SpanSet->empty_set;
261 for my $k ( keys %$closures ) {
262 my $c = $$closures{$k};
264 $spanset = $spanset->union(
266 start => $_dt_parser->parse_datetime(clean_ISO8601($c->{close_start})),
267 end => $_dt_parser->parse_datetime(clean_ISO8601($c->{close_end}))
275 sub new_org_closed_overlap {
280 my $direction = shift || 0;
281 my $no_hoo = shift || 0;
283 return undef unless ($date && $ou);
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;
292 ORDER BY close_start ASC, close_end DESC
296 $date = clean_ISO8601($date);
298 my $target_date = $_dt_parser->parse_datetime( $date );
299 my ($begin, $end) = ($target_date, $target_date);
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 )
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;
311 if ( $direction <= 0 ) {
312 $begin->subtract( minutes => 1 );
314 while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1, 1 ) ) {
315 $begin = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
319 if ( $direction >= 0 ) {
320 $end->add( minutes => 1 );
322 while ( my $_a = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), 1, 1 ) ) {
323 $end = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
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 );
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 );
339 while ( my $_b = new_org_closed_overlap($self, $client, $ou, $begin->strftime('%FT%T%z'), -1 ) ) {
340 $begin = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
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 );
350 while ( my $_b = new_org_closed_overlap($self, $client, $ou, $end->strftime('%FT%T%z'), -1 ) ) {
351 $end = $_dt_parser->parse_datetime( clean_ISO8601($_b->{end}) );
356 my $start = $begin->strftime('%FT%T%z');
357 my $stop = $end->strftime('%FT%T%z');
359 return undef if ($start eq $stop);
360 return { start => $start, end => $stop };
362 __PACKAGE__->register_method(
363 api_name => 'open-ils.storage.actor.org_unit.closed_date.overlap',
365 method => 'new_org_closed_overlap',
368 sub org_closed_overlap {
373 my $direction = shift || 0;
374 my $no_hoo = shift || 0;
376 return undef unless ($date && $ou);
378 my $t = actor::org_unit::closed_date->table;
382 WHERE ? between close_start and close_end
384 ORDER BY close_start ASC, close_end DESC
388 $date = clean_ISO8601($date);
389 my ($begin, $end) = ($date,$date);
391 my $hoo = actor::org_unit::hours_of_operation->retrieve($ou);
393 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $date, $ou )) {
394 $begin = clean_ISO8601($closure->{close_start});
395 $end = clean_ISO8601($closure->{close_end});
397 if ( $direction <= 0 ) {
398 $before = $_dt_parser->parse_datetime( $begin );
399 $before->subtract( minutes => 1 );
401 while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1, 1 ) ) {
402 $before = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
404 $begin = clean_ISO8601($before->strftime('%FT%T%z'));
407 if ( $direction >= 0 ) {
408 $after = $_dt_parser->parse_datetime( $end );
409 $after->add( minutes => 1 );
411 while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1, 1 ) ) {
412 $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
414 $end = clean_ISO8601($after->strftime('%FT%T%z'));
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";
427 while ($hoo->$begin_open_meth eq '00:00:00' and $hoo->$begin_close_meth eq '00:00:00') {
428 $begin = clean_ISO8601($_dt_parser->parse_datetime( $begin )->subtract( days => 1)->strftime('%FT%T%z'));
432 last if ($count > 6);
433 $begin_open_meth = "dow_".$begin_dow."_open";
434 $begin_close_meth = "dow_".$begin_dow."_close";
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( clean_ISO8601($_b->{start}) );
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";
452 while ($hoo->$end_open_meth eq '00:00:00' and $hoo->$end_close_meth eq '00:00:00') {
453 $end = clean_ISO8601($_dt_parser->parse_datetime( $end )->add( days => 1)->strftime('%FT%T%z'));
457 last if ($count > 6);
458 $end_open_meth = "dow_".$end_dow."_open";
459 $end_close_meth = "dow_".$end_dow."_close";
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 );
466 while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1 ) ) {
467 $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
469 $end = clean_ISO8601($after->strftime('%FT%T%z'));
476 if ($begin eq $date && $end eq $date) {
480 return { start => $begin, end => $end };
482 __PACKAGE__->register_method(
483 api_name => 'open-ils.storage.actor.org_unit.closed_date.overlap',
485 method => 'org_closed_overlap',
488 sub user_by_barcode {
491 my @barcodes = shift;
493 return undef unless @barcodes;
495 for my $card ( actor::card->search( { barcode => @barcodes } ) ) {
497 if (@barcodes == 1) {
498 return $card->usr->to_fieldmapper;
500 $client->respond( $card->usr->to_fieldmapper);
504 __PACKAGE__->register_method(
505 api_name => 'open-ils.storage.direct.actor.user.search.barcode',
507 method => 'user_by_barcode',
516 my $c = actor::card->table;
517 my $p = actor::user->table;
519 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.card <> c.id";
521 my $list = actor::user->db_Main->selectcol_arrayref($sql);
522 for my $bc ( @$list ) {
523 $client->respond($bc);
527 __PACKAGE__->register_method(
528 api_name => 'open-ils.storage.actor.user.lost_barcodes',
531 method => 'lost_barcodes',
532 signature => <<' NOTE',
533 Returns an array of barcodes that belong to lost cards.
534 @return array of barcodes
538 sub expired_barcodes {
542 my $c = actor::card->table;
543 my $p = actor::user->table;
545 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.expire_date < CURRENT_DATE";
547 my $list = actor::user->db_Main->selectcol_arrayref($sql);
548 for my $bc ( @$list ) {
549 $client->respond($bc);
553 __PACKAGE__->register_method(
554 api_name => 'open-ils.storage.actor.user.expired_barcodes',
557 method => 'expired_barcodes',
558 signature => <<' NOTE',
559 Returns an array of barcodes that are currently expired.
560 @return array of barcodes
564 sub barred_barcodes {
568 my $c = actor::card->table;
569 my $p = actor::user->table;
571 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.barred IS TRUE";
573 my $list = actor::user->db_Main->selectcol_arrayref($sql);
574 for my $bc ( @$list ) {
575 $client->respond($bc);
579 __PACKAGE__->register_method(
580 api_name => 'open-ils.storage.actor.user.barred_barcodes',
583 method => 'barred_barcodes',
584 signature => <<' NOTE',
585 Returns an array of barcodes that are currently barred.
586 @return array of barcodes
590 sub penalized_barcodes {
594 my $c = actor::card->table;
595 my $p = actor::user_standing_penalty->table;
598 SELECT DISTINCT c.barcode
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);
607 my $list = actor::user->db_Main->selectcol_arrayref($sql);
608 for my $bc ( @$list ) {
609 $client->respond($bc);
613 __PACKAGE__->register_method(
614 api_name => 'open-ils.storage.actor.user.penalized_barcodes',
617 method => 'penalized_barcodes',
618 signature => <<' NOTE',
619 Returns an array of barcodes that have blocking penalties.
620 @return array of barcodes
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);
630 return ($r && @$r) ? $r->[0] : $search;
633 sub _clean_regex_chars {
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;
655 my $limit = shift || 1000;
657 my $inactive = shift;
659 my $search_org = shift || $ws_ou;
660 my $opt_boundary = shift || 0;
661 my $offset = shift || 0;
663 my $penalty_sort = 0;
665 my $strict_opt_in = OpenSRF::Utils::SettingsClient->new->config_value( share => user => 'opt_in' );
667 $sort = ['family_name','first_given_name'] unless ($$sort[0]);
670 if ($$sort[0] eq 'penalties') {
677 # group 2 = phone, ident
682 # Treatment of name fields depends on whether the org has
683 # diacritic_insensitivity turned on or off.
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;
693 # Compile the WHERE component of the actor.usr fields.
694 # When a name field is encountered, search both the name field and
695 # the alternate version of the name field.
696 my @name_fields = qw/prefix first_given_name second_given_name family_name suffix/;
699 my @usr_fields = grep { ''.$$search{$_}{group} eq '0' } keys %$search;
700 for my $usr_field (@usr_fields) {
703 my $where_func = $diacritic_insensitive ?
704 "evergreen.unaccent_and_squash(CAST(%s AS text)) ~ ?" :
705 "evergreen.lowercase(CAST(%s AS text)) ~ ?";
707 my $val = $diacritic_insensitive ?
708 "^" . _prepare_name_argument($$search{$usr_field}{value}) :
709 "^" . _clean_regex_chars($$search{$usr_field}{value});
711 if (grep {$_ eq $usr_field} @name_fields) {
712 # When searching a name field include an OR search
713 # on the alternate version of the same field.
715 push(@usr_where_parts, sprintf(
716 "($where_func OR $where_func)", $usr_field, "pref_$usr_field")
719 # search main field and alt name field with same value.
725 push(@usr_where_parts, sprintf($where_func, $usr_field));
730 $usr = join ' AND ', @usr_where_parts;
732 while (($key, $value) = each (%$search)) {
733 if($$search{$key}{group} eq '4') {
736 my $right = "RIGHT('0'|| ";
738 $end = $right = '' if lc $tval eq 'year';
739 $dob .= $right."CAST(DATE_PART('$tval', dob) AS text)$end ~ ? AND ";
742 # Trim the last " AND "
743 $dob = substr($dob,0,-4);
744 @dobv = map { _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '4' } keys %$search;
745 $usr .= ' AND ' if ( $usr && $dob );
746 $usr .= $dob if $dob; # $dob not in-line above in case $usr doesn't have any search vals (only searched for dob)
747 push(@usrv, @dobv) if @dobv;
749 my $addr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
750 my @addrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
752 # should only be 1 profile sent but this construction makes dealing with the lists simpler.
753 my ($prof) = map { $$search{$_}{value} } grep {''.$$search{$_}{group} eq '5' } keys %$search;
754 $prof = int($prof) if $prof; # int or out
756 my $pv = _clean_regex_chars($$search{phone}{value});
757 my $iv = _clean_regex_chars($$search{ident}{value});
758 my $nv = _clean_regex_chars($$search{name}{value});
759 my $cv = _clean_regex_chars($$search{card}{value});
763 $card = 'JOIN (SELECT DISTINCT usr FROM actor.card WHERE evergreen.lowercase(barcode) LIKE ?||\'%\') AS card ON (card.usr = users.id)';
771 for my $p ( qw/day_phone evening_phone other_phone/ ) {
772 if ($pv =~ /^\d+$/) {
773 push @ps, "evergreen.lowercase(REGEXP_REPLACE($p, '[^0-9]', '', 'g')) ~ ?";
775 push @ps, "evergreen.lowercase($p) ~ ?";
777 push @phonev, "^$pv";
779 $phone = '(' . join(' OR ', @ps) . ')';
786 for my $i ( qw/ident_value ident_value2/ ) {
787 push @is, "evergreen.lowercase($i) ~ ?";
788 push @identv, "^$iv";
790 $ident = '(' . join(' OR ', @is) . ')';
793 # name keywords search
798 $name = "name_kw_tsvector @@ to_tsquery(?)";
800 # Remove characters that to_tsquery might treat as operators.
801 # Note using plainto_tsquery to ignore operators won't let us
802 # also do prefix matching.
803 $nv =~ s/[^\w\s\.\-']//g;
805 my @parts = split(' ', $nv);
807 # tsquery on multiple names joined w/ '&'
808 # Adding :* gives us prefix matching
809 push @namev, join(' & ', map { "$_:*" } @parts);
815 $profile = '(profile IN (SELECT id FROM permission.grp_descendants(?)))';
818 my $usr_where = join ' AND ', grep { $_ } ($usr,$phone,$ident,$name,$profile);
819 my $addr_where = $addr;
822 my $u_table = actor::user->table;
823 my $a_table = actor::user_address->table;
824 my $opt_in_table = actor::usr_org_unit_opt_in->table;
825 my $ou_table = actor::org_unit->table;
827 my $u_select = "SELECT id as id FROM $u_table u WHERE $usr_where";
828 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";
830 my $clone_select = '';
832 #$clone_select = "JOIN (SELECT cu.id as id FROM $a_table ca ".
833 # "JOIN $u_table cu ON (cu.mailing_address = ca.id OR cu.billing_address = ca.id) ".
834 # "WHERE $addr_where) AS clone ON (clone.id = users.id)" if ($addr_where);
839 $select = "$u_select INTERSECT $a_select";
843 } elsif ($addr_where) {
844 $select = "$a_select";
847 return undef if (!$select && !$card);
849 my $order_by = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text)) ' . (split / /,$_)[1] } @$sort;
850 my $distinct_list = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text))' } @$sort;
851 my $group_list = $distinct_list;
856 $inactive = 'AND users.active = TRUE';
859 if (!$ws_ou) { # XXX This should be required!!
860 $ws_ou = actor::org_unit->search( { parent_ou => undef } )->next->id;
863 my $descendants = "actor.org_unit_descendants($search_org)";
865 my $opt_in_where = '';
866 if (lc($strict_opt_in) eq 'true') {
867 $opt_in_where = "AND (";
868 $opt_in_where .= "EXISTS (select id FROM $opt_in_table ";
869 $opt_in_where .= " WHERE org_unit in (select (actor.org_unit_ancestors($ws_ou)).id)";
870 $opt_in_where .= " AND usr = users.id) ";
871 $opt_in_where .= "OR";
872 $opt_in_where .= " users.home_ou IN (select (actor.org_unit_descendants($ws_ou,$opt_boundary)).id))";
875 my $penalty_join = '';
877 $distinct_list = 'COUNT(penalties.id), ' . $distinct_list;
878 $order_by = 'COUNT(penalties.id) DESC, ' . $order_by;
879 unshift @$sort, 'COUNT(penalties.id)';
880 $penalty_join = <<" SQL";
881 LEFT JOIN actor.usr_standing_penalty penalties
882 ON (users.id = penalties.usr AND (penalties.stop_date IS NULL OR penalties.stop_date > NOW()))
886 $select = "JOIN ($select) AS search ON (search.id = users.id)" if ($select);
888 SELECT $distinct_list
889 FROM $u_table AS users $card
890 JOIN $descendants d ON (d.id = users.home_ou)
894 WHERE users.deleted = FALSE
903 return actor::user->db_Main->selectcol_arrayref($select, {Columns=>[scalar(@$sort)]}, map {lc($_)} (@usrv,@phonev,@identv,@namev,@profv,@addrv));
905 __PACKAGE__->register_method(
906 api_name => 'open-ils.storage.actor.user.crazy_search',
908 method => 'patron_search',
915 my $select =<<" SQL";
918 ORDER BY CASE WHEN parent_ou IS NULL THEN 0 ELSE 1 END, name;
921 my $sth = actor::org_unit->db_Main->prepare_cached($select);
924 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
928 __PACKAGE__->register_method(
929 api_name => 'open-ils.storage.direct.actor.org_unit.retrieve.all',
932 method => 'org_unit_list',
935 sub org_unit_type_list {
939 my $select =<<" SQL";
941 FROM actor.org_unit_type
942 ORDER BY depth, name;
945 my $sth = actor::org_unit_type->db_Main->prepare_cached($select);
948 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit_type->construct($_) } $sth->fetchall_hash );
952 __PACKAGE__->register_method(
953 api_name => 'open-ils.storage.direct.actor.org_unit_type.retrieve.all',
956 method => 'org_unit_type_list',
959 sub org_unit_full_path {
964 return undef unless (@binds);
966 my $func = 'actor.org_unit_full_path(?)';
967 $func = 'actor.org_unit_full_path(?,?)' if (@binds > 1);
969 my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
970 $sth->execute(@binds);
972 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
976 __PACKAGE__->register_method(
977 api_name => 'open-ils.storage.actor.org_unit.full_path',
980 method => 'org_unit_full_path',
983 sub org_unit_ancestors {
988 return undef unless ($id);
990 my $func = 'actor.org_unit_ancestors(?)';
992 my $sth = actor::org_unit->db_Main->prepare_cached(<<" SQL");
995 JOIN actor.org_unit_type t ON (f.ou_type = t.id)
996 ORDER BY t.depth, f.name;
998 $sth->execute(''.$id);
1000 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1004 __PACKAGE__->register_method(
1005 api_name => 'open-ils.storage.actor.org_unit.ancestors',
1008 method => 'org_unit_ancestors',
1011 sub org_unit_descendants {
1017 return undef unless ($id);
1019 my $func = 'actor.org_unit_descendants(?)';
1020 if (defined $depth) {
1021 $func = 'actor.org_unit_descendants(?,?)';
1024 my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
1025 $sth->execute(''.$id, ''.$depth) if (defined $depth);
1026 $sth->execute(''.$id) unless (defined $depth);
1028 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1032 __PACKAGE__->register_method(
1033 api_name => 'open-ils.storage.actor.org_unit.descendants',
1036 method => 'org_unit_descendants',
1039 sub fleshed_actor_stat_cat {
1044 @list = ($list[0]) unless ($self->api_name =~ /batch/o);
1046 for my $sc (@list) {
1047 my $cat = actor::stat_cat->retrieve($sc);
1050 my $sc_fm = $cat->to_fieldmapper;
1051 $sc_fm->entries( [ map { $_->to_fieldmapper } $cat->entries ] );
1052 $sc_fm->default_entries( [ map { $_->to_fieldmapper } $cat->default_entries ] );
1054 $client->respond( $sc_fm );
1060 __PACKAGE__->register_method(
1061 api_name => 'open-ils.storage.fleshed.actor.stat_cat.retrieve',
1064 method => 'fleshed_actor_stat_cat',
1067 __PACKAGE__->register_method(
1068 api_name => 'open-ils.storage.fleshed.actor.stat_cat.retrieve.batch',
1072 method => 'fleshed_actor_stat_cat',
1075 #XXX Fix stored proc calls
1076 sub ranged_actor_stat_cat_all {
1079 my $ou = ''.shift();
1081 return undef unless ($ou);
1082 my $s_table = actor::stat_cat->table;
1084 my $select = <<" SQL";
1087 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1092 $fleshed = 1 if ($self->api_name =~ /fleshed/o);
1094 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1097 for my $sc ( map { actor::stat_cat->construct($_) } $sth->fetchall_hash ) {
1098 my $sc_fm = $sc->to_fieldmapper;
1100 [ $self->method_lookup( 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat' )->run($ou,$sc->id) ]
1102 $sc_fm->default_entries(
1103 [ $self->method_lookup( 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve' )->run($ou,$sc->id) ]
1105 $client->respond( $sc_fm );
1110 __PACKAGE__->register_method(
1111 api_name => 'open-ils.storage.ranged.fleshed.actor.stat_cat.all',
1115 method => 'ranged_actor_stat_cat_all',
1118 __PACKAGE__->register_method(
1119 api_name => 'open-ils.storage.ranged.actor.stat_cat.all',
1123 method => 'ranged_actor_stat_cat_all',
1126 #XXX Fix stored proc calls
1127 sub ranged_actor_stat_cat_entry {
1130 my $ou = ''.shift();
1131 my $sc = ''.shift();
1133 return undef unless ($ou);
1134 my $s_table = actor::stat_cat_entry->table;
1136 my $select = <<" SQL";
1139 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1144 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1145 $sth->execute($ou,$sc);
1147 for my $sce ( map { actor::stat_cat_entry->construct($_) } $sth->fetchall_hash ) {
1148 my $sce_fm = $sce->to_fieldmapper;
1149 $client->respond( $sce_fm );
1154 __PACKAGE__->register_method(
1155 api_name => 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat',
1158 method => 'ranged_actor_stat_cat_entry',
1161 sub actor_stat_cat_entry_default {
1164 my $ou = ''.shift();
1165 my $sc = ''.shift();
1167 return undef unless ($ou);
1168 my $s_table = actor::stat_cat_entry_default->table;
1170 my $select = <<" SQL";
1173 WHERE owner = ? AND stat_cat = ?
1176 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1177 $sth->execute($ou,$sc);
1179 for my $sced ( map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash ) {
1180 $client->respond( $sced->to_fieldmapper );
1185 __PACKAGE__->register_method(
1186 api_name => 'open-ils.storage.actor.stat_cat_entry_default.retrieve',
1189 method => 'actor_stat_cat_entry_default',
1192 sub actor_stat_cat_entry_default_ancestor {
1195 my $ou = ''.shift();
1196 my $sc = ''.shift();
1198 return undef unless ($ou);
1199 my $s_table = actor::stat_cat_entry_default->table;
1201 my $select = <<" SQL";
1204 JOIN actor.org_unit_ancestors(?) p ON (p.id = s.owner)
1208 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1209 $sth->execute($ou,$sc);
1211 my @sced = map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash;
1213 my $ancestor_sced = pop @sced;
1215 $client->respond( $ancestor_sced->to_fieldmapper ) if $ancestor_sced;
1219 __PACKAGE__->register_method(
1220 api_name => 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve',
1223 method => 'actor_stat_cat_entry_default_ancestor',