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