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