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