remove duplicate cust_bill_pkg creation RT#3919
[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                               }, );
49
50 my @cust_pkg = 
51   grep { $_->part_pkg->recur != 0
52          && $_->part_pkg->freq !~ /^([01]|\d+[dw])$/
53        }
54     qsearch ( 'cust_pkg', {
55                             'bill' => { op=>'>', value=>$now }
56                           } );
57
58 foreach my $cust_bill_pkg ( @cust_bill_pkg) { 
59   my $period = $cust_bill_pkg->edate - $cust_bill_pkg->sdate;
60
61   my $elapsed = $now - $cust_bill_pkg->sdate;
62   $elapsed = 0 if $elapsed < 0;
63
64   my $remaining = 1 - $elapsed/$period;
65
66   my $unearned = $remaining * $cust_bill_pkg->recur;
67   $total += $unearned;
68
69 }
70
71 foreach my $cust_pkg ( @cust_pkg ) {
72   my $period = $cust_pkg->bill - $cust_pkg->last_bill;
73
74   my $elapsed = $now - $cust_pkg->last_bill;
75   $elapsed = 0 if $elapsed < 0;
76
77   my $remaining = 1 - $elapsed/$period;
78
79   my $unearned = $remaining * $cust_pkg->part_pkg->recur; #!! only works for flat/legacy
80   $total_legacy += $unearned;
81
82 }
83
84 $total = sprintf('%.2f', $total);
85 $total_legacy = sprintf('%.2f', $total_legacy);
86
87 </%init>