Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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'      => [ 0, 1 ],
8                  'links'       => [ '', $link  ],
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
36 # select svcdb
37
38 if ( $cgi->param('svcdb') =~ /^(\w+)$/ ) {
39   my $svcdb = $1;
40   push @where, "EXISTS( SELECT 1 FROM $svcdb LEFT JOIN cust_svc USING ( svcnum )
41                                              LEFT JOIN cust_pkg USING ( pkgnum )
42                           WHERE cust_pkg.custnum = cust_main.custnum
43                       )";
44 }
45
46 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
47
48 # bill zip vs ship zip
49
50 sub fieldorempty {
51   my $field = shift;
52   "CASE WHEN $field IS NULL THEN '' ELSE $field END";
53 }
54
55 sub strip_plus4 {
56   my $field = shift;
57   "CASE WHEN $field is NULL
58     THEN ''
59     ELSE CASE WHEN $field LIKE '_____-____'
60            THEN SUBSTRING($field FROM 1 FOR 5)
61            ELSE $field
62          END
63   END";
64 }
65
66 $cgi->param('column') =~ /^(bill|ship)$/;
67 my $location = $1 || 'bill';
68 $location .= '_locationnum';
69
70 my $zip;
71 if ( $cgi->param('ignore_plus4') ) {
72   $zip = strip_plus4('cust_location.zip');
73 } else {
74   $zip = fieldorempty('cust_location.zip');
75 }
76
77 # construct the queries and send 'em off
78
79 my $join = "JOIN cust_location ON (cust_main.$location = cust_location.locationnum)";
80
81 my $sql_query = 
82   "SELECT $zip AS zipcode,
83           COUNT(*) AS num_cust
84      FROM cust_main
85      $join
86      $where
87      GROUP BY zipcode
88      ORDER BY num_cust DESC, $zip ASC
89   ";
90
91 my $count_sql = 
92   "SELECT COUNT(DISTINCT cust_location.zip)
93     FROM cust_main $join $where";
94
95 my $link = [ $p.'search/cust_main.html?zip=', 
96              sub { $_[0]->[0] } ];
97
98 </%init>