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