stray closing /TABLE in the no-ticket case
[freeside.git] / httemplate / search / cust_main-zip.html
1 <& 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                  'links'       => [ '', $link  ],
8 &>
9 <%init>
10
11 die "access denied"
12   unless $FS::CurrentUser::CurrentUser->access_right('List zip codes');
13
14 # XXX link to customers
15
16 my @where = ();
17
18 # select status
19
20 if ( $cgi->param('status') =~ /^(prospect|uncancel|active|susp|cancel)$/ ) {
21   my $method = $1.'_sql';
22   push @where, FS::cust_main->$method();
23 }
24
25 # select agent
26 # XXX this needs to be virtualized by agent too (like lots of stuff)
27
28 my $agentnum = '';
29 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
30   $agentnum = $1;
31   push @where, "cust_main.agentnum = $agentnum";
32 }
33
34 # select svcdb
35
36 if ( $cgi->param('svcdb') =~ /^(\w+)$/ ) {
37   my $svcdb = $1;
38   push @where, "EXISTS( SELECT 1 FROM $svcdb LEFT JOIN cust_svc USING ( svcnum )
39                                              LEFT JOIN cust_pkg USING ( pkgnum )
40                           WHERE cust_pkg.custnum = cust_main.custnum
41                       )";
42 }
43
44 my $where = scalar(@where) ? 'WHERE '. join(' AND ', @where) : '';
45
46 # bill zip vs ship zip
47
48 sub fieldorempty {
49   my $field = shift;
50   "CASE WHEN $field IS NULL THEN '' ELSE $field END";
51 }
52
53 sub strip_plus4 {
54   my $field = shift;
55   "CASE WHEN $field is NULL
56     THEN ''
57     ELSE CASE WHEN $field LIKE '_____-____'
58            THEN SUBSTRING($field FROM 1 FOR 5)
59            ELSE $field
60          END
61   END";
62 }
63
64 $cgi->param('column') =~ /^(bill|ship)$/;
65 my $location = $1 || 'bill';
66 $location .= '_locationnum';
67
68 my $zip;
69 if ( $cgi->param('ignore_plus4') ) {
70   $zip = strip_plus4('cust_location.zip');
71 } else {
72   $zip = fieldorempty('cust_location.zip');
73 }
74
75 # construct the queries and send 'em off
76
77 my $join = "JOIN cust_location ON (cust_main.$location = cust_location.locationnum)";
78
79 my $sql_query = 
80   "SELECT $zip AS zipcode,
81           COUNT(*) AS num_cust
82      FROM cust_main
83      $join
84      $where
85      GROUP BY zipcode
86      ORDER BY num_cust DESC, $zip ASC
87   ";
88
89 my $count_sql = 
90   "SELECT COUNT(DISTINCT cust_location.zip)
91     FROM cust_main $join $where";
92
93 my $link = [ $p.'search/cust_main.html?zip=', 
94              sub { $_[0]->[0] } ];
95
96 </%init>