Trennstriche in Berichten als Rahmen der Tabellenzellen zeichnen, nicht als <hr>.
[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
317       my $row_data = {
318         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
319         'outer_idx'     => $outer_idx,
320         'outer_idx_odd' => $outer_idx % 2,
321         'inner_idx'     => $inner_idx,
322         'BORDER_TOP'    => $next_border_top,
323       };
324
325       push @rows, $row_data;
326
327       $next_border_top = 0;
328     }
329   }
330
331   my @export_variables;
332   foreach my $key (split m/ +/, $self->{export}->{variable_list}) {
333     push @export_variables, { 'key' => $key, 'value' => $self->{form}->{$key} };
334   }
335
336   my $allow_pdf_export = $opts->{allow_pdf_export} && (-x $main::html2ps_bin) && (-x $main::ghostscript_bin);
337
338   my $variables = {
339     'TITLE'                => $opts->{title},
340     'TOP_INFO_TEXT'        => $self->html_format($opts->{top_info_text}),
341     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
342     'BOTTOM_INFO_TEXT'     => $self->html_format($opts->{bottom_info_text}),
343     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
344     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
345     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
346     'SHOW_EXPORT_BUTTONS'  => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
347     'COLUMN_HEADERS'       => \@column_headers,
348     'NUM_COLUMNS'          => scalar @column_headers,
349     'ROWS'                 => \@rows,
350     'EXPORT_VARIABLES'     => \@export_variables,
351     'EXPORT_VARIABLE_LIST' => $self->{export}->{variable_list},
352     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
353     'DATA_PRESENT'         => $self->{data_present},
354   };
355
356   return $variables;
357 }
358
359 sub generate_html_content {
360   my $self      = shift;
361   my $variables = $self->prepare_html_content();
362
363   return $self->{form}->parse_html_template('report_generator/html_report', $variables);
364 }
365
366 sub verify_paper_size {
367   my $self                 = shift;
368   my $requested_paper_size = lc shift;
369   my $default_paper_size   = shift;
370
371   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 letter legal);
372
373   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
374 }
375
376 sub generate_pdf_content {
377   my $self      = shift;
378   my $variables = $self->prepare_html_content();
379   my $form      = $self->{form};
380   my $myconfig  = $self->{myconfig};
381   my $opt       = $self->{options}->{pdf_export};
382
383   my $opt_number     = $opt->{number}                     ? 'number : 1'    : '';
384   my $opt_landscape  = $opt->{orientation} eq 'landscape' ? 'landscape : 1' : '';
385
386   my $opt_paper_size = $self->verify_paper_size($opt->{paper_size}, 'a4');
387
388   my $html2ps_config = <<"END"
389 \@html2ps {
390   option {
391     titlepage: 0;
392     hyphenate: 0;
393     colour: 1;
394     ${opt_landscape};
395     ${opt_number};
396   }
397   paper {
398     type: ${opt_paper_size};
399   }
400   break-table: 1;
401 }
402
403 \@page {
404   margin-top:    $opt->{margin_top}cm;
405   margin-left:   $opt->{margin_left}cm;
406   margin-bottom: $opt->{margin_bottom}cm;
407   margin-right:  $opt->{margin_right}cm;
408 }
409
410 BODY {
411   font-family: Helvetica;
412   font-size:   $opt->{font_size}pt;
413 }
414
415 END
416   ;
417
418   my $printer_command;
419   if ($opt->{print} && $opt->{printer_id}) {
420     $form->{printer_id} = $opt->{printer_id};
421     $form->get_printer_code($myconfig);
422     $printer_command = $form->{printer_command};
423   }
424
425   my $cfg_file_name = Common::tmpname() . '-html2ps-config';
426   my $cfg_file      = IO::File->new($cfg_file_name, 'w') || $form->error($locale->text('Could not write the html2ps config file.'));
427
428   $cfg_file->print($html2ps_config);
429   $cfg_file->close();
430
431   my $html_file_name = Common::tmpname() . '.html';
432   my $html_file      = IO::File->new($html_file_name, 'w');
433
434   if (!$html_file) {
435     unlink $cfg_file_name;
436     $form->error($locale->text('Could not write the temporary HTML file.'));
437   }
438
439   $html_file->print($form->parse_html_template('report_generator/pdf_report', $variables));
440   $html_file->close();
441
442   my $cmdline =
443     "\"${main::html2ps_bin}\" -f \"${cfg_file_name}\" \"${html_file_name}\" | " .
444     "\"${main::ghostscript_bin}\" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sPAPERSIZE=${opt_paper_size} -sOutputFile=- -c .setpdfwrite -";
445
446   my $gs = IO::File->new("${cmdline} |");
447   if ($gs) {
448     my $content;
449
450     if (!$printer_command) {
451       my $filename = $self->get_attachment_basename();
452       print qq|content-type: application/pdf\n|;
453       print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
454
455       while (my $line = <$gs>) {
456         print $line;
457       }
458
459     } else {
460       while (my $line = <$gs>) {
461         $content .= $line;
462       }
463     }
464
465     $gs->close();
466     unlink $cfg_file_name, $html_file_name;
467
468     if ($printer_command && $content) {
469       foreach my $i (1 .. max $opt->{copies}, 1) {
470         my $printer = IO::File->new("| ${printer_command}");
471         if (!$printer) {
472           $form->error($locale->text('Could not spawn the printer command.'));
473         }
474         $printer->print($content);
475         $printer->close();
476       }
477
478       $form->{report_generator_printed} = 1;
479     }
480
481   } else {
482     unlink $cfg_file_name, $html_file_name;
483     $form->error($locale->text('Could not spawn html2ps or GhostScript.'));
484   }
485 }
486
487 sub generate_csv_content {
488   my $self = shift;
489
490   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
491   my %valid_escape_chars = ('"' => 1, "'" => 1);
492   my %valid_quote_chars  = ('"' => 1, "'" => 1);
493
494   my $opts        = $self->{options}->{csv_export};
495   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
496   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
497   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
498   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
499
500   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
501
502   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
503                                 'sep_char'    => $sep_char,
504                                 'escape_char' => $escape_char,
505                                 'quote_char'  => $quote_char,
506                                 'eol'         => $eol, });
507
508   my $stdout          = wraphandle(\*STDOUT);
509   my @visible_columns = $self->get_visible_columns('CSV');
510
511   if ($opts->{headers}) {
512     $csv->print($stdout, [ map { $self->{columns}->{$_}->{text} } @visible_columns ]);
513   }
514
515   foreach my $row_set (@{ $self->{data} }) {
516     next if ('ARRAY' ne ref $row_set);
517     foreach my $row (@{ $row_set }) {
518       my @data;
519       foreach my $col (@visible_columns) {
520         push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
521       }
522       $csv->print($stdout, \@data);
523     }
524   }
525 }
526
527 1;