Eine Report-Klasse geschrieben, der die Ergebnisse von Datenbankabfragen übergeben...
[kivitendo-erp.git] / SL / ReportGenerator.pm
1 package SL::ReportGenerator;
2
3 use IO::Wrap;
4 use Text::CSV_XS;
5
6 use SL::Form;
7
8 sub new {
9   my $type = shift;
10
11   my $self = { };
12
13   $self->{myconfig} = shift;
14   $self->{form}     = shift;
15
16   $self->{data}     = [];
17   $self->{options}  = {
18     'std_column_visibility' => 0,
19     'output_format'         => 'HTML',
20     'allow_pdf_export'      => 1,
21     'allow_csv_export'      => 1,
22     'pdf_export'            => {
23       'paper_size'          => 'A4',
24       'orientation'         => 'landscape',
25       'font_size'           => '10',
26       'margin_top'          => 1.5,
27       'margin_left'         => 1.5,
28       'margin_bottom'       => 1.5,
29       'margin_right'        => 1.5,
30       'number'              => 1,
31     },
32     'csv_export'            => {
33       'quote_char'          => '"',
34       'sep_char'            => ';',
35       'escape_char'         => '"',
36       'eol_style'           => 'DOS',
37       'headers'             => 1,
38     },
39   };
40   $self->{export}   = {
41     'nextsub'       => '',
42     'variable_list' => '',
43   };
44
45   $self->set_options(@_) if (@_);
46
47   return bless $self, $type;
48 }
49
50 sub set_columns {
51   my $self    = shift;
52   my %columns = @_;
53
54   $self->{columns} = \%columns;
55
56   foreach my $column (values %{ $self->{columns} }) {
57     $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
58   }
59
60   $self->set_column_order(sort keys %{ $self->{columns} });
61 }
62
63 sub set_column_order {
64   my $self    = shift;
65
66   my $order   = 0;
67   my %columns = map { $order++; ($_, $order) } @_;
68
69   foreach my $column (sort keys %{ $self->{columns} }) {
70     next if $columns{$column};
71
72     $order++;
73     $columns{$column} = $order;
74   }
75
76   $self->{column_order} = [ sort { $columns{$a} <=> $columns{$b} } keys %columns ];
77 }
78
79 sub set_sort_indicator {
80   my $self = shift;
81
82   $self->{options}->{sort_indicator_column}    = shift;
83   $self->{options}->{sort_indicator_direction} = shift;
84 }
85
86 sub add_data {
87   my $self = shift;
88
89   while (my $arg = shift) {
90     if ('ARRAY' eq ref $arg) {
91       push @{ $self->{data} }, $arg;
92
93     } elsif ('HASH' eq ref $arg) {
94       push @{ $self->{data} }, [ $arg ];
95
96     } else {
97       $self->{form}->error('Incorrect usage -- expecting hash or array ref');
98     }
99   }
100 }
101
102 sub clear_data {
103   my $self = shift;
104
105   $self->{data} = [];
106 }
107
108 sub set_options {
109   my $self    = shift;
110   my %options = @_;
111
112   map { $self->{options}->{$_} = $options{$_} } keys %options;
113 }
114
115 sub set_options_from_form {
116   my $self     = shift;
117
118   my $form     = $self->{form};
119   my $myconfig = $self->{myconfig};
120
121   foreach my $key (qw(output_format)) {
122     my $full_key = "report_generator_${key}";
123     $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
124   }
125
126   foreach my $format (qw(pdf csv)) {
127     my $opts = $self->{options}->{"${format}_export"};
128     foreach my $key (keys %{ $opts }) {
129       my $full_key = "report_generator_${format}_options_${key}";
130       $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
131     }
132   }
133 }
134
135 sub set_export_options {
136   my $self        = shift;
137
138   $self->{export} = {
139     'nextsub'       => shift,
140     'variable_list' => join(" ", @_),
141   };
142 }
143
144 sub generate_content {
145   my $self   = shift;
146   my $format = lc $self->{options}->{output_format};
147
148   if (!$self->{columns}) {
149     $self->{form}->error('Incorrect usage -- no columns specified');
150   }
151
152   if ($format eq 'html') {
153     return $self->generate_html_content();
154
155   } elsif ($format eq 'csv') {
156     return $self->generate_csv_content();
157
158   } elsif ($format eq 'pdf') {
159     return $self->generate_pdf_content();
160
161   } else {
162     $self->{form}->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
163   }
164 }
165
166 sub generate_with_headers {
167   my $self   = shift;
168   my $format = lc $self->{options}->{output_format};
169
170   if (!$self->{columns}) {
171     $self->{form}->error('Incorrect usage -- no columns specified');
172   }
173
174   my $filename =  $self->{options}->{attachment_basename} || 'report';
175   $filename    =~ s|.*\\||;
176   $filename    =~ s|.*/||;
177
178   if ($format eq 'html') {
179     $self->{form}->{title} = $self->{title};
180     $self->{form}->header();
181     print $self->generate_html_content();
182
183   } elsif ($format eq 'csv') {
184     print qq|content-type: text/plain\n\n|;
185 #     print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
186     $self->generate_csv_content();
187
188   } elsif ($format eq 'pdf') {
189     print qq|content-type: application/pdf\n|;
190     print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
191     $self->generate_pdf_content();
192
193   } else {
194     $self->{form}->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
195   }
196 }
197
198 sub get_visible_columns {
199   my $self   = shift;
200   my $format = shift;
201
202   return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /${format}/i)) } @{ $self->{column_order} };
203 }
204
205 sub prepare_html_content {
206   my $self = shift;
207
208   my ($column, $name, @column_headers);
209
210   my $opts            = $self->{options};
211   my @visible_columns = $self->get_visible_columns('HTML');
212
213   foreach $name (@visible_columns) {
214     $column = $self->{columns}->{$name};
215
216     my $header = {
217       'name'                     => $name,
218       'link'                     => $column->{link},
219       'text'                     => $column->{text},
220       'show_sort_indicator'      => $name eq $opts->{sort_indicator_column},
221       'sort_indicator_direction' => $opts->{sort_indicator_direction},
222     };
223
224     push @column_headers, $header;
225   }
226
227   my ($outer_idx, $inner_idx) = (0, 0);
228   my @rows;
229
230   foreach my $row_set (@{ $self->{data} }) {
231     $outer_idx++;
232
233     foreach my $row (@{ $row_set }) {
234       $inner_idx++;
235
236       my $row_data = {
237         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
238         'outer_idx'     => $outer_idx,
239         'outer_idx_odd' => $outer_idx % 2,
240         'inner_idx'     => $inner_idx,
241       };
242
243       push @rows, $row_data;
244     }
245   }
246
247   my @export_variables;
248   foreach my $key (split m/ +/, $self->{export}->{variable_list}) {
249     push @export_variables, { 'key' => $key, 'value' => $self->{form}->{$key} };
250   }
251
252   my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
253
254   my $variables = {
255     'TITLE'                => $opts->{title},
256     'TOP_INFO_TEXT'        => $opts->{top_info_text},
257     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
258     'BOTTOM_INFO_TEXT'     => $opts->{bottom_info_text},
259     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
260     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
261     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
262     'SHOW_EXPORT_BUTTONS'  => $allow_pdf_export || $opts->{allow_csv_export},
263     'COLUMN_HEADERS'       => \@column_headers,
264     'NUM_COLUMNS'          => scalar @column_headers,
265     'ROWS'                 => \@rows,
266     'EXPORT_VARIABLES'     => \@export_variables,
267     'EXPORT_VARIABLE_LIST' => $self->{export}->{variable_list},
268     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
269   };
270
271   return $variables;
272 }
273
274 sub generate_html_content {
275   my $self      = shift;
276   my $variables = $self->prepare_html_content();
277
278   return $self->{form}->parse_html_template('report_generator/html_report', $variables);
279 }
280
281 sub verify_paper_size {
282   my $self                 = shift;
283   my $requested_paper_size = lc shift;
284   my $default_paper_size   = shift;
285
286   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 letter legal);
287
288   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
289 }
290
291 sub generate_pdf_content {
292   my $self      = shift;
293   my $variables = $self->prepare_html_content();
294   my $form      = $self->{form};
295   my $myconfig  = $self->{myconfig};
296   my $opt       = $self->{options}->{pdf_export};
297
298   my $opt_number     = $opt->{number}                     ? 'number : 1'    : '';
299   my $opt_landscape  = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
300
301   my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
302
303   my $html2ps_config = <<"END"
304 \@html2ps {
305   option {
306     titlepage: 0;
307     hyphenate: 0;
308     colour: 1;
309     ${opt_landscape};
310     ${opt_number};
311   }
312   paper {
313     type: ${opt_paper_size};
314   }
315   break-table: 1;
316 }
317
318 \@page {
319   margin-top:    $opt->{margin_top}cm;
320   margin-left:   $opt->{margin_left}cm;
321   margin-bottom: $opt->{margin_bottom}cm;
322   margin-right:  $opt->{margin_right}cm;
323 }
324
325 BODY {
326   font-family: Helvetica;
327   font-size:   $opt->{font_size}pt;
328 }
329
330 END
331   ;
332
333   my $cfg_file_name = Common::tmpname() . '-html2ps-config';
334   my $cfg_file      = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
335
336   $cfg_file->print($html2ps_config);
337   $cfg_file->close();
338
339   my $html_file_name = Common::tmpname() . '.html';
340   my $html_file      = IO::File->new($html_file_name, 'w');
341
342   if (!$html_file) {
343     unlink $cfg_file_name;
344     $form->error($locale->text('Could not write the temporary HTML file.'));
345   }
346
347   $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
348   $html_file->close();
349
350   my $gs = IO::File->new("\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
351                          "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite - |");
352   if ($gs) {
353     while (my $line = <$gs>) {
354       print $line;
355     }
356     $gs->close();
357     unlink $cfg_file_name, $html_file_name;
358
359   } else {
360     unlink $cfg_file_name, $html_file_name;
361     $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
362   }
363 }
364
365 sub generate_csv_content {
366   my $self = shift;
367
368   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
369   my %valid_escape_chars = ('"' => 1, "'" => 1);
370   my %valid_quote_chars  = ('"' => 1, "'" => 1);
371
372   my $opts        = $self->{options}->{csv_export};
373   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
374   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
375   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
376   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
377
378   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
379
380   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
381                                 'sep_char'    => $sep_char,
382                                 'escape_char' => $escape_char,
383                                 'quote_char'  => $quote_char,
384                                 'eol'         => $eol, });
385
386   my $stdout          = wraphandle(\*STDOUT);
387   my @visible_columns = $self->get_visible_columns('CSV');
388
389   if ($opts->{headers}) {
390     $csv->print($stdout, [ map { $self->{columns}->{$_}->{text} } @visible_columns ]);
391   }
392
393   foreach my $row_set (@{ $self->{data} }) {
394     foreach my $row (@{ $row_set }) {
395       $csv->print($stdout, [ map { $row->{$_}->{data} } @visible_columns ]);
396     }
397   }
398 }
399
400 1;