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 # Check if a set of hours of operation are completely closed.
372 for (my $dow = 0; $dow < 7; $dow++)
375 my $dow_open_meth = "dow_".$dow."_open";
376 my $dow_close_meth = "dow_".$dow."_close";
377 if ($hoo->$dow_open_meth != "00:00:00" || $hoo->$dow_close_meth != "00:00:00")
384 # Recursive method with two parts: first is checking the closures and second is checking the hours of operation
385 # Direction means whether to check forwards or backwards on the next call. Negative 1 is backwards, positive 1 is forwards - 0 means to check both, backwards then forwards
386 # Recursion terminates when returning undefined - this means stop changing the start and end times instead of meaning exit with an error.
387 sub org_closed_overlap {
392 my $direction = shift || 0;
393 my $no_hoo = shift || 0;
395 return undef unless ($date && $ou);
398 my $t = actor::org_unit::closed_date->table;
402 WHERE ? between close_start and close_end
404 ORDER BY close_start ASC, close_end DESC
408 $date = clean_ISO8601($date);
409 my ($begin, $end) = ($date,$date);
411 my $hoo = actor::org_unit::hours_of_operation->retrieve($ou);
413 # This block checks only the closures - does not consider the hours of operation. That's the next block
414 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $date, $ou )) {
415 $begin = clean_ISO8601($closure->{close_start});
416 $end = clean_ISO8601($closure->{close_end});
418 if ( $direction <= 0 ) {
419 $before = $_dt_parser->parse_datetime( $begin );
420 $before->subtract( minutes => 1 );
422 while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1, 1 ) ) {
423 $before = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
425 $begin = clean_ISO8601($before->strftime('%FT%T%z'));
428 if ( $direction >= 0 ) {
429 $after = $_dt_parser->parse_datetime( $end );
430 $after->add( minutes => 1 );
432 while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1, 1 ) ) {
433 $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
435 $end = clean_ISO8601($after->strftime('%FT%T%z'));
439 #This block checks if the org unit's hours are open or not at the given time. If they are, it checks closures.
441 #Making sure to ignore this and take the only closure hours from the first block if all hours are closed
442 if ( $hoo && !are_all_closed($hoo)) {
445 if ( $direction <= 0 ) {
446 my $begin_dow = $_dt_parser->parse_datetime( $begin )->day_of_week_0;
447 my $begin_open_meth = "dow_".$begin_dow."_open";
448 my $begin_close_meth = "dow_".$begin_dow."_close";
451 while ($hoo->$begin_open_meth eq '00:00:00' and $hoo->$begin_close_meth eq '00:00:00') {
452 $begin = clean_ISO8601($_dt_parser->parse_datetime( $begin )->subtract( days => 1)->strftime('%FT%T%z'));
456 last if ($count > 6);
457 $begin_open_meth = "dow_".$begin_dow."_open";
458 $begin_close_meth = "dow_".$begin_dow."_close";
461 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $begin, $ou )) {
462 $before = $_dt_parser->parse_datetime( $begin );
463 $before->subtract( minutes => 1 );
464 while ( my $_b = org_closed_overlap($self, $client, $ou, $before->strftime('%FT%T%z'), -1 ) ) {
465 $before = $_dt_parser->parse_datetime( clean_ISO8601($_b->{start}) );
470 if ( $direction >= 0 ) {
471 my $end_dow = $_dt_parser->parse_datetime( $end )->day_of_week_0;
472 my $end_open_meth = "dow_".$end_dow."_open";
473 my $end_close_meth = "dow_".$end_dow."_close";
476 while ($hoo->$end_open_meth eq '00:00:00' and $hoo->$end_close_meth eq '00:00:00') {
477 $end = clean_ISO8601($_dt_parser->parse_datetime( $end )->add( days => 1)->strftime('%FT%T%z'));
481 last if ($count > 6);
482 $end_open_meth = "dow_".$end_dow."_open";
483 $end_close_meth = "dow_".$end_dow."_close";
486 if (my $closure = actor::org_unit::closed_date->db_Main->selectrow_hashref( $sql, {}, $end, $ou )) {
487 $after = $_dt_parser->parse_datetime( $end );
488 $after->add( minutes => 1 );
490 while ( my $_a = org_closed_overlap($self, $client, $ou, $after->strftime('%FT%T%z'), 1 ) ) {
491 $after = $_dt_parser->parse_datetime( clean_ISO8601($_a->{end}) );
493 $end = clean_ISO8601($after->strftime('%FT%T%z'));
500 # If there were no changes made to the given date that means no further action should be taken - you've arrived at an acceptable date
501 if ($begin eq $date && $end eq $date) {
505 return { start => $begin, end => $end };
507 __PACKAGE__->register_method(
508 api_name => 'open-ils.storage.actor.org_unit.closed_date.overlap',
510 method => 'org_closed_overlap',
513 sub user_by_barcode {
516 my @barcodes = shift;
518 return undef unless @barcodes;
520 for my $card ( actor::card->search( { barcode => @barcodes } ) ) {
522 if (@barcodes == 1) {
523 return $card->usr->to_fieldmapper;
525 $client->respond( $card->usr->to_fieldmapper);
529 __PACKAGE__->register_method(
530 api_name => 'open-ils.storage.direct.actor.user.search.barcode',
532 method => 'user_by_barcode',
541 my $c = actor::card->table;
542 my $p = actor::user->table;
544 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.card <> c.id";
546 my $list = actor::user->db_Main->selectcol_arrayref($sql);
547 for my $bc ( @$list ) {
548 $client->respond($bc);
552 __PACKAGE__->register_method(
553 api_name => 'open-ils.storage.actor.user.lost_barcodes',
556 method => 'lost_barcodes',
557 signature => <<' NOTE',
558 Returns an array of barcodes that belong to lost cards.
559 @return array of barcodes
563 sub expired_barcodes {
567 my $c = actor::card->table;
568 my $p = actor::user->table;
570 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.expire_date < CURRENT_DATE";
572 my $list = actor::user->db_Main->selectcol_arrayref($sql);
573 for my $bc ( @$list ) {
574 $client->respond($bc);
578 __PACKAGE__->register_method(
579 api_name => 'open-ils.storage.actor.user.expired_barcodes',
582 method => 'expired_barcodes',
583 signature => <<' NOTE',
584 Returns an array of barcodes that are currently expired.
585 @return array of barcodes
589 sub barred_barcodes {
593 my $c = actor::card->table;
594 my $p = actor::user->table;
596 my $sql = "SELECT c.barcode FROM $c c JOIN $p p ON (c.usr = p.id) WHERE p.barred IS TRUE";
598 my $list = actor::user->db_Main->selectcol_arrayref($sql);
599 for my $bc ( @$list ) {
600 $client->respond($bc);
604 __PACKAGE__->register_method(
605 api_name => 'open-ils.storage.actor.user.barred_barcodes',
608 method => 'barred_barcodes',
609 signature => <<' NOTE',
610 Returns an array of barcodes that are currently barred.
611 @return array of barcodes
615 sub penalized_barcodes {
619 my $c = actor::card->table;
620 my $p = actor::user_standing_penalty->table;
623 SELECT DISTINCT c.barcode
625 JOIN $p p USING (usr)
626 JOIN config.standing_penalty csp ON (csp.id = p.standing_penalty)
627 WHERE csp.block_list IS NOT NULL
628 AND p.set_date < CURRENT_DATE
629 AND (p.stop_date IS NULL OR p.stop_date > CURRENT_DATE);
632 my $list = actor::user->db_Main->selectcol_arrayref($sql);
633 for my $bc ( @$list ) {
634 $client->respond($bc);
638 __PACKAGE__->register_method(
639 api_name => 'open-ils.storage.actor.user.penalized_barcodes',
642 method => 'penalized_barcodes',
643 signature => <<' NOTE',
644 Returns an array of barcodes that have blocking penalties.
645 @return array of barcodes
649 sub _prepare_name_argument {
650 # Get rid of extra spaces, accents, and regex characters
651 my ($search) = _clean_regex_chars(@_);
652 my $sth = actor::user->db_Main->prepare_cached("SELECT evergreen.unaccent_and_squash(?)");
653 $sth->execute($search);
655 return ($r && @$r) ? $r->[0] : $search;
658 sub _clean_regex_chars {
661 # Escape metacharacters for SIMILAR TO
662 # (http://www.postgresql.org/docs/8.4/interactive/functions-matching.html)
663 $search =~ s/\_/\\_/g;
664 $search =~ s/\%/\\%/g;
665 $search =~ s/\|/\\|/g;
666 $search =~ s/\*/\\*/g;
667 $search =~ s/\+/\\+/g;
668 $search =~ s/\[/\\[/g;
669 $search =~ s/\]/\\]/g;
670 $search =~ s/\(/\\(/g;
671 $search =~ s/\)/\\)/g;
680 my $limit = shift || 1000;
682 my $inactive = shift;
684 my $search_org = shift || $ws_ou;
685 my $opt_boundary = shift || 0;
686 my $offset = shift || 0;
688 my $penalty_sort = 0;
690 my $strict_opt_in = OpenSRF::Utils::SettingsClient->new->config_value( share => user => 'opt_in' );
692 $sort = ['family_name','first_given_name'] unless ($$sort[0]);
695 if ($$sort[0] eq 'penalties') {
702 # group 2 = phone, ident
707 # Treatment of name fields depends on whether the org has
708 # diacritic_insensitivity turned on or off.
710 my $diacritic_insensitive = $U->ou_ancestor_setting_value($ws_ou, 'circ.patron_search.diacritic_insensitive');
711 # Parse from JSON to Perl boolean (1|0):
712 $diacritic_insensitive = ($diacritic_insensitive) ? $JSON->JSON2perl($diacritic_insensitive) : 0;
718 # Compile the WHERE component of the actor.usr fields.
719 # When a name field is encountered, search both the name field and
720 # the alternate version of the name field.
721 my @name_fields = qw/prefix first_given_name second_given_name family_name suffix/;
724 my @usr_fields = grep { ''.$$search{$_}{group} eq '0' } keys %$search;
725 for my $usr_field (@usr_fields) {
728 my $where_func = $diacritic_insensitive ?
729 "evergreen.unaccent_and_squash(CAST(%s AS text)) ~ ?" :
730 "evergreen.lowercase(CAST(%s AS text)) ~ ?";
732 my $val = $diacritic_insensitive ?
733 "^" . _prepare_name_argument($$search{$usr_field}{value}) :
734 "^" . _clean_regex_chars($$search{$usr_field}{value});
736 if (grep {$_ eq $usr_field} @name_fields) {
737 # When searching a name field include an OR search
738 # on the alternate version of the same field.
740 push(@usr_where_parts, sprintf(
741 "($where_func OR $where_func)", $usr_field, "pref_$usr_field")
744 # search main field and alt name field with same value.
750 push(@usr_where_parts, sprintf($where_func, $usr_field));
755 $usr = join ' AND ', @usr_where_parts;
757 while (($key, $value) = each (%$search)) {
758 if($$search{$key}{group} eq '4') {
761 my $right = "RIGHT('0'|| ";
763 $end = $right = '' if lc $tval eq 'year';
764 $dob .= $right."CAST(DATE_PART('$tval', dob) AS text)$end ~ ? AND ";
767 # Trim the last " AND "
768 $dob = substr($dob,0,-4);
769 @dobv = map { _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '4' } keys %$search;
770 $usr .= ' AND ' if ( $usr && $dob );
771 $usr .= $dob if $dob; # $dob not in-line above in case $usr doesn't have any search vals (only searched for dob)
772 push(@usrv, @dobv) if @dobv;
774 my $addr = join ' AND ', map { "evergreen.lowercase(CAST($_ AS text)) ~ ?" } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
775 my @addrv = map { "^" . _clean_regex_chars($$search{$_}{value}) } grep { ''.$$search{$_}{group} eq '1' } keys %$search;
777 # should only be 1 profile sent but this construction makes dealing with the lists simpler.
778 my ($prof) = map { $$search{$_}{value} } grep {''.$$search{$_}{group} eq '5' } keys %$search;
779 $prof = int($prof) if $prof; # int or out
781 my $pv = _clean_regex_chars($$search{phone}{value});
782 my $iv = _clean_regex_chars($$search{ident}{value});
783 my $nv = _clean_regex_chars($$search{name}{value});
784 my $cv = _clean_regex_chars($$search{card}{value});
788 $card = 'JOIN (SELECT DISTINCT usr FROM actor.card WHERE evergreen.lowercase(barcode) LIKE ?||\'%\') AS card ON (card.usr = users.id)';
796 for my $p ( qw/day_phone evening_phone other_phone/ ) {
797 if ($pv =~ /^\d+$/) {
798 push @ps, "evergreen.lowercase(REGEXP_REPLACE($p, '[^0-9]', '', 'g')) ~ ?";
800 push @ps, "evergreen.lowercase($p) ~ ?";
802 push @phonev, "^$pv";
804 $phone = '(' . join(' OR ', @ps) . ')';
811 for my $i ( qw/ident_value ident_value2/ ) {
812 push @is, "evergreen.lowercase($i) ~ ?";
813 push @identv, "^$iv";
815 $ident = '(' . join(' OR ', @is) . ')';
818 # name keywords search
823 $name = "name_kw_tsvector @@ to_tsquery(?)";
825 # Remove characters that to_tsquery might treat as operators.
826 # Note using plainto_tsquery to ignore operators won't let us
827 # also do prefix matching.
828 $nv =~ s/[^\w\s\.\-']//g;
830 my @parts = split(' ', $nv);
832 # tsquery on multiple names joined w/ '&'
833 # Adding :* gives us prefix matching
834 push @namev, join(' & ', map { "$_:*" } @parts);
840 $profile = '(profile IN (SELECT id FROM permission.grp_descendants(?)))';
843 my $usr_where = join ' AND ', grep { $_ } ($usr,$phone,$ident,$name,$profile);
844 my $addr_where = $addr;
847 my $u_table = actor::user->table;
848 my $a_table = actor::user_address->table;
849 my $opt_in_table = actor::usr_org_unit_opt_in->table;
850 my $ou_table = actor::org_unit->table;
852 my $u_select = "SELECT id as id FROM $u_table u WHERE $usr_where";
853 my $a_select = "SELECT u.id as id FROM $a_table a JOIN $u_table u ON (u.mailing_address = a.id OR u.billing_address = a.id) WHERE $addr_where";
855 my $clone_select = '';
857 #$clone_select = "JOIN (SELECT cu.id as id FROM $a_table ca ".
858 # "JOIN $u_table cu ON (cu.mailing_address = ca.id OR cu.billing_address = ca.id) ".
859 # "WHERE $addr_where) AS clone ON (clone.id = users.id)" if ($addr_where);
864 $select = "$u_select INTERSECT $a_select";
868 } elsif ($addr_where) {
869 $select = "$a_select";
872 return undef if (!$select && !$card);
874 my $order_by = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text)) ' . (split / /,$_)[1] } @$sort;
875 my $distinct_list = join ', ', map { 'evergreen.lowercase(CAST(users.'. (split / /,$_)[0] . ' AS text))' } @$sort;
876 my $group_list = $distinct_list;
881 $inactive = 'AND users.active = TRUE';
884 if (!$ws_ou) { # XXX This should be required!!
885 $ws_ou = actor::org_unit->search( { parent_ou => undef } )->next->id;
888 my $descendants = "actor.org_unit_descendants($search_org)";
890 my $opt_in_where = '';
891 if (lc($strict_opt_in) eq 'true') {
892 $opt_in_where = "AND (";
893 $opt_in_where .= "EXISTS (select id FROM $opt_in_table ";
894 $opt_in_where .= " WHERE org_unit in (select (actor.org_unit_ancestors($ws_ou)).id)";
895 $opt_in_where .= " AND usr = users.id) ";
896 $opt_in_where .= "OR";
897 $opt_in_where .= " users.home_ou IN (select (actor.org_unit_descendants($ws_ou,$opt_boundary)).id))";
900 my $penalty_join = '';
902 $distinct_list = 'COUNT(penalties.id), ' . $distinct_list;
903 $order_by = 'COUNT(penalties.id) DESC, ' . $order_by;
904 unshift @$sort, 'COUNT(penalties.id)';
905 $penalty_join = <<" SQL";
906 LEFT JOIN actor.usr_standing_penalty penalties
907 ON (users.id = penalties.usr AND (penalties.stop_date IS NULL OR penalties.stop_date > NOW()))
911 $select = "JOIN ($select) AS search ON (search.id = users.id)" if ($select);
913 SELECT $distinct_list
914 FROM $u_table AS users $card
915 JOIN $descendants d ON (d.id = users.home_ou)
919 WHERE users.deleted = FALSE
928 return actor::user->db_Main->selectcol_arrayref($select, {Columns=>[scalar(@$sort)]}, map {lc($_)} (@usrv,@phonev,@identv,@namev,@profv,@addrv));
930 __PACKAGE__->register_method(
931 api_name => 'open-ils.storage.actor.user.crazy_search',
933 method => 'patron_search',
940 my $select =<<" SQL";
943 ORDER BY CASE WHEN parent_ou IS NULL THEN 0 ELSE 1 END, name;
946 my $sth = actor::org_unit->db_Main->prepare_cached($select);
949 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
953 __PACKAGE__->register_method(
954 api_name => 'open-ils.storage.direct.actor.org_unit.retrieve.all',
957 method => 'org_unit_list',
960 sub org_unit_type_list {
964 my $select =<<" SQL";
966 FROM actor.org_unit_type
967 ORDER BY depth, name;
970 my $sth = actor::org_unit_type->db_Main->prepare_cached($select);
973 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit_type->construct($_) } $sth->fetchall_hash );
977 __PACKAGE__->register_method(
978 api_name => 'open-ils.storage.direct.actor.org_unit_type.retrieve.all',
981 method => 'org_unit_type_list',
984 sub org_unit_full_path {
989 return undef unless (@binds);
991 my $func = 'actor.org_unit_full_path(?)';
992 $func = 'actor.org_unit_full_path(?,?)' if (@binds > 1);
994 my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
995 $sth->execute(@binds);
997 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1001 __PACKAGE__->register_method(
1002 api_name => 'open-ils.storage.actor.org_unit.full_path',
1005 method => 'org_unit_full_path',
1008 sub org_unit_ancestors {
1013 return undef unless ($id);
1015 my $func = 'actor.org_unit_ancestors(?)';
1017 my $sth = actor::org_unit->db_Main->prepare_cached(<<" SQL");
1020 JOIN actor.org_unit_type t ON (f.ou_type = t.id)
1021 ORDER BY t.depth, f.name;
1023 $sth->execute(''.$id);
1025 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1029 __PACKAGE__->register_method(
1030 api_name => 'open-ils.storage.actor.org_unit.ancestors',
1033 method => 'org_unit_ancestors',
1036 sub org_unit_descendants {
1042 return undef unless ($id);
1044 my $func = 'actor.org_unit_descendants(?)';
1045 if (defined $depth) {
1046 $func = 'actor.org_unit_descendants(?,?)';
1049 my $sth = actor::org_unit->db_Main->prepare_cached("SELECT * FROM $func");
1050 $sth->execute(''.$id, ''.$depth) if (defined $depth);
1051 $sth->execute(''.$id) unless (defined $depth);
1053 $client->respond( $_->to_fieldmapper ) for ( map { actor::org_unit->construct($_) } $sth->fetchall_hash );
1057 __PACKAGE__->register_method(
1058 api_name => 'open-ils.storage.actor.org_unit.descendants',
1061 method => 'org_unit_descendants',
1064 sub fleshed_actor_stat_cat {
1069 @list = ($list[0]) unless ($self->api_name =~ /batch/o);
1071 for my $sc (@list) {
1072 my $cat = actor::stat_cat->retrieve($sc);
1075 my $sc_fm = $cat->to_fieldmapper;
1076 $sc_fm->entries( [ map { $_->to_fieldmapper } $cat->entries ] );
1077 $sc_fm->default_entries( [ map { $_->to_fieldmapper } $cat->default_entries ] );
1079 $client->respond( $sc_fm );
1085 __PACKAGE__->register_method(
1086 api_name => 'open-ils.storage.fleshed.actor.stat_cat.retrieve',
1089 method => 'fleshed_actor_stat_cat',
1092 __PACKAGE__->register_method(
1093 api_name => 'open-ils.storage.fleshed.actor.stat_cat.retrieve.batch',
1097 method => 'fleshed_actor_stat_cat',
1100 #XXX Fix stored proc calls
1101 sub ranged_actor_stat_cat_all {
1104 my $ou = ''.shift();
1106 return undef unless ($ou);
1107 my $s_table = actor::stat_cat->table;
1109 my $select = <<" SQL";
1112 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1117 $fleshed = 1 if ($self->api_name =~ /fleshed/o);
1119 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1122 for my $sc ( map { actor::stat_cat->construct($_) } $sth->fetchall_hash ) {
1123 my $sc_fm = $sc->to_fieldmapper;
1125 [ $self->method_lookup( 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat' )->run($ou,$sc->id) ]
1127 $sc_fm->default_entries(
1128 [ $self->method_lookup( 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve' )->run($ou,$sc->id) ]
1130 $client->respond( $sc_fm );
1135 __PACKAGE__->register_method(
1136 api_name => 'open-ils.storage.ranged.fleshed.actor.stat_cat.all',
1140 method => 'ranged_actor_stat_cat_all',
1143 __PACKAGE__->register_method(
1144 api_name => 'open-ils.storage.ranged.actor.stat_cat.all',
1148 method => 'ranged_actor_stat_cat_all',
1151 #XXX Fix stored proc calls
1152 sub ranged_actor_stat_cat_entry {
1155 my $ou = ''.shift();
1156 my $sc = ''.shift();
1158 return undef unless ($ou);
1159 my $s_table = actor::stat_cat_entry->table;
1161 my $select = <<" SQL";
1164 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
1169 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1170 $sth->execute($ou,$sc);
1172 for my $sce ( map { actor::stat_cat_entry->construct($_) } $sth->fetchall_hash ) {
1173 my $sce_fm = $sce->to_fieldmapper;
1174 $client->respond( $sce_fm );
1179 __PACKAGE__->register_method(
1180 api_name => 'open-ils.storage.ranged.actor.stat_cat_entry.search.stat_cat',
1183 method => 'ranged_actor_stat_cat_entry',
1186 sub actor_stat_cat_entry_default {
1189 my $ou = ''.shift();
1190 my $sc = ''.shift();
1192 return undef unless ($ou);
1193 my $s_table = actor::stat_cat_entry_default->table;
1195 my $select = <<" SQL";
1198 WHERE owner = ? AND stat_cat = ?
1201 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1202 $sth->execute($ou,$sc);
1204 for my $sced ( map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash ) {
1205 $client->respond( $sced->to_fieldmapper );
1210 __PACKAGE__->register_method(
1211 api_name => 'open-ils.storage.actor.stat_cat_entry_default.retrieve',
1214 method => 'actor_stat_cat_entry_default',
1217 sub actor_stat_cat_entry_default_ancestor {
1220 my $ou = ''.shift();
1221 my $sc = ''.shift();
1223 return undef unless ($ou);
1224 my $s_table = actor::stat_cat_entry_default->table;
1226 my $select = <<" SQL";
1229 JOIN actor.org_unit_ancestors(?) p ON (p.id = s.owner)
1233 my $sth = actor::stat_cat->db_Main->prepare_cached($select);
1234 $sth->execute($ou,$sc);
1236 my @sced = map { actor::stat_cat_entry_default->construct($_) } $sth->fetchall_hash;
1238 my $ancestor_sced = pop @sced;
1240 $client->respond( $ancestor_sced->to_fieldmapper ) if $ancestor_sced;
1244 __PACKAGE__->register_method(
1245 api_name => 'open-ils.storage.actor.stat_cat_entry_default.ancestor.retrieve',
1248 method => 'actor_stat_cat_entry_default_ancestor',