allow services with a tower but no sector to appear in search results, #33056
[freeside.git] / FS / FS / svc_Tower_Mixin.pm
1 package FS::svc_Tower_Mixin;
2
3 use strict;
4 use FS::Record qw(qsearchs); #qsearch;
5 use FS::tower_sector;
6
7 =item tower_sector
8
9 =cut
10
11 sub tower_sector {
12   my $self = shift;
13   return '' unless $self->sectornum;
14   qsearchs('tower_sector', { sectornum => $self->sectornum });
15 }
16
17 =item tower_sector_sql HASHREF
18
19 Class method which returns a list of WHERE clause fragments to 
20 search for services with tower/sector given by HASHREF.  Can 
21 contain 'towernum' and 'sectornum' keys, either of which can be 
22 an arrayref or a single value.  To use this, the search needs to
23 join to tower_sector.
24
25 towernum or sectornum can also contain 'none' to allow null values.
26
27 =cut
28
29 sub tower_sector_sql {
30   my( $class, $params ) = @_;
31   return () unless keys %$params;
32
33   my @where = ();
34   for my $field (qw(towernum sectornum)) {
35     my $value = $params->{$field} or next;
36     if ( ref $value and grep { $_ } @$value ) {
37       my $in = join(',', map { /^(\d+)$/ ? $1 : () } @$value);
38       my @orwhere;
39       push @orwhere, "tower_sector.$field IN ($in)" if $in;
40       if ( grep /^none$/, @$value ) {
41         # then allow this field to be null
42         push @orwhere, "tower_sector.$field IS NULL";
43         # and if this field is the sector, also allow the default sector
44         # on the tower
45         push @orwhere, "sectorname = '_default'" if $field eq 'sectornum';
46       }
47       push @where, '( '.join(' OR ', @orwhere).' )';
48     }
49     elsif ( $value =~ /^(\d+)$/ ) {
50       push @where, "tower_sector.$field = $1";
51     }
52     elsif ( $value eq 'none' ) {
53       push @where, "tower_sector.$field IS NULL";
54     }
55   }
56   @where;
57 }
58
59 1;