Reportgenerator: Man kann jetzt auch Trennzeilen einfügen, die in der HTML-Ausgabe...
[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   my $last_row_set;
90
91   while (my $arg = shift) {
92     if ('ARRAY' eq ref $arg) {
93       push @{ $self->{data} }, $arg;
94       $last_row_set = $arg;
95
96     } elsif ('HASH' eq ref $arg) {
97       my $row_set = [ $arg ];
98       push @{ $self->{data} }, $row_set;
99       $last_row_set = $row_set;
100
101     } else {
102       $self->{form}->error('Incorrect usage -- expecting hash or array ref');
103     }
104   }
105
106   return $last_row_set;
107 }
108
109 sub add_separator {
110   my $self = shift;
111
112   push @{ $self->{data} }, { 'type' => 'separator' };
113 }
114
115 sub clear_data {
116   my $self = shift;
117
118   $self->{data} = [];
119 }
120
121 sub set_options {
122   my $self    = shift;
123   my %options = @_;
124
125   map { $self->{options}->{$_} = $options{$_} } keys %options;
126 }
127
128 sub set_options_from_form {
129   my $self     = shift;
130
131   my $form     = $self->{form};
132   my $myconfig = $self->{myconfig};
133
134   foreach my $key (qw(output_format)) {
135     my $full_key = "report_generator_${key}";
136     $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
137   }
138
139   foreach my $format (qw(pdf csv)) {
140     my $opts = $self->{options}->{"${format}_export"};
141     foreach my $key (keys %{ $opts }) {
142       my $full_key = "report_generator_${format}_options_${key}";
143       $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
144     }
145   }
146 }
147
148 sub set_export_options {
149   my $self        = shift;
150
151   $self->{export} = {
152     'nextsub'       => shift,
153     'variable_list' => join(" ", @_),
154   };
155 }
156
157 sub generate_content {
158   my $self   = shift;
159   my $format = lc $self->{options}->{output_format};
160
161   if (!$self->{columns}) {
162     $self->{form}->error('Incorrect usage -- no columns specified');
163   }
164
165   if ($format eq 'html') {
166     return $self->generate_html_content();
167
168   } elsif ($format eq 'csv') {
169     return $self->generate_csv_content();
170
171   } elsif ($format eq 'pdf') {
172     return $self->generate_pdf_content();
173
174   } else {
175     $self->{form}->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
176   }
177 }
178
179 sub generate_with_headers {
180   my $self   = shift;
181   my $format = lc $self->{options}->{output_format};
182
183   if (!$self->{columns}) {
184     $self->{form}->error('Incorrect usage -- no columns specified');
185   }
186
187   my $filename =  $self->{options}->{attachment_basename} || 'report';
188   $filename    =~ s|.*\\||;
189   $filename    =~ s|.*/||;
190
191   if ($format eq 'html') {
192     $self->{form}->{title} = $self->{title};
193     $self->{form}->header();
194     print $self->generate_html_content();
195
196   } elsif ($format eq 'csv') {
197     print qq|content-type: text/csv\n|;
198     print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
199     $self->generate_csv_content();
200
201   } elsif ($format eq 'pdf') {
202     print qq|content-type: application/pdf\n|;
203     print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
204     $self->generate_pdf_content();
205
206   } else {
207     $self->{form}->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
208   }
209 }
210
211 sub get_visible_columns {
212   my $self   = shift;
213   my $format = shift;
214
215   return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /${format}/i)) } @{ $self->{column_order} };
216 }
217
218 sub html_format {
219   my $self  = shift;
220   my $value = shift;
221
222   $value =  $self->{form}->quote_html($value);
223   $value =~ s/\r//g;
224   $value =~ s/\n/<br>/g;
225
226   return $value;
227 }
228
229 sub prepare_html_content {
230   my $self = shift;
231
232   my ($column, $name, @column_headers);
233
234   my $opts            = $self->{options};
235   my @visible_columns = $self->get_visible_columns('HTML');
236
237   foreach $name (@visible_columns) {
238     $column = $self->{columns}->{$name};
239
240     my $header = {
241       'name'                     => $name,
242       'link'                     => $column->{link},
243       'text'                     => $column->{text},
244       'show_sort_indicator'      => $name eq $opts->{sort_indicator_column},
245       'sort_indicator_direction' => $opts->{sort_indicator_direction},
246     };
247
248     push @column_headers, $header;
249   }
250
251   my ($outer_idx, $inner_idx) = (0, 0);
252   my @rows;
253
254   foreach my $row_set (@{ $self->{data} }) {
255     if ('HASH' eq ref $row_set) {
256       my $row_data = {
257         'IS_CONTROL'    => 1,
258         'IS_SEPARATOR'  => $row_set->{type} eq 'separator',
259         'NUM_COLUMNS'   => scalar @visible_columns,
260       };
261
262       push @rows, $row_data;
263
264       next;
265     }
266
267     $outer_idx++;
268
269     foreach my $row (@{ $row_set }) {
270       $inner_idx++;
271
272       map { $row->{$_}->{data} = $self->html_format($row->{$_}->{data}) } @visible_columns;
273
274       my $row_data = {
275         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
276         'outer_idx'     => $outer_idx,
277         'outer_idx_odd' => $outer_idx % 2,
278         'inner_idx'     => $inner_idx,
279       };
280
281       push @rows, $row_data;
282     }
283   }
284
285   my @export_variables;
286   foreach my $key (split m/ +/, $self->{export}->{variable_list}) {
287     push @export_variables, { 'key' => $key, 'value' => $self->{form}->{$key} };
288   }
289
290   my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
291
292   my $variables = {
293     'TITLE'                => $opts->{title},
294     'TOP_INFO_TEXT'        => $self->html_format($opts->{top_info_text}),
295     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
296     'BOTTOM_INFO_TEXT'     => $self->html_format($opts->{bottom_info_text}),
297     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
298     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
299     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
300     'SHOW_EXPORT_BUTTONS'  => $allow_pdf_export || $opts->{allow_csv_export},
301     'COLUMN_HEADERS'       => \@column_headers,
302     'NUM_COLUMNS'          => scalar @column_headers,
303     'ROWS'                 => \@rows,
304     'EXPORT_VARIABLES'     => \@export_variables,
305     'EXPORT_VARIABLE_LIST' => $self->{export}->{variable_list},
306     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
307   };
308
309   return $variables;
310 }
311
312 sub generate_html_content {
313   my $self      = shift;
314   my $variables = $self->prepare_html_content();
315
316   return $self->{form}->parse_html_template('report_generator/html_report', $variables);
317 }
318
319 sub verify_paper_size {
320   my $self                 = shift;
321   my $requested_paper_size = lc shift;
322   my $default_paper_size   = shift;
323
324   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 letter legal);
325
326   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
327 }
328
329 sub generate_pdf_content {
330   my $self      = shift;
331   my $variables = $self->prepare_html_content();
332   my $form      = $self->{form};
333   my $myconfig  = $self->{myconfig};
334   my $opt       = $self->{options}->{pdf_export};
335
336   my $opt_number     = $opt->{number}                     ? 'number : 1'    : '';
337   my $opt_landscape  = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
338
339   my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
340
341   my $html2ps_config = <<"END"
342 \@html2ps {
343   option {
344     titlepage: 0;
345     hyphenate: 0;
346     colour: 1;
347     ${opt_landscape};
348     ${opt_number};
349   }
350   paper {
351     type: ${opt_paper_size};
352   }
353   break-table: 1;
354 }
355
356 \@page {
357   margin-top:    $opt->{margin_top}cm;
358   margin-left:   $opt->{margin_left}cm;
359   margin-bottom: $opt->{margin_bottom}cm;
360   margin-right:  $opt->{margin_right}cm;
361 }
362
363 BODY {
364   font-family: Helvetica;
365   font-size:   $opt->{font_size}pt;
366 }
367
368 END
369   ;
370
371   my $cfg_file_name = Common::tmpname() . '-html2ps-config';
372   my $cfg_file      = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
373
374   $cfg_file->print($html2ps_config);
375   $cfg_file->close();
376
377   my $html_file_name = Common::tmpname() . '.html';
378   my $html_file      = IO::File->new($html_file_name, 'w');
379
380   if (!$html_file) {
381     unlink $cfg_file_name;
382     $form->error($locale->text('Could not write the temporary HTML file.'));
383   }
384
385   $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
386   $html_file->close();
387
388   my $gs = IO::File->new("\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
389                          "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite - |");
390   if ($gs) {
391     while (my $line = <$gs>) {
392       print $line;
393     }
394     $gs->close();
395     unlink $cfg_file_name, $html_file_name;
396
397   } else {
398     unlink $cfg_file_name, $html_file_name;
399     $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
400   }
401 }
402
403 sub generate_csv_content {
404   my $self = shift;
405
406   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
407   my %valid_escape_chars = ('"' => 1, "'" => 1);
408   my %valid_quote_chars  = ('"' => 1, "'" => 1);
409
410   my $opts        = $self->{options}->{csv_export};
411   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
412   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
413   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
414   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
415
416   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
417
418   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
419                                 'sep_char'    => $sep_char,
420                                 'escape_char' => $escape_char,
421                                 'quote_char'  => $quote_char,
422                                 'eol'         => $eol, });
423
424   my $stdout          = wraphandle(\*STDOUT);
425   my @visible_columns = $self->get_visible_columns('CSV');
426
427   if ($opts->{headers}) {
428     $csv->print($stdout, [ map { $self->{columns}->{$_}->{text} } @visible_columns ]);
429   }
430
431   foreach my $row_set (@{ $self->{data} }) {
432     next if ('ARRAY' ne ref $row_set);
433     foreach my $row (@{ $row_set }) {
434       $csv->print($stdout, [ map { $row->{$_}->{data} } @visible_columns ]);
435     }
436   }
437 }
438
439 1;