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