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