Report-Generator: Spaltenüberschriften in HTML- und PDF-Ausgaben nicht erneut HTML...
[kivitendo-erp.git] / SL / ReportGenerator.pm
1 package SL::ReportGenerator;
2
3 use IO::Wrap;
4 use List::Util qw(max);
5 use Text::CSV_XS;
6 use Text::Iconv;
7
8 use SL::Form;
9
10 sub new {
11   my $type = shift;
12
13   my $self = { };
14
15   $self->{myconfig} = shift;
16   $self->{form}     = shift;
17
18   $self->{data}     = [];
19   $self->{options}  = {
20     'std_column_visibility' => 0,
21     'output_format'         => 'HTML',
22     'allow_pdf_export'      => 1,
23     'allow_csv_export'      => 1,
24     'pdf_export'            => {
25       'paper_size'          => 'A4',
26       'orientation'         => 'landscape',
27       'font_size'           => '10',
28       'margin_top'          => 1.5,
29       'margin_left'         => 1.5,
30       'margin_bottom'       => 1.5,
31       'margin_right'        => 1.5,
32       'number'              => 1,
33       'print'               => 0,
34       'printer_id'          => 0,
35       'copies'              => 1,
36     },
37     'csv_export'            => {
38       'quote_char'          => '"',
39       'sep_char'            => ';',
40       'escape_char'         => '"',
41       'eol_style'           => 'Unix',
42       'headers'             => 1,
43     },
44   };
45   $self->{export}   = {
46     'nextsub'       => '',
47     'variable_list' => '',
48   };
49
50   $self->{data_present} = 0;
51
52   bless $self, $type;
53
54   $self->set_options(@_) if (@_);
55
56   $self->_init_escaped_strings_map();
57
58   return $self;
59 }
60
61 sub _init_escaped_strings_map {
62   my $self = shift;
63
64   $self->{escaped_strings_map} =
65     ('ä'  => 'ä',
66      'ö'  => 'ö',
67      'ü'  => 'ü',
68      'Ä'  => 'Ä',
69      'Ö'  => 'Ö',
70      'Ü'  => 'Ü',
71      'ß' => 'ß',
72      '>'    => '>',
73      '&lt;'    => '<',
74      '&quot;'  => '"');
75
76   my $iconv = $main::locale->{iconv_iso8859};
77
78   if ($iconv) {
79     map { $self->{escaped_strings_map}->{$_} = $iconv->convert($self->{escaped_strings_map}->{$_}) } keys %{ $self->{escaped_strings_map} };
80   }
81 }
82
83 sub set_columns {
84   my $self    = shift;
85   my %columns = @_;
86
87   $self->{columns} = \%columns;
88
89   foreach my $column (values %{ $self->{columns} }) {
90     $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
91   }
92
93   $self->set_column_order(sort keys %{ $self->{columns} });
94 }
95
96 sub set_column_order {
97   my $self    = shift;
98
99   my $order   = 0;
100   my %columns = map { $order++; ($_, $order) } @_;
101
102   foreach my $column (sort keys %{ $self->{columns} }) {
103     next if $columns{$column};
104
105     $order++;
106     $columns{$column} = $order;
107   }
108
109   $self->{column_order} = [ sort { $columns{$a} <=> $columns{$b} } keys %columns ];
110 }
111
112 sub set_sort_indicator {
113   my $self = shift;
114
115   $self->{options}->{sort_indicator_column}    = shift;
116   $self->{options}->{sort_indicator_direction} = shift;
117 }
118
119 sub add_data {
120   my $self = shift;
121
122   my $last_row_set;
123
124   while (my $arg = shift) {
125     my $row_set;
126
127     if ('ARRAY' eq ref $arg) {
128       $row_set = $arg;
129
130     } elsif ('HASH' eq ref $arg) {
131       $row_set = [ $arg ];
132
133     } else {
134       $self->{form}->error('Incorrect usage -- expecting hash or array ref');
135     }
136
137     my @columns_with_default_alignment = grep { defined $self->{columns}->{$_}->{align} } keys %{ $self->{columns} };
138
139     foreach my $row (@{ $row_set }) {
140       foreach my $column (@columns_with_default_alignment) {
141         $row->{$column}          ||= { };
142         $row->{$column}->{align}   = $self->{columns}->{$column}->{align} unless (defined $row->{$column}->{align});
143       }
144
145       foreach my $field (qw(data link)) {
146         map { $row->{$_}->{$field} = [ $row->{$_}->{$field} ] if (ref $row->{$_}->{$field} ne 'ARRAY') } keys %{ $row };
147       }
148     }
149
150     push @{ $self->{data} }, $row_set;
151     $last_row_set = $row_set;
152
153     $self->{data_present} = 1;
154   }
155
156   return $last_row_set;
157 }
158
159 sub add_separator {
160   my $self = shift;
161
162   push @{ $self->{data} }, { 'type' => 'separator' };
163 }
164
165 sub add_control {
166   my $self = shift;
167   my $data = shift;
168
169   push @{ $self->{data} }, $data;
170 }
171
172 sub clear_data {
173   my $self = shift;
174
175   $self->{data}         = [];
176   $self->{data_present} = 0;
177 }
178
179 sub set_options {
180   my $self    = shift;
181   my %options = @_;
182
183   map { $self->{options}->{$_} = $options{$_} } keys %options;
184 }
185
186 sub set_options_from_form {
187   my $self     = shift;
188
189   my $form     = $self->{form};
190   my $myconfig = $self->{myconfig};
191
192   foreach my $key (qw(output_format)) {
193     my $full_key = "report_generator_${key}";
194     $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
195   }
196
197   foreach my $format (qw(pdf csv)) {
198     my $opts = $self->{options}->{"${format}_export"};
199     foreach my $key (keys %{ $opts }) {
200       my $full_key = "report_generator_${format}_options_${key}";
201       $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
202     }
203   }
204 }
205
206 sub set_export_options {
207   my $self        = shift;
208
209   $self->{export} = {
210     'nextsub'       => shift,
211     'variable_list' => join(" ", @_),
212   };
213 }
214
215 sub get_attachment_basename {
216   my $self     = shift;
217   my $filename =  $self->{options}->{attachment_basename} || 'report';
218   $filename    =~ s|.*\\||;
219   $filename    =~ s|.*/||;
220
221   return $filename;
222 }
223
224 sub generate_with_headers {
225   my $self   = shift;
226   my $format = lc $self->{options}->{output_format};
227   my $form   = $self->{form};
228
229   if (!$self->{columns}) {
230     $form->error('Incorrect usage -- no columns specified');
231   }
232
233   if ($format eq 'html') {
234     my $title      = $form->{title};
235     $form->{title} = $self->{title} if ($self->{title});
236     $form->header();
237     $form->{title} = $title;
238
239     print $self->generate_html_content();
240
241   } elsif ($format eq 'csv') {
242     my $filename = $self->get_attachment_basename();
243     print qq|content-type: text/csv\n|;
244     print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
245     $self->generate_csv_content();
246
247   } elsif ($format eq 'pdf') {
248     $self->generate_pdf_content();
249
250   } else {
251     $form->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
252   }
253 }
254
255 sub get_visible_columns {
256   my $self   = shift;
257   my $format = shift;
258
259   return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /\Q${format}\E/i)) } @{ $self->{column_order} };
260 }
261
262 sub html_format {
263   my $self  = shift;
264   my $value = shift;
265
266   $value =  $self->{form}->quote_html($value);
267   $value =~ s/\r//g;
268   $value =~ s/\n/<br>/g;
269
270   return $value;
271 }
272
273 sub prepare_html_content {
274   my $self = shift;
275
276   my ($column, $name, @column_headers);
277
278   my $opts            = $self->{options};
279   my @visible_columns = $self->get_visible_columns('HTML');
280
281   foreach $name (@visible_columns) {
282     $column = $self->{columns}->{$name};
283
284     my $header = {
285       'name'                     => $name,
286       'link'                     => $column->{link},
287       'text'                     => $column->{text},
288       'show_sort_indicator'      => $name eq $opts->{sort_indicator_column},
289       'sort_indicator_direction' => $opts->{sort_indicator_direction},
290     };
291
292     push @column_headers, $header;
293   }
294
295   my ($outer_idx, $inner_idx) = (0, 0);
296   my $next_border_top;
297   my @rows;
298
299   foreach my $row_set (@{ $self->{data} }) {
300     if ('HASH' eq ref $row_set) {
301       if ($row_set->{type} eq 'separator') {
302         if (! scalar @rows) {
303           $next_border_top = 1;
304         } else {
305           $rows[-1]->{BORDER_BOTTOM} = 1;
306         }
307
308         next;
309       }
310
311       my $row_data = {
312         'IS_CONTROL'      => 1,
313         'IS_COLSPAN_DATA' => $row_set->{type} eq 'colspan_data',
314         'NUM_COLUMNS'     => scalar @visible_columns,
315         'BORDER_TOP'      => $next_border_top,
316         'data'            => $row_set->{data},
317       };
318
319       push @rows, $row_data;
320
321       $next_border_top = 0;
322
323       next;
324     }
325
326     $outer_idx++;
327
328     foreach my $row (@{ $row_set }) {
329       $inner_idx++;
330
331       foreach my $col_name (@visible_columns) {
332         my $col = $row->{$col_name};
333         $col->{CELL_ROWS} = [ ];
334         foreach my $i (0 .. scalar(@{ $col->{data} }) - 1) {
335           push @{ $col->{CELL_ROWS} }, {
336             'data' => $self->html_format($col->{data}->[$i]),
337             'link' => $col->{link}->[$i],
338           };
339         }
340
341         # Force at least a &nbsp; to be displayed so that browsers
342         # will format the table cell (e.g. borders etc).
343         if (!scalar @{ $col->{CELL_ROWS} }) {
344           push @{ $col->{CELL_ROWS} }, { 'data' => '&nbsp;' };
345         } elsif ((1 == scalar @{ $col->{CELL_ROWS} }) && !$col->{CELL_ROWS}->[0]->{data}) {
346           $col->{CELL_ROWS}->[0]->{data} = '&nbsp;';
347         }
348       }
349
350       my $row_data = {
351         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
352         'outer_idx'     => $outer_idx,
353         'outer_idx_odd' => $outer_idx % 2,
354         'inner_idx'     => $inner_idx,
355         'BORDER_TOP'    => $next_border_top,
356       };
357
358       push @rows, $row_data;
359
360       $next_border_top = 0;
361     }
362   }
363
364   my @export_variables;
365   foreach my $key (split m/ +/, $self->{export}->{variable_list}) {
366     push @export_variables, { 'key' => $key, 'value' => $self->{form}->{$key} };
367   }
368
369   my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
370
371   my $variables = {
372     'TITLE'                => $opts->{title},
373     'TOP_INFO_TEXT'        => $self->html_format($opts->{top_info_text}),
374     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
375     'BOTTOM_INFO_TEXT'     => $self->html_format($opts->{bottom_info_text}),
376     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
377     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
378     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
379     'SHOW_EXPORT_BUTTONS'  => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
380     'COLUMN_HEADERS'       => \@column_headers,
381     'NUM_COLUMNS'          => scalar @column_headers,
382     'ROWS'                 => \@rows,
383     'EXPORT_VARIABLES'     => \@export_variables,
384     'EXPORT_VARIABLE_LIST' => $self->{export}->{variable_list},
385     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
386     'DATA_PRESENT'         => $self->{data_present},
387   };
388
389   return $variables;
390 }
391
392 sub generate_html_content {
393   my $self      = shift;
394   my $variables = $self->prepare_html_content();
395
396   return $self->{form}->parse_html_template('report_generator/html_report', $variables);
397 }
398
399 sub verify_paper_size {
400   my $self                 = shift;
401   my $requested_paper_size = lc shift;
402   my $default_paper_size   = shift;
403
404   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 letter legal);
405
406   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
407 }
408
409 sub generate_pdf_content {
410   my $self      = shift;
411   my $variables = $self->prepare_html_content();
412   my $form      = $self->{form};
413   my $myconfig  = $self->{myconfig};
414   my $opt       = $self->{options}->{pdf_export};
415
416   my $opt_number     = $opt->{number}                     ? 'number : 1'    : '';
417   my $opt_landscape  = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
418
419   my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
420
421   my $html2ps_config = <<"END"
422 \@html2ps {
423   option {
424     titlepage: 0;
425     hyphenate: 0;
426     colour: 1;
427     ${opt_landscape};
428     ${opt_number};
429   }
430   paper {
431     type: ${opt_paper_size};
432   }
433   break-table: 1;
434 }
435
436 \@page {
437   margin-top:    $opt->{margin_top}cm;
438   margin-left:   $opt->{margin_left}cm;
439   margin-bottom: $opt->{margin_bottom}cm;
440   margin-right:  $opt->{margin_right}cm;
441 }
442
443 BODY {
444   font-family: Helvetica;
445   font-size:   $opt->{font_size}pt;
446 }
447
448 END
449   ;
450
451   my $printer_command;
452   if ($opt->{print} && $opt->{printer_id}) {
453     $form->{printer_id} = $opt->{printer_id};
454     $form->get_printer_code($myconfig);
455     $printer_command = $form->{printer_command};
456   }
457
458   my $cfg_file_name = Common::tmpname() . '-html2ps-config';
459   my $cfg_file      = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
460
461   $cfg_file->print($html2ps_config);
462   $cfg_file->close();
463
464   my $html_file_name = Common::tmpname() . '.html';
465   my $html_file      = IO::File->new($html_file_name, 'w');
466
467   if (!$html_file) {
468     unlink $cfg_file_name;
469     $form->error($locale->text('Could not write the temporary HTML file.'));
470   }
471
472   $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
473   $html_file->close();
474
475   my $cmdline =
476     "\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
477     "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite -";
478
479   my $gs = IO::File->new("${cmdline} |");
480   if ($gs) {
481     my $content;
482
483     if (!$printer_command) {
484       my $filename = $self->get_attachment_basename();
485       print qq|content-type: application/pdf\n|;
486       print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
487
488       while (my $line = <$gs>) {
489         print $line;
490       }
491
492     } else {
493       while (my $line = <$gs>) {
494         $content .= $line;
495       }
496     }
497
498     $gs->close();
499     unlink $cfg_file_name, $html_file_name;
500
501     if ($printer_command && $content) {
502       foreach my $i (1 .. max $opt->{copies}, 1) {
503         my $printer = IO::File->new("| ${printer_command}");
504         if (!$printer) {
505           $form->error($locale->text('Could not spawn the printer command.'));
506         }
507         $printer->print($content);
508         $printer->close();
509       }
510
511       $form->{report_generator_printed} = 1;
512     }
513
514   } else {
515     unlink $cfg_file_name, $html_file_name;
516     $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
517   }
518 }
519
520 sub unescape_string {
521   my $self = shift;
522   my $text = shift;
523
524   foreach my $key (keys %{ $self->{escaped_strigns_map} }) {
525     $text =~ s/\Q$key\E/$self->{escaped_strings_map}->{$key}/g;
526   }
527
528   $text =~ s/\Q&amp;\E/&/g;
529
530   return $text;
531 }
532
533 sub generate_csv_content {
534   my $self = shift;
535
536   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
537   my %valid_escape_chars = ('"' => 1, "'" => 1);
538   my %valid_quote_chars  = ('"' => 1, "'" => 1);
539
540   my $opts        = $self->{options}->{csv_export};
541   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
542   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
543   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
544   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
545
546   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
547
548   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
549                                 'sep_char'    => $sep_char,
550                                 'escape_char' => $escape_char,
551                                 'quote_char'  => $quote_char,
552                                 'eol'         => $eol, });
553
554   my $stdout          = wraphandle(\*STDOUT);
555   my @visible_columns = $self->get_visible_columns('CSV');
556
557   if ($opts->{headers}) {
558     $csv->print($stdout, [ map { $self->unescape_for_csv($self->{columns}->{$_}->{text}) } @visible_columns ]);
559   }
560
561   foreach my $row_set (@{ $self->{data} }) {
562     next if ('ARRAY' ne ref $row_set);
563     foreach my $row (@{ $row_set }) {
564       my @data;
565       foreach my $col (@visible_columns) {
566         push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
567       }
568       $csv->print($stdout, \@data);
569     }
570   }
571 }
572
573 1;