This commit was generated by cvs2svn to compensate for changes in r8593,
[freeside.git] / httemplate / search / cust_main-zip.html
1 <% include( 'elements/search.html',
2                  'title'       => 'Zip code Search Results',
3                  'name'        => 'zip codes',
4                  'query'       => $sql_query,
5                  'count_query' => $count_sql,
6                  'header'      => [ 'Zip code', 'Customers', ],
7                  #'fields'      => [ 'zip', 'num_cust', ],
8                  'links'       => [ '', sub { 'somewhere'; }  ],
9              )
10 %>
11 <%init>
12
13 die "access denied"
14   unless $FS::CurrentUser::CurrentUser->access_right('List zip codes');
15
16 # XXX link to customers
17
18 my @where = ();
19
20 # select status
21
22 if ( $cgi->param('status') =~ /^(prospect|uncancel|active|susp|cancel)$/ ) {
23   my $method = $1.'_sql';
24   push @where, FS::cust_main->$method();
25 }
26
27 # select agent
28 # XXX this needs to be virtualized by agent too (like lots of stuff)
29
30 my $agentnum = '';
31 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
32   $agentnum = $1;
33   push @where, "cust_main.agentnum = $agentnum";
34 }
35 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
36
37 # bill zip vs ship zip
38
39 sub fieldorempty {
40   my $field = shift;
41   "CASE WHEN $field IS NULL THEN '' ELSE $field END";
42 }
43
44 sub strip_plus4 {
45   my $field = shift;
46   "CASE WHEN $field is NULL
47     THEN ''
48     ELSE CASE WHEN $field LIKE '_____-____'
49            THEN SUBSTRING($field FROM 1 FOR 5)
50            ELSE $field
51          END
52   END";
53 }
54
55 my( $zip, $czip);
56 if ( $cgi->param('column') eq 'ship_zip' ) {
57
58   my $casewhen_noship =
59     "CASE WHEN ( ship_last IS NULL OR ship_last = '' ) THEN ";
60
61   $czip = "$casewhen_noship zip ELSE ship_zip END";
62
63   if ( $cgi->param('ignore_plus4') ) {
64     $zip = $casewhen_noship. strip_plus4('zip').
65                    " ELSE ". strip_plus4('ship_zip'). ' END';
66
67   } else {
68     $zip = $casewhen_noship. fieldorempty('zip').
69                    " ELSE ". fieldorempty('ship_zip'). ' END';
70   }
71
72 } else {
73
74   $czip = 'zip';
75
76   if ( $cgi->param('ignore_plus4') ) {
77     $zip = strip_plus4('zip');
78   } else {
79     $zip = fieldorempty('zip');
80   }
81
82 }
83
84 # construct the queries and send 'em off
85
86 my $sql_query = 
87   "SELECT $zip AS zipcode,
88           COUNT(*) AS num_cust
89      FROM cust_main
90      $where
91      GROUP BY zipcode
92      ORDER BY num_cust DESC
93   ";
94
95 my $count_sql = "select count(distinct $czip) from cust_main $where";
96
97 # XXX should link...
98
99 </%init>