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