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