647dcab767d036595463443111aeeb9d60d6d634
[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 use Text::Iconv;
7
8 use SL::Form;
9
10 # Cause locales.pl to parse these files:
11 # parse_html_template('report_generator/html_report')
12
13 sub new {
14   my $type = shift;
15
16   my $self = { };
17
18   $self->{myconfig} = shift;
19   $self->{form}     = shift;
20
21   $self->{data}     = [];
22   $self->{options}  = {
23     'std_column_visibility' => 0,
24     'output_format'         => 'HTML',
25     'allow_pdf_export'      => 1,
26     'allow_csv_export'      => 1,
27     'html_template'         => 'report_generator/html_report',
28     'pdf_export'            => {
29       'paper_size'          => 'a4',
30       'orientation'         => 'landscape',
31       'font_name'           => 'Verdana',
32       'font_size'           => '7',
33       'margin_top'          => 1.5,
34       'margin_left'         => 1.5,
35       'margin_bottom'       => 1.5,
36       'margin_right'        => 1.5,
37       'number'              => 1,
38       'print'               => 0,
39       'printer_id'          => 0,
40       'copies'              => 1,
41     },
42     'csv_export'            => {
43       'quote_char'          => '"',
44       'sep_char'            => ';',
45       'escape_char'         => '"',
46       'eol_style'           => 'Unix',
47       'headers'             => 1,
48     },
49   };
50   $self->{export}   = {
51     'nextsub'       => '',
52     'variable_list' => [],
53   };
54
55   $self->{data_present} = 0;
56
57   bless $self, $type;
58
59   $self->set_options(@_) if (@_);
60
61   return $self;
62 }
63
64 sub set_columns {
65   my $self    = shift;
66   my %columns = @_;
67
68   $self->{columns} = \%columns;
69
70   foreach my $column (values %{ $self->{columns} }) {
71     $column->{visible} = $self->{options}->{std_column_visibility} unless defined $column->{visible};
72   }
73
74   $self->set_column_order(sort keys %{ $self->{columns} });
75 }
76
77 sub set_column_order {
78   my $self    = shift;
79   my %seen;
80   $self->{column_order} = [ grep { !$seen{$_}++ } @_, sort keys %{ $self->{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     my $row_set;
97
98     if ('ARRAY' eq ref $arg) {
99       $row_set = $arg;
100
101     } elsif ('HASH' eq ref $arg) {
102       $row_set = [ $arg ];
103
104     } else {
105       $self->{form}->error('Incorrect usage -- expecting hash or array ref');
106     }
107
108     my @columns_with_default_alignment = grep { defined $self->{columns}->{$_}->{align} } keys %{ $self->{columns} };
109
110     foreach my $row (@{ $row_set }) {
111       foreach my $column (@columns_with_default_alignment) {
112         $row->{$column}          ||= { };
113         $row->{$column}->{align}   = $self->{columns}->{$column}->{align} unless (defined $row->{$column}->{align});
114       }
115
116       foreach my $field (qw(data link)) {
117         map { $row->{$_}->{$field} = [ $row->{$_}->{$field} ] if (ref $row->{$_}->{$field} ne 'ARRAY') } keys %{ $row };
118       }
119     }
120
121     push @{ $self->{data} }, $row_set;
122     $last_row_set = $row_set;
123
124     $self->{data_present} = 1;
125   }
126
127   return $last_row_set;
128 }
129
130 sub add_separator {
131   my $self = shift;
132
133   push @{ $self->{data} }, { 'type' => 'separator' };
134 }
135
136 sub add_control {
137   my $self = shift;
138   my $data = shift;
139
140   push @{ $self->{data} }, $data;
141 }
142
143 sub clear_data {
144   my $self = shift;
145
146   $self->{data}         = [];
147   $self->{data_present} = 0;
148 }
149
150 sub set_options {
151   my $self    = shift;
152   my %options = @_;
153
154   while (my ($key, $value) = each %options) {
155     if ($key eq 'pdf_export') {
156       map { $self->{options}->{pdf_export}->{$_} = $value->{$_} } keys %{ $value };
157     } else {
158       $self->{options}->{$key} = $value;
159     }
160   }
161 }
162
163 sub set_options_from_form {
164   my $self     = shift;
165
166   my $form     = $self->{form};
167   my $myconfig = $self->{myconfig};
168
169   foreach my $key (qw(output_format)) {
170     my $full_key = "report_generator_${key}";
171     $self->{options}->{$key} = $form->{$full_key} if (defined $form->{$full_key});
172   }
173
174   foreach my $format (qw(pdf csv)) {
175     my $opts = $self->{options}->{"${format}_export"};
176     foreach my $key (keys %{ $opts }) {
177       my $full_key = "report_generator_${format}_options_${key}";
178       $opts->{$key} = $key =~ /^margin/ ? $form->parse_amount($myconfig, $form->{$full_key}) : $form->{$full_key};
179     }
180   }
181 }
182
183 sub set_export_options {
184   my $self        = shift;
185
186   $self->{export} = {
187     'nextsub'       => shift,
188     'variable_list' => [ @_ ],
189   };
190 }
191
192 sub get_attachment_basename {
193   my $self     = shift;
194   my $filename =  $self->{options}->{attachment_basename} || 'report';
195   $filename    =~ s|.*\\||;
196   $filename    =~ s|.*/||;
197
198   return $filename;
199 }
200
201 sub generate_with_headers {
202   my $self   = shift;
203   my $format = lc $self->{options}->{output_format};
204   my $form   = $self->{form};
205
206   if (!$self->{columns}) {
207     $form->error('Incorrect usage -- no columns specified');
208   }
209
210   if ($format eq 'html') {
211     my $title      = $form->{title};
212     $form->{title} = $self->{title} if ($self->{title});
213     $form->header();
214     $form->{title} = $title;
215
216     print $self->generate_html_content();
217
218   } elsif ($format eq 'csv') {
219     my $filename = $self->get_attachment_basename();
220     print qq|content-type: text/csv\n|;
221     print qq|content-disposition: attachment; filename=${filename}.csv\n\n|;
222     $self->generate_csv_content();
223
224   } elsif ($format eq 'pdf') {
225     $self->generate_pdf_content();
226
227   } else {
228     $form->error('Incorrect usage -- unknown format (supported are HTML, CSV, PDF)');
229   }
230 }
231
232 sub get_visible_columns {
233   my $self   = shift;
234   my $format = shift;
235
236   return grep { my $c = $self->{columns}->{$_}; $c && $c->{visible} && (($c->{visible} == 1) || ($c->{visible} =~ /\Q${format}\E/i)) } @{ $self->{column_order} };
237 }
238
239 sub html_format {
240   my $self  = shift;
241   my $value = shift;
242
243   $value =  $main::locale->quote_special_chars('HTML', $value);
244   $value =~ s/\r//g;
245   $value =~ s/\n/<br>/g;
246
247   return $value;
248 }
249
250 sub prepare_html_content {
251   my $self = shift;
252
253   my ($column, $name, @column_headers);
254
255   my $opts            = $self->{options};
256   my @visible_columns = $self->get_visible_columns('HTML');
257
258   foreach $name (@visible_columns) {
259     $column = $self->{columns}->{$name};
260
261     my $header = {
262       'name'                     => $name,
263       'link'                     => $column->{link},
264       'text'                     => $column->{text},
265       'show_sort_indicator'      => $name eq $opts->{sort_indicator_column},
266       'sort_indicator_direction' => $opts->{sort_indicator_direction},
267     };
268
269     push @column_headers, $header;
270   }
271
272   my ($outer_idx, $inner_idx) = (0, 0);
273   my $next_border_top;
274   my @rows;
275
276   foreach my $row_set (@{ $self->{data} }) {
277     if ('HASH' eq ref $row_set) {
278       if ($row_set->{type} eq 'separator') {
279         if (! scalar @rows) {
280           $next_border_top = 1;
281         } else {
282           $rows[-1]->{BORDER_BOTTOM} = 1;
283         }
284
285         next;
286       }
287
288       my $row_data = {
289         'IS_CONTROL'      => 1,
290         'IS_COLSPAN_DATA' => $row_set->{type} eq 'colspan_data',
291         'NUM_COLUMNS'     => scalar @visible_columns,
292         'BORDER_TOP'      => $next_border_top,
293         'data'            => $row_set->{data},
294       };
295
296       push @rows, $row_data;
297
298       $next_border_top = 0;
299
300       next;
301     }
302
303     $outer_idx++;
304
305     foreach my $row (@{ $row_set }) {
306       $inner_idx++;
307
308       foreach my $col_name (@visible_columns) {
309         my $col = $row->{$col_name};
310         $col->{CELL_ROWS} = [ ];
311         foreach my $i (0 .. scalar(@{ $col->{data} }) - 1) {
312           push @{ $col->{CELL_ROWS} }, {
313             'data' => $self->html_format($col->{data}->[$i]),
314             'link' => $col->{link}->[$i],
315           };
316         }
317
318         # Force at least a &nbsp; to be displayed so that browsers
319         # will format the table cell (e.g. borders etc).
320         if (!scalar @{ $col->{CELL_ROWS} }) {
321           push @{ $col->{CELL_ROWS} }, { 'data' => '&nbsp;' };
322         } elsif ((1 == scalar @{ $col->{CELL_ROWS} }) && (!defined $col->{CELL_ROWS}->[0]->{data} || ($col->{CELL_ROWS}->[0]->{data} eq ''))) {
323           $col->{CELL_ROWS}->[0]->{data} = '&nbsp;';
324         }
325       }
326
327       my $row_data = {
328         'COLUMNS'       => [ map { $row->{$_} } @visible_columns ],
329         'outer_idx'     => $outer_idx,
330         'outer_idx_odd' => $outer_idx % 2,
331         'inner_idx'     => $inner_idx,
332         'BORDER_TOP'    => $next_border_top,
333       };
334
335       push @rows, $row_data;
336
337       $next_border_top = 0;
338     }
339   }
340
341   my @export_variables = $self->{form}->flatten_variables(@{ $self->{export}->{variable_list} });
342
343   my $allow_pdf_export = $opts->{allow_pdf_export};
344
345   eval { require PDF::API2; require PDF::Table; };
346   $allow_pdf_export |= 1 if (! $@);
347
348   my $variables = {
349     'TITLE'                => $opts->{title},
350     'TOP_INFO_TEXT'        => $self->html_format($opts->{top_info_text}),
351     'RAW_TOP_INFO_TEXT'    => $opts->{raw_top_info_text},
352     'BOTTOM_INFO_TEXT'     => $self->html_format($opts->{bottom_info_text}),
353     'RAW_BOTTOM_INFO_TEXT' => $opts->{raw_bottom_info_text},
354     'ALLOW_PDF_EXPORT'     => $allow_pdf_export,
355     'ALLOW_CSV_EXPORT'     => $opts->{allow_csv_export},
356     'SHOW_EXPORT_BUTTONS'  => ($allow_pdf_export || $opts->{allow_csv_export}) && $self->{data_present},
357     'COLUMN_HEADERS'       => \@column_headers,
358     'NUM_COLUMNS'          => scalar @column_headers,
359     'ROWS'                 => \@rows,
360     'EXPORT_VARIABLES'     => \@export_variables,
361     'EXPORT_VARIABLE_LIST' => join(' ', @{ $self->{export}->{variable_list} }),
362     'EXPORT_NEXTSUB'       => $self->{export}->{nextsub},
363     'DATA_PRESENT'         => $self->{data_present},
364   };
365
366   return $variables;
367 }
368
369 sub generate_html_content {
370   my $self      = shift;
371   my $variables = $self->prepare_html_content();
372
373   return $self->{form}->parse_html_template($self->{options}->{html_template}, $variables);
374 }
375
376 sub _cm2bp {
377   # 1 bp = 1/72 in
378   # 1 in = 2.54 cm
379   return $_[0] * 72 / 2.54;
380 }
381
382 sub render_pdf_with_pdf_api2 {
383   my $self       = shift;
384   my $variables  = $self->prepare_html_content();
385   my $form       = $self->{form};
386   my $myconfig   = $self->{myconfig};
387
388   my $opts       = $self->{options};
389   my $pdfopts    = $opts->{pdf_export};
390
391   my (@data, @column_props, @cell_props);
392
393   my $data_row        = [];
394   my $cell_props_row  = [];
395   my @visible_columns = $self->get_visible_columns('HTML');
396
397   foreach $name (@visible_columns) {
398     $column = $self->{columns}->{$name};
399
400     push @{ $data_row },       $column->{text};
401     push @{ $cell_props_row }, {};
402     push @column_props,        { 'justify' => $column->{align} eq 'right' ? 'right' : 'left' };
403   }
404
405   push @data,       $data_row;
406   push @cell_props, $cell_props_row;
407
408   my $num_columns = scalar @column_props;
409
410   foreach my $row_set (@{ $self->{data} }) {
411     if ('HASH' eq ref $row_set) {
412       if ($row_set->{type} eq 'colspan_data') {
413         push @data, [ $row_set->{data} ];
414
415         $cell_props_row = [];
416         push @cell_props, $cell_props_row;
417
418         foreach (0 .. $num_columns - 1) {
419           push @{ $cell_props_row }, { 'background_color' => '#666666',
420                                        'font_color'       => '#ffffff',
421                                        'colspan'          => $_ == 0 ? -1 : undef, };
422         }
423       }
424       next;
425     }
426
427     foreach my $row (@{ $row_set }) {
428       $data_row = [];
429       push @data, $data_row;
430
431       my $col_idx = 0;
432       foreach my $col_name (@visible_columns) {
433         my $col = $row->{$col_name};
434         push @{ $data_row }, join("\n", @{ $col->{data} });
435
436         $column_props[$col_idx]->{justify} = 'right' if ($col->{align} eq 'right');
437
438         $col_idx++;
439       }
440
441       $cell_props_row = [];
442       push @cell_props, $cell_props_row;
443
444       foreach (0 .. $num_columns - 1) {
445         push @{ $cell_props_row }, { };
446       }
447     }
448   }
449
450   foreach my $i (0 .. scalar(@data) - 1) {
451     my $aref             = $data[$i];
452     my $num_columns_here = scalar @{ $aref };
453
454     if ($num_columns_here < $num_columns) {
455       push @{ $aref }, ('') x ($num_columns - $num_columns_here);
456     } elsif ($num_columns_here > $num_columns) {
457       splice @{ $aref }, $num_columns;
458     }
459   }
460
461   my $papersizes = {
462     'a3'         => [ 842, 1190 ],
463     'a4'         => [ 595,  842 ],
464     'a5'         => [ 420,  595 ],
465     'letter'     => [ 612,  792 ],
466     'legal'      => [ 612, 1008 ],
467   };
468
469   my %supported_fonts = map { $_ => 1 } qw(courier georgia helvetica times verdana);
470
471   my $paper_size  = defined $pdfopts->{paper_size} && defined $papersizes->{lc $pdfopts->{paper_size}} ? lc $pdfopts->{paper_size} : 'a4';
472   my ($paper_width, $paper_height);
473
474   if (lc $pdfopts->{orientation} eq 'landscape') {
475     ($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[1, 0];
476   } else {
477     ($paper_width, $paper_height) = @{$papersizes->{$paper_size}}[0, 1];
478   }
479
480   my $margin_top        = _cm2bp($pdfopts->{margin_top}    || 1.5);
481   my $margin_bottom     = _cm2bp($pdfopts->{margin_bottom} || 1.5);
482   my $margin_left       = _cm2bp($pdfopts->{margin_left}   || 1.5);
483   my $margin_right      = _cm2bp($pdfopts->{margin_right}  || 1.5);
484
485   my $table             = PDF::Table->new();
486   my $pdf               = PDF::API2->new();
487   my $page              = $pdf->page();
488
489   $pdf->mediabox($paper_width, $paper_height);
490
491   my $font              = $pdf->corefont(defined $pdfopts->{font_name} && $supported_fonts{lc $pdfopts->{font_name}} ? ucfirst $pdfopts->{font_name} : 'Verdana',
492                                          '-encoding' => $main::dbcharset || 'ISO-8859-15');
493   my $font_size         = $pdfopts->{font_size} || 7;
494   my $title_font_size   = $font_size + 1;
495   my $padding           = 1;
496   my $font_height       = $font_size + 2 * $padding;
497   my $title_font_height = $font_size + 2 * $padding;
498
499   my $header_height     = 2 * $title_font_height if ($opts->{title});
500   my $footer_height     = 2 * $font_height       if ($pdfopts->{number});
501
502   my $top_text_height   = 0;
503
504   if ($self->{options}->{top_info_text}) {
505     my $top_text     =  $self->{options}->{top_info_text};
506     $top_text        =~ s/\r//g;
507     $top_text        =~ s/\n+$//;
508
509     my @lines        =  split m/\n/, $top_text;
510     $top_text_height =  $font_height * scalar @lines;
511
512     foreach my $line_no (0 .. scalar(@lines) - 1) {
513       my $y_pos    = $paper_height - $margin_top - $header_height - $line_no * $font_height;
514       my $text_obj = $page->text();
515
516       $text_obj->font($font, $font_size);
517       $text_obj->translate($margin_left, $y_pos);
518       $text_obj->text($lines[$line_no]);
519     }
520   }
521
522   $table->table($pdf,
523                 $page,
524                 \@data,
525                 'x'                     => $margin_left,
526                 'w'                     => $paper_width - $margin_left - $margin_right,
527                 'start_y'               => $paper_height - $margin_top                  - $header_height                  - $top_text_height,
528                 'next_y'                => $paper_height - $margin_top                  - $header_height,
529                 'start_h'               => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height - $top_text_height,
530                 'next_h'                => $paper_height - $margin_top - $margin_bottom - $header_height - $footer_height,
531                 'padding'               => 1,
532                 'background_color_odd'  => '#ffffff',
533                 'background_color_even' => '#eeeeee',
534                 'font'                  => $font,
535                 'font_size'             => $font_size,
536                 'font_color'            => '#000000',
537                 'header_props'          => {
538                   'bg_color'            => '#ffffff',
539                   'repeat'              => 1,
540                   'font_color'          => '#000000',
541                 },
542                 'column_props'          => \@column_props,
543                 'cell_props'            => \@cell_props,
544     );
545
546   foreach my $page_num (1..$pdf->pages()) {
547     my $curpage  = $pdf->openpage($page_num);
548
549     if ($pdfopts->{number}) {
550       my $label    = $main::locale->text("Page #1/#2", $page_num, $pdf->pages());
551       my $text_obj = $curpage->text();
552
553       $text_obj->font($font, $font_size);
554       $text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($label) / 2, $margin_bottom);
555       $text_obj->text($label);
556     }
557
558     if ($opts->{title}) {
559       my $text_obj = $curpage->text();
560
561       $text_obj->font($font, $title_font_size);
562       $text_obj->translate(($paper_width - $margin_left - $margin_right) / 2 + $margin_left - $text_obj->advancewidth($opts->{title}) / 2,
563                            $paper_height - $margin_top);
564       $text_obj->text($opts->{title}, '-underline' => 1);
565     }
566   }
567
568   my $content = $pdf->stringify();
569
570   my $printer_command;
571   if ($pdfopts->{print} && $pdfopts->{printer_id}) {
572     $form->{printer_id} = $pdfopts->{printer_id};
573     $form->get_printer_code($myconfig);
574     $printer_command = $form->{printer_command};
575   }
576
577   if ($printer_command) {
578     $self->_print_content('printer_command' => $printer_command,
579                           'content'         => $content,
580                           'copies'          => $pdfopts->{copies});
581     $form->{report_generator_printed} = 1;
582
583   } else {
584     my $filename = $self->get_attachment_basename();
585
586     print qq|content-type: application/pdf\n|;
587     print qq|content-disposition: attachment; filename=${filename}.pdf\n\n|;
588
589     print $content;
590   }
591 }
592
593 sub verify_paper_size {
594   my $self                 = shift;
595   my $requested_paper_size = lc shift;
596   my $default_paper_size   = shift;
597
598   my %allowed_paper_sizes  = map { $_ => 1 } qw(a3 a4 a5 letter legal);
599
600   return $allowed_paper_sizes{$requested_paper_size} ? $requested_paper_size : $default_paper_size;
601 }
602
603 sub _print_content {
604   my $self   = shift;
605   my %params = @_;
606
607   foreach my $i (1 .. max $params{copies}, 1) {
608     my $printer = IO::File->new("| $params{printer_command}");
609     $main::form->error($main::locale->text('Could not spawn the printer command.')) if (!$printer);
610     $printer->print($params{content});
611     $printer->close();
612   }
613 }
614
615 sub generate_pdf_content {
616   my $self = shift;
617
618   eval { require PDF::API2; require PDF::Table; };
619
620   return $self->render_pdf_with_pdf_api2(@_);
621 }
622
623 sub unescape_string {
624   my $self  = shift;
625   my $text  = shift;
626   my $iconv = $main::locale->{iconv};
627
628   $text     = $main::locale->unquote_special_chars('HTML', $text);
629   $text     = $main::locale->{iconv}->convert($text) if ($main::locale->{iconv});
630
631   return $text;
632 }
633
634 sub generate_csv_content {
635   my $self = shift;
636
637   my %valid_sep_chars    = (';' => ';', ',' => ',', ':' => ':', 'TAB' => "\t");
638   my %valid_escape_chars = ('"' => 1, "'" => 1);
639   my %valid_quote_chars  = ('"' => 1, "'" => 1);
640
641   my $opts        = $self->{options}->{csv_export};
642   my $eol         = $opts->{eol_style} eq 'DOS'               ? "\r\n"                              : "\n";
643   my $sep_char    = $valid_sep_chars{$opts->{sep_char}}       ? $valid_sep_chars{$opts->{sep_char}} : ';';
644   my $escape_char = $valid_escape_chars{$opts->{escape_char}} ? $opts->{escape_char}                : '"';
645   my $quote_char  = $valid_quote_chars{$opts->{quote_char}}   ? $opts->{quote_char}                 : '"';
646
647   $escape_char    = $quote_char if ($opts->{escape_char} eq 'QUOTE_CHAR');
648
649   my $csv = Text::CSV_XS->new({ 'binary'      => 1,
650                                 'sep_char'    => $sep_char,
651                                 'escape_char' => $escape_char,
652                                 'quote_char'  => $quote_char,
653                                 'eol'         => $eol, });
654
655   my $stdout          = wraphandle(\*STDOUT);
656   my @visible_columns = $self->get_visible_columns('CSV');
657
658   if ($opts->{headers}) {
659     $csv->print($stdout, [ map { $self->unescape_string($self->{columns}->{$_}->{text}) } @visible_columns ]);
660   }
661
662   foreach my $row_set (@{ $self->{data} }) {
663     next if ('ARRAY' ne ref $row_set);
664     foreach my $row (@{ $row_set }) {
665       my @data;
666       foreach my $col (@visible_columns) {
667         push @data, join($eol, map { s/\r?\n/$eol/g; $_ } @{ $row->{$col}->{data} });
668       }
669       $csv->print($stdout, \@data);
670     }
671   }
672 }
673
674 1;
675
676 __END__
677
678 =head1 NAME
679
680 SL::ReportGenerator.pm: the Lx-Office way of getting data in shape
681
682 =head1 SYNOPSIS
683
684   my $report = SL::ReportGenerator->new(\%myconfig, $form);
685      $report->set_options(%options);                         # optional
686      $report->set_columns(%column_defs);
687      $report->set_sort_indicator($column, $direction);       # optional
688      $report->add_data($row1, $row2, @more_rows);
689      $report->generate_with_headers();
690
691 This creates a report object, sets a few columns, adds some data and generates a standard report. 
692 Sorting of columns will be alphabetic, and options will be set to their defaults.
693 The report will be printed including table headers, html headers and http headers.
694
695 =head1 DESCRIPTION
696
697 Imagine the following scenario:
698 There's a simple form, which loads some data from the database, and needs to print it out. You write a template for it.
699 Then there may be more than one line. You add a loop in the template.
700 Then there are some options made by the user, such as hidden columns. You add more to the template.
701 Then it lacks usability. You want it to be able to sort the data. You add code for that.
702 Then there are too many results, you need pagination, you want to print or export that data..... and so on.
703
704 The ReportGenerator class was designed because this exact scenario happened about half a dozen times in Lx-Office. 
705 It's purpose is to manage all those formating, culling, sorting, and templating. 
706 Which makes it almost as complicated to use as doing the work for yourself.
707
708 =head1 FUNCTIONS
709
710 =over 4
711
712 =item new \%myconfig,$form,%options
713
714 Creates a new ReportGenerator object, sets all given options, and returns it.
715
716 =item set_columns %columns
717
718 Sets the columns available to this report.
719
720 =item set_column_order @columns
721
722 Sets the order of columns. Any columns not present here are appended in alphabetic order.
723
724 =item set_sort_indicator $column,$direction
725
726 Sets sorting ot the table by specifying a column and a direction, where the direction will be evaluated to ascending if true.
727 Note that this is only for displaying. The data has to be presented already sorted.
728
729 =item add_data \@data
730
731 =item add_data \%data
732
733 Adds data to the report. A given hash_ref is interpreted as a single line of data, every array_ref as a collection of lines. 
734 Every line will be expected to be in a kay => value format. Note that the rows have to be already sorted. 
735 ReportGenerator does only colum sorting on its own, and provides links to sorting and visual cue as to which column was sorted by.
736
737 =item add_separator
738
739 Adds a separator line to the report.
740
741 =item add_control \%data
742
743 Adds a control element to the data. Control elements are an experimental feature to add functionality to a report the regular data cannot.
744 Every control element needs to set IS_CONTROL_DATA, in order to be recongnized by the template. 
745 Currently the only control element is a colspan element, which can be used as a mini header further down the report.
746
747 =item clear_data
748
749 Deletes all data filled into the report, but keeps options set.
750
751 =item set_options %options
752
753 Sets options. For an incomplete list of options, see section configuration.
754
755 =item set_options_from_form
756
757 Tries to import options from the $form object given at creation
758
759 =item set_export_options $next_sub,@variable_list
760
761 Sets next_sub and additional variables needed for export.
762
763 =item get_attachment_basename
764
765 Returns the set attachment_basename option, or 'report' if nothing was set. See configuration for the option.
766
767 =item generate_with_headers
768
769 Parses the report, adds headers and prints it out. Headers depend on the option 'output_format', 
770 for example 'HTML' will add proper table headers, html headers and http headers. See configuration for this option.
771
772 =item get_visible_columns $format
773
774 Returns a list of columns that will be visible in the report after considering all options or match the given format.
775
776 =item html_format $value
777
778 Escapes HTML characters in $value and substitutes newlines with '<br>'. Returns the escaped $value.
779
780 =item prepare_html_content $column,$name,@column_headers
781
782 Parses the data, and sets internal data needed for certain output format. Must be called once before the template is invoked. 
783 Should not be called extrenally, since all render and generate functions invoke it anyway.
784  
785 =item generate_html_content
786
787 The html generation function. Is invoked by generate_with_headers.
788
789 =item generate_pdf_content
790
791 The PDF generation function. It is invoked by generate_with_headers, tests whether or not the Perl module PDF::API2 is installed and calls render_pdf_with_pdf_api2 if it is and render_pdf_with_html2ps otherwise.
792
793 =item generate_csv_content
794
795 The CSV generation function. Uses XS_CSV to parse the information into csv.
796
797 =item render_pdf_with_pdf_api2
798
799 PDF render function using the Perl module PDF::API2.
800
801 =item render_pdf_with_html2ps
802
803 PDF render function using the external application html2ps.
804
805 =back
806
807 =head1 CONFIGURATION
808
809 These are known options and their defaults. Options for pdf export and csv export need to be set as a hashref inside the export option.
810
811 =head2 General Options
812
813 =over 4
814
815 =item std_column_visibility
816
817 Standard column visibility. Used if no visibility is set. Use this to save the trouble of enabling every column. Default is no.
818
819 =item output_format
820
821 Output format. Used by generate_with_headers to determine the format. Supported options are HTML, CSV, and PDF. Default is HTML.
822
823 =item allow_pdf_export
824
825 Used to determine if a button for PDF export should be displayed. Default is yes. The PDF button is hidden if neither the Perl module PDF::API2 nor the external applications html2ps and Ghostscript are available regardless of this parameter's value.
826
827 =item allow_csv_export
828
829 Used to determine if a button for CSV export should be displayed. Default is yes.
830
831 =item html_template
832
833 The template to be used for HTML reports. Default is 'report_generator/html_report'.
834
835 =back
836
837 =head2 PDF Options
838
839 =over 4
840
841 =item paper_size
842
843 Paper size. Default is a4. Supported paper sizes are a3, a4, a5, letter and legal.
844
845 =item orientation (landscape)
846
847 Landscape or portrait. Default is landscape.
848
849 =item font_name 
850
851 Default is Verdana. Supported font names are Courier, Georgia, Helvetica, Times and Verdana. This option only affects the rendering with PDF::API2.
852
853 =item font_size
854
855 Default is 7. This option only affects the rendering with PDF::API2.
856
857 =item margin_top
858
859 =item margin_left
860
861 =item margin_bottom
862
863 =item margin_right
864
865 The paper margins in cm. They all default to 1.5.
866
867 =item number
868
869 Set to a true value if the pages should be numbered. Default is 1.
870
871 =item print
872
873 If set then the resulting PDF will be output to a printer. If not it will be downloaded by the user. Default is no.
874
875 =item printer_id
876
877 Default 0.
878
879 =item copies
880
881 Default 1.
882
883 =back
884
885 =head2 CSV Options
886
887 =over 4
888
889 =item quote_char
890
891 Character to enclose entries. Default is double quote (").
892
893 =item sep_char
894
895 Character to separate entries. Default is semicolon (;).
896
897 =item escape_char
898
899 Character to escape the quote_char. Default is double quote (").
900
901 =item eol_style
902
903 End of line style. Default is Unix.
904
905 =item headers
906
907 Include headers? Default is yes.
908
909 =back
910
911 =head1 SEE ALO
912
913 C<Template.pm>
914
915 =head1 MODULE AUTHORS
916
917 Moritz Bunkus E<lt>mbunkus@linet-services.deE<gt>
918
919 L<http://linet-services.de>