summaryrefslogtreecommitdiff
path: root/httemplate/search/cust_main-zip.html
blob: 56df924bc26bfe203bc2eb9d5a4a50c4323e3231 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<% include( 'elements/search.html',
                 'title'       => 'Zip code Search Results',
                 'name'        => 'zip codes',
                 'query'       => $sql_query,
                 'count_query' => $count_sql,
                 'header'      => [ 'Zip code', 'Customers', ],
                 #'fields'      => [ 'zip', 'num_cust', ],
                 'links'       => [ '', sub { 'somewhere'; }  ],
             )
%>
<%init>

die "access denied"
  unless $FS::CurrentUser::CurrentUser->access_right('List zip codes');

# XXX link to customers

my @where = ();

# select status

if ( $cgi->param('status') =~ /^(prospect|uncancel|active|susp|cancel)$/ ) {
  my $method = $1.'_sql';
  push @where, FS::cust_main->$method();
}

# select agent
# XXX this needs to be virtualized by agent too (like lots of stuff)

my $agentnum = '';
if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
  $agentnum = $1;
  push @where, "cust_main.agentnum = $agentnum";
}
my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';

# bill zip vs ship zip

sub fieldorempty {
  my $field = shift;
  "CASE WHEN $field IS NULL THEN '' ELSE $field END";
}

sub strip_plus4 {
  my $field = shift;
  "CASE WHEN $field is NULL
    THEN ''
    ELSE CASE WHEN $field LIKE '_____-____'
           THEN SUBSTRING($field FROM 1 FOR 5)
           ELSE $field
         END
  END";
}

my( $zip, $czip);
if ( $cgi->param('column') eq 'ship_zip' ) {

  my $casewhen_noship =
    "CASE WHEN ( ship_last IS NULL OR ship_last = '' ) THEN ";

  $czip = "$casewhen_noship zip ELSE ship_zip END";

  if ( $cgi->param('ignore_plus4') ) {
    $zip = $casewhen_noship. strip_plus4('zip').
                   " ELSE ". strip_plus4('ship_zip'). ' END';

  } else {
    $zip = $casewhen_noship. fieldorempty('zip').
                   " ELSE ". fieldorempty('ship_zip'). ' END';
  }

} else {

  $czip = 'zip';

  if ( $cgi->param('ignore_plus4') ) {
    $zip = strip_plus4('zip');
  } else {
    $zip = fieldorempty('zip');
  }

}

# construct the queries and send 'em off

my $sql_query = 
  "SELECT $zip AS zipcode,
          COUNT(*) AS num_cust
     FROM cust_main
     $where
     GROUP BY zipcode
     ORDER BY num_cust DESC
  ";

my $count_sql = "select count(distinct $czip) from cust_main $where";

# XXX should link...

</%init>