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