add customer status column to customer & most other reports. also put the C in ACL...
[freeside.git] / httemplate / search / report_receivables.cgi
1 <% include( 'elements/search.html',
2                  'title'       => 'Accounts Receivable Aging Summary',
3                  'name'        => 'customers',
4                  'query'       => $sql_query,
5                  'count_query' => $count_sql,
6                  'header'      => [
7                                     FS::UI::Web::cust_header(),
8                                     #'Status', # (me)',
9                                     #'Status', # (cust_main)',
10                                     '0-30',
11                                     '30-60',
12                                     '60-90',
13                                     '90+',
14                                     'Total',
15                                   ],
16                  'footer'      => [
17                                     'Total',
18                                     ( map '',
19                                           ( 1 .. 
20                                             scalar(FS::UI::Web::cust_header()-1)
21                                           )
22                                     ),
23                                     #'',
24                                     #'',
25                                     sprintf( $money_char.'%.2f',
26                                              $row->{'owed_0_30'} ),
27                                     sprintf( $money_char.'%.2f',
28                                              $row->{'owed_30_60'} ),
29                                     sprintf( $money_char.'%.2f',
30                                              $row->{'owed_60_90'} ),
31                                     sprintf( $money_char.'%.2f',
32                                              $row->{'owed_90_0'} ),
33                                     sprintf( '<b>'. $money_char.'%.2f'. '</b>',
34                                              $row->{'owed_0_0'} ),
35                                   ],
36                  'fields'      => [
37                                     \&FS::UI::Web::cust_fields,
38                                     #sub { ( &{$status_statuscol}(shift) )[0] },
39                                     #sub { ucfirst(shift->status) },
40                                     sub { sprintf( $money_char.'%.2f',
41                                                    shift->get('owed_0_30') ) },
42                                     sub { sprintf( $money_char.'%.2f',
43                                                    shift->get('owed_30_60') ) },
44                                     sub { sprintf( $money_char.'%.2f',
45                                                    shift->get('owed_60_90') ) },
46                                     sub { sprintf( $money_char.'%.2f',
47                                                    shift->get('owed_90_0') ) },
48                                     sub { sprintf( $money_char.'%.2f',
49                                                    shift->get('owed_0_0') ) },
50                                   ],
51                  'links'       => [
52                                     ( map { $_ ne 'Cust. Status' ? $clink : '' }
53                                           FS::UI::Web::cust_header()
54                                     ),
55                                     #'',
56                                     #'',
57                                     '',
58                                     '',
59                                     '',
60                                     '',
61                                     '',
62                                   ],
63                  #'align'       => 'rlccrrrrr',
64                  'align'       => $align,
65                  #'size'        => [ '', '', '-1', '-1', '', '', '', '',  '', ],
66                  #'style'       => [ '', '',  'b',  'b', '', '', '', '', 'b', ],
67                  'size'        => [ ( map '', FS::UI::Web::cust_header() ),
68                                     #'-1', '', '', '', '',  '', ],
69                                     '', '', '', '',  '', ],
70                  'style'       => [ FS::UI::Web::cust_styles(),
71                                     #'b', '', '', '', '', 'b', ],
72                                     '', '', '', '', 'b', ],
73                  'color'       => [
74                                     FS::UI::Web::cust_colors(),
75                                     #sub { ( &{$status_statuscol}(shift) )[1] },
76                                     #sub { shift->statuscolor; },
77                                     '',
78                                     '',
79                                     '',
80                                     '',
81                                     '',
82                                   ],
83
84              )
85 %>
86 <%init>
87
88 die "access denied"
89   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
90
91 sub owed {
92   my($start, $end, %opt) = @_;
93
94   my @where = ();
95
96   #handle start and end ranges
97
98   #24h * 60m * 60s
99   push @where, "cust_bill._date <= extract(epoch from now())-".
100                ($start * 86400)
101     if $start;
102
103   push @where, "cust_bill._date > extract(epoch from now()) - ".
104                ($end * 86400)
105     if $end;
106
107   #handle 'cust' option
108
109   push @where, "cust_main.custnum = cust_bill.custnum"
110     if $opt{'cust'};
111
112   #handle 'agentnum' option
113   my $join = '';
114   if ( $opt{'agentnum'} ) {
115     $join = 'LEFT JOIN cust_main USING ( custnum )';
116     push @where, "agentnum = '$opt{'agentnum'}'";
117   }
118
119   my $where = scalar(@where) ? 'WHERE '.join(' AND ', @where) : '';
120
121   my $as = $opt{'noas'} ? '' : "as owed_${start}_$end";
122
123   my $charged = <<END;
124 sum( charged
125      - coalesce(
126          ( select sum(amount) from cust_bill_pay
127            where cust_bill.invnum = cust_bill_pay.invnum )
128          ,0
129        )
130      - coalesce(
131          ( select sum(amount) from cust_credit_bill
132            where cust_bill.invnum = cust_credit_bill.invnum )
133          ,0
134        )
135
136    )
137 END
138
139   "coalesce( ( select $charged from cust_bill $join $where ) ,0 ) $as";
140
141 }
142
143 my @ranges = (
144   [  0, 30 ],
145   [ 30, 60 ],
146   [ 60, 90 ],
147   [ 90,  0 ],
148   [  0,  0 ],
149 );
150
151 my $owed_cols = join(',', map owed( @$_, 'cust'=>1 ), @ranges );
152
153 my $select_count_pkgs = FS::cust_main->select_count_pkgs_sql;
154
155 my $active_sql    = FS::cust_pkg->active_sql;
156 my $inactive_sql  = FS::cust_pkg->inactive_sql;
157 my $suspended_sql = FS::cust_pkg->suspended_sql;
158 my $cancelled_sql = FS::cust_pkg->cancelled_sql;
159
160 my $packages_cols = <<END;
161      ( $select_count_pkgs                    ) AS num_pkgs_sql,
162      ( $select_count_pkgs AND $active_sql    ) AS active_pkgs,
163      ( $select_count_pkgs AND $inactive_sql  ) AS inactive_pkgs,
164      ( $select_count_pkgs AND $suspended_sql ) AS suspended_pkgs,
165      ( $select_count_pkgs AND $cancelled_sql ) AS cancelled_pkgs
166 END
167
168 my $where = "where ". owed(0, 0, 'cust'=>1, 'noas'=>1). " > 0";
169
170 my $agentnum = '';
171 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
172   $agentnum = $1;
173   $where .= " AND agentnum = '$agentnum' ";
174 }
175
176 #here is the agent virtualization
177 $where .= ' AND '. $FS::CurrentUser::CurrentUser->agentnums_sql;
178
179 my $count_sql = "select count(*) from cust_main $where";
180
181 my $sql_query = {
182   'table'     => 'cust_main',
183   'hashref'   => {},
184   'select'    => "*, $owed_cols, $packages_cols",
185   'extra_sql' => "$where order by coalesce(lower(company), ''), lower(last)",
186 };
187
188 my $total_sql = "select ".
189                   join(',', map owed( @$_, 'agentnum'=>$agentnum ), @ranges );
190
191 my $total_sth = dbh->prepare($total_sql) or die dbh->errstr;
192 $total_sth->execute or die "error executing $total_sql: ". $total_sth->errstr;
193 my $row = $total_sth->fetchrow_hashref();
194
195 my $conf = new FS::Conf;
196 my $money_char = $conf->config('money_char') || '$';
197
198 #my $align = join('', map { /#/ ? 'r' : 'l' } FS::UI::Web::cust_header() ).
199 #           'crrrrr';
200 my $align = FS::UI::Web::cust_aligns().
201            'rrrrr';
202
203 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
204
205 my $status_statuscol = sub {
206   #conceptual false laziness with cust_main::status...
207   my $row = shift;
208
209   my $status = 'unknown';
210   if ( $row->num_pkgs_sql == 0 ) {
211     $status = 'prospect';
212   } elsif ( $row->active_pkgs    > 0 ) {
213     $status = 'active';
214   } elsif ( $row->inactive_pkgs  > 0 ) {
215     $status = 'inactive';
216   } elsif ( $row->suspended_pkgs > 0 ) {
217     $status = 'suspended';
218   } elsif ( $row->cancelled_pkgs > 0 ) {
219     $status = 'cancelled'
220   }
221
222   ( ucfirst($status), $FS::cust_main::statuscolor{$status} );
223 };
224
225 </%init>