RT#39638: VoIP Usage cost reporting [bug fixes/cleanup]
[freeside.git] / httemplate / search / customer_cdr_profit.html
1 % if ( $cgi->param('_type') =~ /(xls)$/ ) {
2 <%perl>
3   # egregious false laziness w/ search/report_tax-xls.cgi
4   my $format = $FS::CurrentUser::CurrentUser->spreadsheet_format;
5   my $filename = $cgi->url(-relative => 1);
6   $filename =~ s/\.html$//;
7   $filename .= $format->{extension};
8   http_header('Content-Type' => $format->{mime_type});
9   http_header('Content-Disposition' => qq!attachment;filename="$filename"!);
10
11   my $output = '';
12   my $XLS = IO::String->new($output);
13   my $workbook = $format->{class}->new($XLS)
14     or die "Error opening .xls file: $!";
15
16   my $worksheet = $workbook->add_worksheet('Summary');
17
18   my %format = (
19     header => {
20       size      => 11,
21       bold      => 1,
22       align     => 'center',
23       valign    => 'vcenter',
24       text_wrap => 1,
25     },
26     money => {
27       size      => 11,
28       align     => 'right',
29       valign    => 'bottom',
30       num_format=> 8,
31     },
32     '' => {},
33   );
34   my %default = (
35       font      => 'Calibri',
36       border    => 1,
37   );
38   foreach (keys %format) {
39     my %f = (%default, %{$format{$_}});
40     $format{$_} = $workbook->add_format(%f);
41     $format{"m_$_"} = $workbook->add_format(%f);
42   }
43
44   my ($r, $c) = (0, 0);
45   for my $row (@rows) {
46     $c = 0;
47     my $thisrow = shift @cells;
48     for my $cell (@$thisrow) {
49       if (!ref($cell)) {
50         # placeholder, so increment $c so that we write to the correct place
51         $c++;
52         next;
53       }
54       # format name
55       my $f = '';
56       $f = 'header' if $row->{header} or $cell->{header};
57       $f = 'money' if $cell->{format} eq 'money';
58       if ( $cell->{rowspan} > 1 or $cell->{colspan} > 1 ) {
59         my $range = xl_range_formula(
60           'Summary',
61           $r, $r - 1 + ($cell->{rowspan} || 1),
62           $c, $c - 1 + ($cell->{colspan} || 1)
63         );
64         #warn "merging $range\n";
65         $worksheet->merge_range($range, $cell->{value}, $format{"m_$f"});
66       } else {
67       #warn "writing ".xl_rowcol_to_cell($r, $c)."\n";
68         $worksheet->write( $r, $c, $cell->{value}, $format{$f} );
69       }
70       $c += $cell->{colspan} || 1;
71     } #$cell
72   $r++;
73   } #$row
74   $workbook->close;
75
76   http_header('Content-Length' => length($output));
77   $m->print($output);
78 </%perl>
79 % } else {
80 <& /elements/header.html, $title &>
81 % my $myself = $cgi->self_url;
82 <P ALIGN="right" CLASS="noprint">
83 Download full reports<BR>
84 as <A HREF="<% "$myself;_type=xls" %>">Excel spreadsheet</A>
85 </P>
86 <style type="text/css">
87 .report * {
88   background-color: #f8f8f8;
89   border: 1px solid #999999;
90   padding: 2px;
91 }
92 .report td {
93   text-align: right;
94 }
95 .total { background-color: #f5f6be; }
96 .shaded { background-color: #c8c8c8; }
97 .totalshaded { background-color: #bfc094; }
98 </style>
99 <table class="report" width="100%" cellspacing=0>
100 % foreach my $rowinfo (@rows) {
101   <tr<% $rowinfo->{class} ? ' class="'.$rowinfo->{class}.'"' : ''%>>
102 %   my $thisrow = shift @cells;
103 %   foreach my $cell (@$thisrow) {
104 %     next if !ref($cell); # placeholders
105 %     my $td = $cell->{header} ? 'th' : 'td';
106 %     my $style = '';
107 %     $style .= ' class="'.$cell->{class}.'"' if $cell->{class};
108 %     $style .= " rowspan=".$cell->{rowspan} if $cell->{rowspan} > 1;
109 %     $style .= " colspan=".$cell->{colspan} if $cell->{colspan} > 1;
110 %     $style .= ' style="color: red"' if $cell->{value} < 0;
111       <<%$td%><%$style%>><% $cell->{value} |h %></<%$td%>>
112 %   }
113   </tr>
114 % }
115 </table>
116
117 <& /elements/footer.html &>
118 % }
119 <%init>
120
121 die "access denied"
122   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports')
123       && $FS::CurrentUser::CurrentUser->access_right('List rating data');
124
125 my ($agentnum,$sel_agent);
126 if ( $cgi->param('agentnum') =~ /^(\d+)$/ ) {
127   $agentnum = $1;
128   $sel_agent = qsearchs('agent', { 'agentnum' => $agentnum } );
129   die "agentnum $agentnum not found!" unless $sel_agent;
130 }
131 my $title = $sel_agent ? $sel_agent->agent.' ' : '';
132
133 $title .= 'Customer CDRs Profit/Loss Report';
134
135 my @items  = ('cust_bill_pkg_recur', 'cust_bill_pkg_recur', 'cust_bill_pkg_detail', 'cust_bill_pkg_detail' );
136 my @params = ( [], [ 'cost' => 1 ], [], [ 'cost' => 1 ] );
137
138 my @labels = ();
139 my @cross_params = ();
140
141 my %search_hash;
142 foreach (qw(agentnum)) {
143   if ( defined $cgi->param($_) ) {
144     $search_hash{$_} = $cgi->param($_);
145   }
146 }
147
148 my $query = FS::cust_main::Search->search(\%search_hash);
149 my @cust_main = qsearch($query);
150
151 foreach my $cust_main (@cust_main) {
152   push @cross_params, [ ('custnum' => $cust_main->custnum) ];
153 }
154
155 my %opt = (
156   items         => \@items,
157   params        => \@params,
158   cross_params  => \@cross_params,
159   agentnum      => $agentnum,
160 );
161 for ( qw(start_month start_year end_month end_year) ) {
162   if ( $cgi->param($_) =~ /^(\d+)$/ ) {
163     $opt{$_} = $1;
164   }
165 }
166
167 my $report = FS::Report::Table::Monthly->new(%opt);
168 my $data = $report->data;
169
170 ### False laziness with customer_accounting_summary.html
171 my @total;
172
173 my @rows; # hashes of row info
174 my @cells; # arrayrefs of cell info
175 # We use Excel currency format, but not Excel dates, because
176 # these are whole months and there's no nice way to express that.
177 # This is the historical behavior for monthly reports.
178
179 # header row
180 $rows[0] = {};
181 $cells[0] = [
182   { header => 1, rowspan => 2 },
183   map {
184     { header => 1, colspan => 5, value => time2str('%b %Y', $_) }
185   } @{ $data->{speriod} }
186 ];
187 my $ncols = scalar(@{ $data->{speriod} });
188
189 $rows[1] = {};
190 $cells[1] = [ '',
191   map { 
192   ( 
193     { header => 1, value => mt('Recur Fee') },
194     { header => 1, value => mt('Recur Cost') },
195     { header => 1, value => mt('Usage Fee') },
196     { header => 1, value => mt('Usage Cost') },
197     { header => 1, value => mt('Profit'), class => 'shaded' },
198   ) } (1..$ncols)
199 ];
200
201 my $row = 0;
202 foreach my $cust_main (@cust_main) { # correspond to cross_params
203   my $skip = 1; # skip the customer iff ALL of their values are zero
204   push @rows, {};
205   my @thisrow;
206   # customer name
207   push @thisrow,
208     { value   => $cust_main->name,
209       header  => 1
210     };
211   for my $col (0..$ncols-1) { # the month
212     my $profit = 0;
213     for my $item (0..3) { # recur/recur_cost/usage/usage_cost
214       my $value = $data->{data}[$item][$col][$row];
215       $skip = 0 if abs($value) > 0.005;
216       push @thisrow, { value => sprintf('%0.2f', $value), format => 'money' };
217       $total[$col * 5 + $item] += $value;
218       $profit += (($item % 2) ? -1 : 1) * $value;
219     } #item
220     push @thisrow, { 
221       value => sprintf('%0.2f', $profit), 
222       format => 'money',
223       class => 'shaded',
224     };
225     $total[$col * 5 + 4] += $profit;
226   } #month
227   push @cells, \@thisrow;
228
229   if ( $skip ) {
230     # all values are zero--remove the rows we just added
231     pop @rows;
232     pop @cells;
233   }
234   $row++;
235 }
236
237 push @rows, { class => 'total' };
238 my @thisrow;
239 push @thisrow,
240   { value => mt('Total'),
241     header => 1
242   };
243 for my $col (0..($ncols * 5)-1) { # month and recur/recur_cost/usage/usage_cost/profit
244   my $value = $total[$col];
245   push @thisrow, { 
246     value => sprintf('%0.2f', $value), 
247     format => 'money',
248     class => ($col % 5 == 4) ? 'totalshaded' : 'total',
249   };
250 }
251 push @cells, \@thisrow;
252
253 </%init>