3694c7aaece83370176026c5e8e668014e1093fb
[freeside.git] / httemplate / search / report_prepaid_income.cgi
1 <% include("/elements/header.html", 'Prepaid Income (Unearned Revenue) Report') %>
2
3 <% table() %>
4   <TR>
5     <TH>Actual Unearned Revenue</TH>
6     <TH>Legacy Unearned Revenue</TH>
7   </TR>
8   <TR>
9     <TD ALIGN="right">$<% $total %>
10     <TD ALIGN="right">
11       <% $now == $time ? "\$$total_legacy" : '<i>N/A</i>'%>
12     </TD>
13   </TR>
14
15 </TABLE>
16 <BR>
17 Actual unearned revenue is the amount of unearned revenue Freeside has  
18 actually invoiced for packages with longer-than monthly terms.
19 <BR><BR>
20 Legacy unearned revenue is the amount of unearned revenue represented by 
21 customer packages.  This number may be larger than actual unearned 
22 revenue if you have imported longer-than monthly customer packages from
23 a previous billing system.
24 </BODY>
25 </HTML>
26 <%init>
27
28 die "access denied"
29   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
30
31 #doesn't yet deal with daily/weekly packages
32
33 #needs to be re-written in sql for efficiency
34
35 my $time = time;
36
37 my $now = $cgi->param('date') && str2time($cgi->param('date')) || $time;
38 $now =~ /^(\d+)$/ or die "unparsable date?";
39 $now = $1;
40
41 my( $total, $total_legacy ) = ( 0, 0 );
42
43 my @cust_bill_pkg =
44   grep { $_->cust_pkg && $_->cust_pkg->part_pkg->freq !~ /^([01]|\d+[dw])$/ }
45     qsearch( 'cust_bill_pkg', {
46                                 'recur'     => { op=>'!=', value=>0 },
47                                 'edate'     => { op=>'>', value=>$now },
48                                 'duplicate' => '',
49                               }, );
50
51 my @cust_pkg = 
52   grep { $_->part_pkg->recur != 0
53          && $_->part_pkg->freq !~ /^([01]|\d+[dw])$/
54        }
55     qsearch ( 'cust_pkg', {
56                             'bill' => { op=>'>', value=>$now }
57                           } );
58
59 foreach my $cust_bill_pkg ( @cust_bill_pkg) { 
60   my $period = $cust_bill_pkg->edate - $cust_bill_pkg->sdate;
61
62   my $elapsed = $now - $cust_bill_pkg->sdate;
63   $elapsed = 0 if $elapsed < 0;
64
65   my $remaining = 1 - $elapsed/$period;
66
67   my $unearned = $remaining * $cust_bill_pkg->recur;
68   $total += $unearned;
69
70 }
71
72 foreach my $cust_pkg ( @cust_pkg ) {
73   my $period = $cust_pkg->bill - $cust_pkg->last_bill;
74
75   my $elapsed = $now - $cust_pkg->last_bill;
76   $elapsed = 0 if $elapsed < 0;
77
78   my $remaining = 1 - $elapsed/$period;
79
80   my $unearned = $remaining * $cust_pkg->part_pkg->recur; #!! only works for flat/legacy
81   $total_legacy += $unearned;
82
83 }
84
85 $total = sprintf('%.2f', $total);
86 $total_legacy = sprintf('%.2f', $total_legacy);
87
88 </%init>