filter by customer class on all financial reports, #20573
[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 my @cust_classnums = grep /^\d+$/, $cgi->param('cust_classnum');
160 if ( @cust_classnums ) {
161   push @where, 'cust_main.classnum IN ('.join(',', @cust_classnums).')';
162 }
163
164 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
165   push @where, "cust_main.agentnum = $1";
166 }
167
168 #classnum
169 # not specified: all classes
170 # 0: empty class
171 # N: classnum
172 my $use_override = 1; #$cgi->param('use_override');
173 if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
174   my $comparison = '';
175   if ( $1 == 0 ) {
176     $comparison = "IS NULL";
177   } else {
178     $comparison = "= $1";
179   }
180
181   if ( $use_override ) {
182     push @where, "(
183       part_pkg.classnum $comparison AND pkgpart_override IS NULL OR
184       override.classnum $comparison AND pkgpart_override IS NOT NULL
185     )";
186   } else {
187     push @where, "part_pkg.classnum $comparison";
188   }
189 }
190
191 # report option
192 my @report_option = grep /^\d+$/, ( $cgi->param('report_option') );
193 if ( @report_option ) {
194   @report_option = map { "'report_option_$_'" } @report_option;
195   push @where, "EXISTS( 
196     SELECT 1 FROM part_pkg_option WHERE optionname IN (".
197     join(',', @report_option).") AND (
198       part_pkg_option.pkgpart = cust_pkg.pkgpart AND pkgpart_override IS NULL
199       OR part_pkg_option.pkgpart = pkgpart_override
200     )
201   )";
202 }
203
204 my $setup_sql =
205   FS::cust_bill_pkg->charged_sql('', '', setuprecur => 'setup');
206 my $recur_sql =
207   FS::cust_bill_pkg->charged_sql('', '', setuprecur => 'recur', no_usage => 1);
208 my $usage_sql = FS::cust_bill_pkg->usage_sql;
209
210 # exclude zero-amount items
211 my @orwhere;
212 push @orwhere, "(cust_bill_pkg.setup > 0)" if $setup;
213 push @orwhere, "($recur_sql > 0)"          if $recur;
214 push @orwhere, "($usage_sql > 0)"          if $usage;
215 push @where, '('.join(' OR ', @orwhere).')' if @orwhere;
216
217 $join_cust =  '        JOIN cust_bill     USING ( invnum )
218                   LEFT JOIN cust_main     USING ( custnum )
219                   LEFT JOIN part_referral USING ( refnum )
220                   LEFT JOIN agent ON cust_main.agentnum = agent.agentnum
221               ';
222
223 $join_pkg .=  ' LEFT JOIN cust_pkg USING ( pkgnum )
224                 LEFT JOIN part_pkg USING ( pkgpart )
225                 LEFT JOIN part_pkg AS override
226                   ON pkgpart_override = override.pkgpart 
227                 LEFT JOIN pkg_class ON '; #...
228
229 if ( $use_override ) {
230   # join to whichever pkgpart is appropriate
231   $join_pkg .= '
232       ( pkgpart_override IS NULL     AND part_pkg.classnum = pkg_class.classnum )
233    OR ( pkgpart_override IS NOT NULL AND override.classnum = pkg_class.classnum )';
234 } else {
235   $join_pkg .= 'part_pkg.classnum = pkg_class.classnum';
236 }
237
238 my $where = ' WHERE '. join(' AND ', @where);
239
240 # setup and recurring only
241 my $count_query = "SELECT 
242   COUNT(billpkgnum)".
243   ($setup ? ", SUM($setup_sql)" : '').
244   ($recur ? ", SUM($recur_sql)" : '').
245   ($usage ? ", SUM($usage_sql)" : '').
246   " FROM cust_bill_pkg
247   $join_cust
248   $join_pkg
249   $where
250   ";
251
252 my $paid_sql = FS::cust_bill_pkg->paid_sql('', '');
253 my $last_pay_sql = "SELECT MAX(_date)
254   FROM cust_bill_pay JOIN cust_bill_pay_pkg USING (billpaynum)
255   WHERE cust_bill_pay_pkg.billpkgnum = cust_bill_pkg.billpkgnum";
256
257 push @select, 'part_pkg.pkg',
258               'part_pkg.freq',
259               'cust_main.custnum',
260               'cust_main.first',
261               'cust_main.last',
262               'cust_main.company',
263               'part_referral.referral',
264               "($paid_sql) AS paid",
265               "($last_pay_sql) AS last_pay",
266               "($recur_sql) AS recur_no_usage",
267               "($usage_sql) AS recur_usage",
268               'pkg_class.classname',
269               'agent.agent',
270               ;
271
272 my $query = {
273   'table'     => 'cust_bill_pkg',
274   'addl_from' => "$join_cust $join_pkg",
275   'hashref'   => {},
276   'select'    => join(",\n", @select ),
277   'extra_sql' => $where,
278   'order_by'  => 'ORDER BY cust_bill._date, billpkgnum',
279 };
280
281 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
282 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
283
284 my $conf = new FS::Conf;
285 my $money_char = $conf->config('money_char') || '$';
286
287 my %report_classes; #cache
288 my %report_option_name = 
289   map { $_->num => $_->name } qsearch('part_pkg_report_option', {});
290
291 # should this be in Mason.pm or something?
292 sub money_sub {
293   $conf ||= new FS::Conf;
294   $money_char ||= $conf->config('money_char') || '$';
295   my $field = shift;
296   sub {
297     $money_char . sprintf('%.2f', $_[0]->get($field));
298   };
299 }
300
301 sub date_sub {
302   my $field = shift;
303   sub {
304     my $value = $_[0]->get($field);
305     $value ? time2str('%b %d %Y', $value) : '';
306   };
307 }
308
309 </%init>