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