merging RT 4.0.6
[freeside.git] / httemplate / search / unearned_detail.html
1 <& elements/search.html,
2   'title'       => emt("Unearned revenue - ".ucfirst($unearned_mode)) . ' (' .
3                    time2str('%b %d %Y', $unearned) . ')',
4   'name'        => emt('line items'),
5   'query'       => $query,
6   'count_query' => $count_query,
7   'count_addl'  => [ $money_char. '%.2f total',
8                      $money_char. '%.2f unearned revenue' 
9                    ],
10   'header'      => [ map( {emt $_} 
11     'Description',
12     'Unearned', # depends on mode
13     'Recurring charge', #recur - usage
14     'Owed', #recur - usage - credits - payments
15     'Paid', #payments
16     'Payment date', #of last payment
17     'Credit date', #of last credit
18     'Charge start',
19     'Charge end',
20     'Invoice',
21     'Date'
22     ),
23     FS::UI::Web::cust_header(),
24   ],
25   'fields'      => [
26     #Description
27     sub { $_[0]->pkgnum > 0
28       ? $_[0]->get('pkg')      # possibly use override.pkg
29       : $_[0]->get('itemdesc') # but i think this correct
30     },
31     #Unearned
32     money_sub('unearned_revenue'),
33     #Recurring charge
34     money_sub('recur_no_usage'),
35     #Owed
36     money_sub('owed_no_usage'),
37     #Paid
38     money_sub('paid_no_usage'),
39     #Payment date
40     date_sub('last_pay'),
41     #Credit date
42     date_sub('last_credit'),
43     #Charge start
44     date_sub('sdate'),
45     #Charge end, minus most of a day
46     date_sub('before_edate'),
47     #Invoice
48     'invnum',
49     #Invoice date
50     date_sub('_date'),
51     \&FS::UI::Web::cust_fields,
52   ],
53   'sort_fields' => [
54     'pkg',
55     # SQL expressions work as sort keys...
56     'unearned_revenue',
57     'recur_no_usage',
58     'owed_no_usage',
59     'paid_no_usage',
60     'last_pay',
61     'last_credit',
62     'sdate',
63     'edate',
64     'invnum',
65     '_date',
66   ],
67   'links'       => [
68     ('' x 9),
69     $ilink,
70     $ilink,
71     ( map { $_ ne 'Cust. Status' ? $clink : '' }
72       FS::UI::Web::cust_header()
73     ),
74   ],
75   'align' => 'lrrcrccrc'.  FS::UI::Web::cust_aligns(),
76   'color' => [ 
77     ('' x 11),
78     FS::UI::Web::cust_colors(),
79   ],
80   'style' => [ 
81     ('' x 11),
82     FS::UI::Web::cust_styles(),
83   ],
84 &>
85 <%init>
86
87 # Separated from cust_bill_pkg.cgi to simplify things.
88
89 die "access denied"
90   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
91
92 my $conf = new FS::Conf;
93
94 my $unearned = '';
95 my $unearned_mode = '';
96 my $unearned_base = '';
97 my $unearned_sql = '';
98
99 my @select = ( 'cust_bill_pkg.*', 'cust_bill._date' );
100 my ($join_cust, $join_pkg ) = ('', '');
101
102 #here is the agent virtualization
103 my $agentnums_sql =
104   $FS::CurrentUser::CurrentUser->agentnums_sql( 'table' => 'cust_main' );
105
106 my @where = ( $agentnums_sql );
107
108 my($beginning, $ending) = FS::UI::Web::parse_beginning_ending($cgi);
109
110 if ( $cgi->param('status') =~ /^([a-z]+)$/ ) {
111   push @where, FS::cust_main->cust_status_sql . " = '$1'";
112 }
113
114 push @where, "cust_bill._date >= $beginning",
115              "cust_bill._date <= $ending";
116
117 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
118   push @where, "cust_main.agentnum = $1";
119 }
120
121 # no pkgclass, no taxclass, no tax location...
122
123 # unearned revenue mode
124 $cgi->param('date') =~ /^(\d+)$/
125   or die "date required";
126
127 $unearned = $1;
128 $unearned_mode = $cgi->param('mode');
129
130 push @where, "cust_bill_pkg.sdate < $unearned",
131              "cust_bill_pkg.edate > $unearned",
132              "cust_bill_pkg.recur != 0",
133              "part_pkg.freq != '0'";
134
135 if ( !$cgi->param('include_monthly') ) {
136   push @where,
137              "part_pkg.freq != '1'",
138              "part_pkg.freq NOT LIKE '%h'",
139              "part_pkg.freq NOT LIKE '%d'",
140              "part_pkg.freq NOT LIKE '%w'";
141 }
142
143 my @opt = (
144   $unearned, #before this date
145   '',        #after this date
146   setuprecur => 'recur',
147   no_usage => 1
148 );
149
150 my $charged = FS::cust_bill_pkg->charged_sql(@opt);
151 push @select, "($charged) AS recur_no_usage";
152
153 my $owed_sql = FS::cust_bill_pkg->owed_sql(@opt);
154 push @select, "($owed_sql) AS owed_no_usage";
155
156 my $paid_sql = FS::cust_bill_pkg->paid_sql(@opt);
157 push @select, "$paid_sql AS paid_no_usage";
158
159 if ( $unearned_mode eq 'paid' ) {
160   # then use the amount paid, minus usage charges
161   $unearned_base = $paid_sql;
162 }
163 else {
164   # use the amount billed, minus usage charges and credits
165   $unearned_base = "( $charged - " . 
166                     FS::cust_bill_pkg->credited_sql(@opt) . ' )';
167 }
168 # whatever we're using as the base, only show rows where it's positive
169 push @where, "$unearned_base > 0";
170
171 my $edate_zero = midnight_sql('edate');
172 my $sdate_zero = midnight_sql('sdate');
173 # $unearned is one second before midnight on the date requested for the report.
174
175 # suppress partial days for more accounting-like behavior
176 my $period = "CAST( ($edate_zero - $sdate_zero) / 86400.0 AS DECIMAL(10,0) )";
177
178 my $remaining = "GREATEST( 
179   CAST( ($edate_zero - $unearned) / 86400.0 AS DECIMAL(10,0) ),
180   0)";
181 my $fraction = "$remaining / $period";
182
183 $unearned_sql = "CAST( $unearned_base * $fraction AS DECIMAL(10,2) )";
184 push @select, "$unearned_sql AS unearned_revenue";
185
186 # last payment/credit date
187 my %t = (pay => 'cust_bill_pay', credit => 'cust_credit_bill');
188 foreach my $x (qw(pay credit)) {
189   my $table = $t{$x};
190   my $link = $table.'_pkg';
191   my $pkey = dbdef->table($table)->primary_key;
192   my $last_date_sql = "SELECT MAX(_date) 
193   FROM $table JOIN $link USING ($pkey)
194   WHERE $link.billpkgnum = cust_bill_pkg.billpkgnum 
195   AND $table._date <= $unearned";
196   push @select, "($last_date_sql) AS last_$x";
197 }
198
199 push @select, '(edate - 82799) AS before_edate';
200
201 #no itemdesc
202 #no tax report group kludge
203 #no tax exemption
204 #usage always excluded
205
206 # always 'nottax', not 'istax'
207 $join_cust =  '        JOIN cust_bill USING ( invnum )
208                   LEFT JOIN cust_main USING ( custnum ) ';
209
210 $join_pkg .=  ' LEFT JOIN cust_pkg USING ( pkgnum )
211                 LEFT JOIN part_pkg USING ( pkgpart )
212                 LEFT JOIN part_pkg AS override
213                   ON pkgpart_override = override.pkgpart ';
214
215 my $where = ' WHERE '. join(' AND ', @where);
216
217 my $count_query = "SELECT COUNT(DISTINCT billpkgnum), 
218   SUM( $unearned_base ), SUM( $unearned_sql )
219   FROM cust_bill_pkg $join_cust $join_pkg $where";
220
221 push @select, 'part_pkg.pkg',
222               'part_pkg.freq',
223               'cust_main.custnum',
224               FS::UI::Web::cust_sql_fields();
225
226 my $query = {
227   'table'     => 'cust_bill_pkg',
228   'addl_from' => "$join_cust $join_pkg",
229   'hashref'   => {},
230   'select'    => join(",\n", @select ),
231   'extra_sql' => $where,
232   'order_by'  => 'ORDER BY cust_bill._date, billpkgnum',
233 };
234
235 my $ilink = [ "${p}view/cust_bill.cgi?", 'invnum' ];
236 my $clink = [ "${p}view/cust_main.cgi?", 'custnum' ];
237
238 my $money_char;
239
240 sub money_sub {
241   $conf ||= new FS::Conf;
242   $money_char ||= $conf->config('money_char') || '$';
243   my $field = shift;
244   sub {
245     $money_char . sprintf('%.2f', $_[0]->get($field));
246   };
247 }
248
249 sub date_sub {
250   my $field = shift;
251   sub {
252     my $value = $_[0]->get($field);
253     $value ? time2str('%b %d %Y', $value) : '';
254   };
255 };
256
257 </%init>