Update httemplate/elements/selectlayers.html
[freeside.git] / httemplate / search / customer_accounting_summary.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   use IO::String;
13   my $XLS = IO::String->new($output);;
14   my $workbook = $format->{class}->new($XLS)
15     or die "Error opening .xls file: $!";
16
17   my $worksheet = $workbook->add_worksheet('Summary');
18
19   my %format = (
20     header => {
21       size      => 11,
22       bold      => 1,
23       align     => 'center',
24       valign    => 'vcenter',
25       text_wrap => 1,
26     },
27     money => {
28       size      => 11,
29       align     => 'right',
30       valign    => 'bottom',
31       num_format=> 8,
32     },
33     '' => {},
34   );
35   my %default = (
36       font      => 'Calibri',
37       border    => 1,
38   );
39   foreach (keys %format) {
40     my %f = (%default, %{$format{$_}});
41     $format{$_} = $workbook->add_format(%f);
42     $format{"m_$_"} = $workbook->add_format(%f);
43   }
44
45   my ($r, $c) = (0, 0);
46   for my $row (@rows) {
47     $c = 0;
48     my $thisrow = shift @cells;
49     for my $cell (@$thisrow) {
50       if (!ref($cell)) {
51         # placeholder, so increment $c so that we write to the correct place
52         $c++;
53         next;
54       }
55       # format name
56       my $f = '';
57       $f = 'header' if $row->{header} or $cell->{header};
58       $f = 'money' if $cell->{format} eq 'money';
59       if ( $cell->{rowspan} > 1 or $cell->{colspan} > 1 ) {
60         my $range = xl_range_formula(
61           'Summary',
62           $r, $r - 1 + ($cell->{rowspan} || 1),
63           $c, $c - 1 + ($cell->{colspan} || 1)
64         );
65         #warn "merging $range\n";
66         $worksheet->merge_range($range, $cell->{value}, $format{"m_$f"});
67       } else {
68       #warn "writing ".xl_rowcol_to_cell($r, $c)."\n";
69         $worksheet->write( $r, $c, $cell->{value}, $format{$f} );
70       }
71       $c++;
72     } #$cell
73   $r++;
74   } #$row
75   $workbook->close;
76 </%perl>
77 <% $output %>
78 % } else { 
79 <& /elements/header.html, $title &>
80 % my $myself = $cgi->self_url;
81 <P ALIGN="right" CLASS="noprint">
82 Download full reports<BR>
83 as <A HREF="<% "$myself;_type=xls" %>">Excel spreadsheet</A><BR>
84 % # as <A HREF="<% "$myself;_type=csv" %>">CSV file</A> # is this still needed?
85 </P>
86 <style type="text/css">
87 .report * {
88   background-color: #f8f8f8;
89   border: 1px solid black;
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 .= " rowspan=".$cell->{rowspan} if $cell->{rowspan} > 1;
108 %     $style .= " colspan=".$cell->{colspan} if $cell->{colspan} > 1;
109       <<%$td%><%$style%>><% $cell->{value} %></<%$td%>>
110 %   }
111   </tr>
112 % }
113 </table>
114
115 <& /elements/footer.html &>
116 % }
117 <%init>
118
119 die "access denied"
120   unless $FS::CurrentUser::CurrentUser->access_right('Financial reports');
121
122 my ($agentnum,$sel_agent);
123 if ( $cgi->param('agentnum') eq 'all' ) {
124   $agentnum = 0;
125 }
126 elsif ( $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 my ($refnum,$sel_part_referral);
134 if ( $cgi->param('refnum') =~ /^(\d+)$/ ) {
135   $refnum = $1;
136   $sel_part_referral = qsearchs('part_referral', { 'refnum' => $refnum } );
137   die "refnum $refnum not found!" unless $sel_part_referral;
138 }
139 $title .=  $sel_part_referral->referral.' '
140   if $sel_part_referral;
141
142 $title .= 'Customer Accounting Summary Report';
143
144 my @custs = ();
145 @custs = qsearch('cust_main', {} );
146
147 my @items  = ('netsales', 'cashflow');
148 my @params = ( [], [] );
149 my $setuprecur = '';
150 if ( $cgi->param('setuprecur') ) {
151   $setuprecur = 1;
152   # instead of 'cashflow' (payments - refunds), use 'receipts'
153   # (applied payments), because it's divisible into setup and recur.
154   @items = ('netsales', 'receipts', 'netsales', 'receipts');
155   @params = ( 
156     [ setuprecur => 'setup' ],
157     [ setuprecur => 'setup' ],
158     [ setuprecur => 'recur' ],
159     [ setuprecur => 'recur' ],
160   );
161 }
162 my @labels = ();
163 my @cross_params = ();
164 my @custnames = ();
165
166 my $status = $cgi->param('status');
167 die "invalid status" unless $status =~ /^\w+|$/;
168
169 foreach my $cust_main ( @custs ) {
170   # XXX should do this in the qsearch
171   next unless ($status eq '' || $status eq $cust_main->status); 
172   next unless ($agentnum == 0 || $cust_main->agentnum eq $agentnum);
173   next unless ($refnum   == 0 || $cust_main->refnum eq $refnum);
174
175   push @custnames, $cust_main->name;
176
177   push @cross_params, [ ('custnum' => $cust_main->custnum) ];
178 }
179
180 my %opt = (
181   items         => \@items,
182   params        => \@params,
183   cross_params  => \@cross_params,
184   agentnum      => $agentnum,
185   refnum        => $refnum,
186 );
187 for ( qw(start_month start_year end_month end_year) ) {
188   if ( $cgi->param($_) =~ /^(\d+)$/ ) {
189     $opt{$_} = $1;
190   }
191 }
192
193 warn Dumper(OPTIONS => \%opt) if $cgi->param('debug');
194 my $report = FS::Report::Table::Monthly->new(%opt);
195 my $data = $report->data;
196 warn Dumper(DATA => $data) if $cgi->param('debug') >= 2;
197
198 my @total;
199
200 my @rows; # hashes of row info
201 my @cells; # arrayrefs of cell info
202 # We use Excel currency format, but not Excel dates, because
203 # these are whole months and there's no nice way to express that.
204 # This is the historical behavior for monthly reports.
205
206 # header row
207 $rows[0] = {};
208 $cells[0] = [
209   { header => 1, rowspan => 2, colspan => ($setuprecur ? 2 : 1) },
210   ($setuprecur ? '' : ()),
211   map {
212     { header => 1, colspan => 2, value => time2str('%b %Y', $_) },
213     ''
214   } @{ $data->{speriod} }
215 ];
216 my $ncols = scalar(@{ $data->{speriod} });
217
218 $rows[1] = {};
219 $cells[1] = [ '',
220   ($setuprecur ? '' : ()),
221   map { 
222   ( { header => 1, value => mt('Billed') },
223     { header => 1, value => mt('Paid') }
224   ) } (1..$ncols)
225 ];
226
227 # use PDL; # ha ha, I just might.
228 my $row = 0;
229 foreach my $name (@custnames) { # correspond to cross_params
230   my $skip = 1; # skip the customer iff ALL of their values are zero
231   for my $subrow (0..($setuprecur ? 1 : 0)) { # the setup/recur axis
232     push @rows, { class => $subrow ? 'shaded' : '' };
233     my @thisrow;
234     if ( $subrow == 0 ) {
235       # customer name
236       push @thisrow,
237         { value => $name,
238           header => 1,
239           rowspan => ($setuprecur ? 2 : 1) };
240     } else {
241       push @thisrow, '';
242     }
243     if ( $setuprecur ) {
244       # subheading
245       push @thisrow,
246         { value => $subrow ? mt('recurring') : mt('setup'),
247           header => 1 };
248     }
249     for my $col (0..$ncols-1) { # the month
250       for my $subcol (0..1) { # the billed/paid axis
251         my $item = $subrow * 2 + $subcol;
252         my $value = $data->{data}[$item][$col][$row];
253         $skip = 0 if abs($value) > 0.005;
254         push @thisrow, { value => sprintf('%0.2f', $value), format => 'money' };
255         $total[( ($ncols * $subrow) + $col ) * 2 + $subcol] += $value;
256       } #subcol
257     } #col
258     push @cells, \@thisrow;
259   } #subrow
260   if ( $skip ) {
261     # all values are zero--remove the rows we just added
262     pop @rows;
263     pop @cells;
264     if ( $setuprecur ) {
265       pop @rows;
266       pop @cells;
267     }
268   }
269   $row++;
270 }
271 for my $subrow (0..($setuprecur ? 1 : 0)) {
272   push @rows, { class => ($subrow ? 'totalshaded' : 'total') };
273   my @thisrow;
274   if ( $subrow == 0 ) {
275     push @thisrow,
276       { value => mt('Total'),
277         header => 1,
278         rowspan => ($setuprecur ? 2 : 1), };
279   } else {
280     push @thisrow, '';
281   }
282   if ( $setuprecur ) {
283     push @thisrow,
284       { value => $subrow ? mt('recurring') : mt('setup'),
285         header => 1 };
286   }
287   for my $col (0..($ncols * 2)-1) { # month and billed/paid axis
288     my $value = $total[($subrow * $ncols * 2) + $col];
289     push @thisrow, { value => sprintf('%0.2f', $value), format => 'money' };
290   }
291   push @cells, \@thisrow;
292 } #subrow
293
294 if ( $cgi->param('debug') >= 3 ) {
295   warn Dumper(\@rows, \@cells);
296 }
297
298 my $title = 'Customer Accounting Summary';
299 </%init>