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