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