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