Berichtsklasse:
[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/csv\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 html_format {
206   my $self  = shift;
207   my $value = shift;
208
209   $value =  $self->{form}->quote_html($value);
210   $value =~ s/\r//g;
211   $value =~ s/\n/<br>/g;
212
213   return $value;
214 }
215
216 sub prepare_html_content {
217   my $self = shift;
218
219   my ($column, $name, @column_headers);
220
221   my $opts            = $self->{options};
222   my @visible_columns = $self->get_visible_columns('HTML');
223
224   foreach $name (@visible_columns) {
225     $column = $self->{columns}->{$name};
226
227     my $header = {
228       'name'                     => $name,
229       'link'                     => $column->{link},
230       'text'                     => $column->{text},
231       'show_sort_indicator'      => $name eq $opts->{sort_indicator_column},
232       'sort_indicator_direction' => $opts->{sort_indicator_direction},
233     };
234
235     push @column_headers, $header;
236   }
237
238   my ($outer_idx, $inner_idx) = (0, 0);
239   my @rows;
240
241   foreach my $row_set (@{ $self->{data} }) {
242     $outer_idx++;
243
244     foreach my $row (@{ $row_set }) {
245       $inner_idx++;
246
247       map { $row->{$_}->{data} = $self->html_format($row->{$_}->{data}) } @visible_columns;
248
249       my $row_data = {
250         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
251         'outer_idx'     => $outer_idx,
252         'outer_idx_odd' => $outer_idx % 2,
253         'inner_idx'     => $inner_idx,
254       };
255
256       push @rows, $row_data;
257     }
258   }
259
260   my @export_variables;
261   foreach my $key (split m/ +/, $self->{export}->{variable_list}) {
262     push @export_variables, { 'key' => $key, 'value' => $self->{form}->{$key} };
263   }
264
265   my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
266
267   my $variables = {
268     'TITLE'                => $opts->{title},
269     'TOP_INFO_TEXT'        => $self->html_format($opts->{top_info_text}),
270     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
271     'BOTTOM_INFO_TEXT'     => $self->html_format($opts->{bottom_info_text}),
272     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
273     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
274     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
275     'SHOW_EXPORT_BUTTONS'  => $allow_pdf_export || $opts->{allow_csv_export},
276     'COLUMN_HEADERS'       => \@column_headers,
277     'NUM_COLUMNS'          => scalar @column_headers,
278     'ROWS'                 => \@rows,
279     'EXPORT_VARIABLES'     => \@export_variables,
280     'EXPORT_VARIABLE_LIST' => $self->{export}->{variable_list},
281     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
282   };
283
284   return $variables;
285 }
286
287 sub generate_html_content {
288   my $self      = shift;
289   my $variables = $self->prepare_html_content();
290
291   return $self->{form}->parse_html_template('report_generator/html_report', $variables);
292 }
293
294 sub verify_paper_size {
295   my $self                 = shift;
296   my $requested_paper_size = lc shift;
297   my $default_paper_size   = shift;
298
299   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 letter legal);
300
301   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
302 }
303
304 sub generate_pdf_content {
305   my $self      = shift;
306   my $variables = $self->prepare_html_content();
307   my $form      = $self->{form};
308   my $myconfig  = $self->{myconfig};
309   my $opt       = $self->{options}->{pdf_export};
310
311   my $opt_number     = $opt->{number}                     ? 'number : 1'    : '';
312   my $opt_landscape  = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
313
314   my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
315
316   my $html2ps_config = <<"END"
317 \@html2ps {
318   option {
319     titlepage: 0;
320     hyphenate: 0;
321     colour: 1;
322     ${opt_landscape};
323     ${opt_number};
324   }
325   paper {
326     type: ${opt_paper_size};
327   }
328   break-table: 1;
329 }
330
331 \@page {
332   margin-top:    $opt->{margin_top}cm;
333   margin-left:   $opt->{margin_left}cm;
334   margin-bottom: $opt->{margin_bottom}cm;
335   margin-right:  $opt->{margin_right}cm;
336 }
337
338 BODY {
339   font-family: Helvetica;
340   font-size:   $opt->{font_size}pt;
341 }
342
343 END
344   ;
345
346   my $cfg_file_name = Common::tmpname() . '-html2ps-config';
347   my $cfg_file      = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
348
349   $cfg_file->print($html2ps_config);
350   $cfg_file->close();
351
352   my $html_file_name = Common::tmpname() . '.html';
353   my $html_file      = IO::File->new($html_file_name, 'w');
354
355   if (!$html_file) {
356     unlink $cfg_file_name;
357     $form->error($locale->text('Could not write the temporary HTML file.'));
358   }
359
360   $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
361   $html_file->close();
362
363   my $gs = IO::File->new("\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
364                          "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite - |");
365   if ($gs) {
366     while (my $line = <$gs>) {
367       print $line;
368     }
369     $gs->close();
370     unlink $cfg_file_name, $html_file_name;
371
372   } else {
373     unlink $cfg_file_name, $html_file_name;
374     $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
375   }
376 }
377
378 sub generate_csv_content {
379   my $self = shift;
380
381   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
382   my %valid_escape_chars = ('"' => 1, "'" => 1);
383   my %valid_quote_chars  = ('"' => 1, "'" => 1);
384
385   my $opts        = $self->{options}->{csv_export};
386   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
387   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
388   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
389   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
390
391   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
392
393   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
394                                 'sep_char'    => $sep_char,
395                                 'escape_char' => $escape_char,
396                                 'quote_char'  => $quote_char,
397                                 'eol'         => $eol, });
398
399   my $stdout          = wraphandle(\*STDOUT);
400   my @visible_columns = $self->get_visible_columns('CSV');
401
402   if ($opts->{headers}) {
403     $csv->print($stdout, [ map { $self->{columns}->{$_}->{text} } @visible_columns ]);
404   }
405
406   foreach my $row_set (@{ $self->{data} }) {
407     foreach my $row (@{ $row_set }) {
408       $csv->print($stdout, [ map { $row->{$_}->{data} } @visible_columns ]);
409     }
410   }
411 }
412
413 1;