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