add customer class to A/R report, fix "(none)" selection in other reports, RT#22540
[freeside.git] / httemplate / search / cust_bill_pkg_referral.html
1 <& elements/search.html,
2   'title'       => emt('Sales with advertising source'),
3   'name'        => emt('line items'),
4   'query'       => $query,
5   'count_query' => $count_query,
6   'count_addl'  => [ 
7                      ($setup ? $money_char. '%.2f setup' : ()),
8                      ($recur ? $money_char. '%.2f recurring' : ()),
9                      ($usage ? $money_char. '%.2f usage' : ()),
10                    ],
11   'header'      => [
12     emt('Description'),
13     ($setup ? emt('Setup') : ()),
14     ($recur ? emt('Recurring') : ()),
15     ($usage ? emt('Usage') : ()),
16     emt('Invoice'),
17     emt('Invoice date'),
18     emt('Paid'),
19     emt('Payment date'),
20     emt('Pkg. status'),
21     emt('Pkg. class'),
22     '', #report class
23     emt('Cust#'),
24     emt('Customer'),
25     emt('Ad source'),
26     emt('Agent'),
27   ],
28   'fields'      => [
29     'pkg',
30     ($setup ? money_sub('setup') : ()),
31     ($recur ? money_sub('recur_no_usage') : ()),
32     ($usage ? money_sub('recur_usage') : ()),
33     'invnum',
34     date_sub('_date'),
35     money_sub('paid'),
36     date_sub('last_pay'),
37     sub {
38       my $cust_pkg = shift->cust_pkg;
39       $cust_pkg ? ucfirst($cust_pkg->status) : '';
40     },
41     'classname',
42     sub { # report_option
43       my $cust_bill_pkg = shift;
44       my $pkgpart = $cust_bill_pkg->pkgpart_override
45                  || $cust_bill_pkg->cust_pkg->pkgpart;
46       if ( !exists($report_classes{$pkgpart}) ) {
47         my $part_pkg = FS::part_pkg->by_key($pkgpart);
48         my %opts = $part_pkg->options;
49         $report_classes{$pkgpart} = [
50           map { /^report_option_(\d+)/ ? 
51                 $report_option_name{$1} :
52                 () }
53           keys %opts
54         ];
55       }
56       join( '<BR>', @{ $report_classes{$pkgpart} });
57     },
58     'custnum',
59     'name',
60     'referral', # from query
61     'agent',
62   ],
63   'sort_fields' => [
64     '',
65     ($setup ? 'setup' : ()),
66     ($recur ? 'recur_no_usage' : ()),
67     ($usage ? 'recur_usage' : ()),
68     'invnum',
69     '_date',
70     'paid',
71     'last_pay',
72     '', #package status
73     'classname',
74     '', #report_option
75     'custnum',
76     '',
77     'referral',
78     'agent',
79   ],
80   'links'       => [
81     '', #package/item desc
82     ('') x $x, #setup/recur/usage
83     $ilink, #invnum
84     $ilink, #invoice date
85     '', #paid amt
86     '', #payment date
87     '', #pkg status
88     '', #classnum
89     '', #report class
90     $clink, #custnum
91     $clink, #customer name
92     '', #referral
93     '', #agent
94   ],
95   #'align' => 'rlrrrc'.FS::UI::Web::cust_aligns(),
96   'align' => 'l' . ('r' x $x) . 'rcrccccrlll',
97   'color' => [ ('') x (5 + $x),
98                 sub {
99                   my $cust_pkg = shift->cust_pkg;
100                   $cust_pkg ? ucfirst($cust_pkg->statuscolor) : '';
101                 },
102                ('') x 6,
103              ],
104   'style' => [
105                ('') x (5 + $x),
106                'b',
107                ('') x 6
108              ],
109 &>
110 <%init>
111
112 die "access denied"
113   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
114
115 my $conf = new FS::Conf;
116
117 my $setup = $cgi->param('setup') ? 1 : 0;
118 my $recur = $cgi->param('recur') ? 1 : 0;
119 my $usage = $cgi->param('usage') ? 1 : 0;
120
121 my $x = $setup + $recur + $usage;
122
123 my @select = ( 'cust_bill_pkg.*', 'cust_bill._date' );
124 my ($join_cust, $join_pkg ) = ('', '');
125
126 #here is the agent virtualization
127 my $agentnums_sql =
128   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
129
130 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
131
132 my @where = ( $agentnums_sql,
133               'cust_bill_pkg.pkgnum != 0', # exclude taxes
134               "cust_bill._date >= $beginning",
135               "cust_bill._date <= $ending",
136             );
137
138 my @status_where;
139 foreach my $status ($cgi->param('status')) {
140   if ( $status =~ /^([- a-z]+)$/ ) { #"one-time charge"
141     push @status_where, "'$status'";
142   }
143 }
144 if ( @status_where ) {
145   push @where, '('. FS::cust_pkg->status_sql.
146     ') IN (' . join(',', @status_where) .')';
147 }
148
149 my @refnum;
150 foreach my $refnum ($cgi->param('refnum')) {
151   if ( $refnum =~ /^\d+$/ ) {
152     push @refnum, $refnum;
153   }
154 }
155 if ( @refnum ) {
156   push @where, 'cust_main.refnum IN ('.join(',', @refnum).')';
157 }
158
159 # cust_classnum (false laziness w/ elements/cust_main_dayranges.html, elements/cust_pay_or_refund.html, prepaid_income.html, cust_bill_pay.html, cust_bill_pkg.html, unearned_detail.html, cust_credit.html, cust_credit_refund.html, cust_main::Search::search_sql)
160 if ( grep { $_ eq 'cust_classnum' } $cgi->param ) {
161   my @classnums = grep /^\d*$/, $cgi->param('cust_classnum');
162   push @where, 'COALESCE( cust_main.classnum, 0) IN ( '.
163                    join(',', map { $_ || '0' } @classnums ).
164                ' )'
165     if @classnums;
166 }
167
168 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
169   push @where, "cust_main.agentnum = $1";
170 }
171
172 #classnum
173 # not specified: all classes
174 # 0: empty class
175 # N: classnum
176 my $use_override = 1; #$cgi->param('use_override');
177 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
178   my $comparison = '';
179   if ( $1 == 0 ) {
180     $comparison = "IS NULL";
181   } else {
182     $comparison = "= $1";
183   }
184
185   if ( $use_override ) {
186     push @where, "(
187       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
188       override.classnum $comparison AND pkgpart_override IS NOT NULL
189     )";
190   } else {
191     push @where, "part_pkg.classnum $comparison";
192   }
193 }
194
195 # report option
196 my @report_option = grep /^\d+$/, ( $cgi->param('report_option') );
197 if ( @report_option ) {
198   @report_option = map { "'report_option_$_'" } @report_option;
199   push @where, "EXISTS( 
200     SELECT 1 FROM part_pkg_option WHERE optionname IN (".
201     join(',', @report_option).") AND (
202       part_pkg_option.pkgpart = cust_pkg.pkgpart AND pkgpart_override IS NULL
203       OR part_pkg_option.pkgpart = pkgpart_override
204     )
205   )";
206 }
207
208 my $setup_sql =
209   FS::cust_bill_pkg->charged_sql('', '', setuprecur => 'setup');
210 my $recur_sql =
211   FS::cust_bill_pkg->charged_sql('', '', setuprecur => 'recur', no_usage => 1);
212 my $usage_sql = FS::cust_bill_pkg->usage_sql;
213
214 # exclude zero-amount items
215 my @orwhere;
216 push @orwhere, "(cust_bill_pkg.setup > 0)" if $setup;
217 push @orwhere, "($recur_sql > 0)"          if $recur;
218 push @orwhere, "($usage_sql > 0)"          if $usage;
219 push @where, '('.join(' OR ', @orwhere).')' if @orwhere;
220
221 $join_cust =  '        JOIN cust_bill     USING ( invnum )
222                   LEFT JOIN cust_main     USING ( custnum )
223                   LEFT JOIN part_referral USING ( refnum )
224                   LEFT JOIN agent ON cust_main.agentnum = agent.agentnum
225               ';
226
227 $join_pkg .=  ' LEFT JOIN cust_pkg USING ( pkgnum )
228                 LEFT JOIN part_pkg USING ( pkgpart )
229                 LEFT JOIN part_pkg AS override
230                   ON pkgpart_override = override.pkgpart 
231                 LEFT JOIN pkg_class ON '; #...
232
233 if ( $use_override ) {
234   # join to whichever pkgpart is appropriate
235   $join_pkg .= '
236       ( pkgpart_override IS NULL     AND part_pkg.classnum = pkg_class.classnum )
237    OR ( pkgpart_override IS NOT NULL AND override.classnum = pkg_class.classnum )';
238 } else {
239   $join_pkg .= 'part_pkg.classnum = pkg_class.classnum';
240 }
241
242 my $where = ' WHERE '. join(' AND ', @where);
243
244 # setup and recurring only
245 my $count_query = "SELECT 
246   COUNT(billpkgnum)".
247   ($setup ? ", SUM($setup_sql)" : '').
248   ($recur ? ", SUM($recur_sql)" : '').
249   ($usage ? ", SUM($usage_sql)" : '').
250   " FROM cust_bill_pkg
251   $join_cust
252   $join_pkg
253   $where
254   ";
255
256 my $paid_sql = FS::cust_bill_pkg->paid_sql('', '');
257 my $last_pay_sql = "SELECT MAX(_date)
258   FROM cust_bill_pay JOIN cust_bill_pay_pkg USING (billpaynum)
259   WHERE cust_bill_pay_pkg.billpkgnum = cust_bill_pkg.billpkgnum";
260
261 push @select, 'part_pkg.pkg',
262               'part_pkg.freq',
263               'cust_main.custnum',
264               'cust_main.first',
265               'cust_main.last',
266               'cust_main.company',
267               'part_referral.referral',
268               "($paid_sql) AS paid",
269               "($last_pay_sql) AS last_pay",
270               "($recur_sql) AS recur_no_usage",
271               "($usage_sql) AS recur_usage",
272               'pkg_class.classname',
273               'agent.agent',
274               ;
275
276 my $query = {
277   'table'     => 'cust_bill_pkg',
278   'addl_from' => "$join_cust $join_pkg",
279   'hashref'   => {},
280   'select'    => join(",\n", @select ),
281   'extra_sql' => $where,
282   'order_by'  => 'ORDER BY cust_bill._date, billpkgnum',
283 };
284
285 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
286 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
287
288 my $conf = new FS::Conf;
289 my $money_char = $conf->config('money_char') || '$';
290
291 my %report_classes; #cache
292 my %report_option_name = 
293   map { $_->num => $_->name } qsearch('part_pkg_report_option', {});
294
295 # should this be in Mason.pm or something?
296 sub money_sub {
297   $conf ||= new FS::Conf;
298   $money_char ||= $conf->config('money_char') || '$';
299   my $field = shift;
300   sub {
301     $money_char . sprintf('%.2f', $_[0]->get($field));
302   };
303 }
304
305 sub date_sub {
306   my $field = shift;
307   sub {
308     my $value = $_[0]->get($field);
309     $value ? time2str('%b %d %Y', $value) : '';
310   };
311 }
312
313 </%init>