]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/reporter/clark-kent.pl
320ee8c5c90ed2aa332a5aba0708c618d1fdbd8f
[Evergreen.git] / Open-ILS / src / reporter / clark-kent.pl
1 #!/usr/bin/perl
2 # vim:ts=4:noet:
3
4 use strict;
5 use DBI;
6 use FileHandle;
7 use XML::LibXML;
8 use Getopt::Long;
9 use DateTime;
10 use DateTime::Format::ISO8601;
11 use Data::Dumper;
12 use Text::CSV_XS;
13 use Excel::Writer::XLSX;
14 use OpenSRF::EX qw/:try/;
15 use OpenSRF::Utils qw/:daemon/;
16 use OpenSRF::Utils::JSON;
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use OpenSRF::System;
19 use OpenSRF::AppSession;
20 use OpenSRF::Utils::SettingsClient;
21 use OpenILS::Reporter::SQLBuilder;
22 use POSIX;
23 use GD::Graph::pie;
24 use GD::Graph::bars3d;
25 use GD::Graph::lines3d;
26 use Tie::IxHash;
27 use Email::Send;
28
29 use open ':utf8';
30
31
32 my ($config, $sleep_interval, $lockfile, $daemon) = ('SYSCONFDIR/opensrf_core.xml', 10, '/tmp/reporter-LOCK');
33
34 my $opt_count;
35 my $opt_max_rows_for_charts;
36 my $opt_statement_timeout;
37 my $opt_resultset_limit;
38
39 GetOptions(
40         "daemon"        => \$daemon,
41         "sleep=i"       => \$sleep_interval,
42         "concurrency=i" => \$opt_count,
43         "max-rows-for-charts=i" => \$opt_max_rows_for_charts,
44         "resultset-limit=i" => \$opt_resultset_limit,
45         "statement-timeout=i" => \$opt_statement_timeout,
46         "bootstrap|boostrap=s"  => \$config,
47         "lockfile=s"    => \$lockfile,
48 );
49
50 if (-e $lockfile) {
51         die "I seem to be running already. If not, remove $lockfile and try again\n";
52 }
53
54 OpenSRF::System->bootstrap_client( config_file => $config );
55
56 my (%data_db, %state_db);
57
58 my $sc = OpenSRF::Utils::SettingsClient->new;
59
60 $data_db{db_driver} = $sc->config_value( reporter => setup => database => 'driver' );
61 $data_db{db_host}   = $sc->config_value( reporter => setup => database => 'host' );
62 $data_db{db_port}   = $sc->config_value( reporter => setup => database => 'port' );
63 $data_db{db_name}   = $sc->config_value( reporter => setup => database => 'db' );
64 if (!$data_db{db_name}) {
65     $data_db{db_name} = $sc->config_value( reporter => setup => database => 'name' );
66     print STDERR "WARN: <database><name> is a deprecated setting for database name. For future compatibility, you should use <database><db> instead." if $data_db{db_name}; 
67 }
68 $data_db{db_user}   = $sc->config_value( reporter => setup => database => 'user' );
69 $data_db{db_pw}     = $sc->config_value( reporter => setup => database => 'pw' );
70 $data_db{db_app}    = $sc->config_value( reporter => setup => database => 'application_name' );
71
72
73
74 # Fetch the optional state database connection info
75 $state_db{db_driver} = $sc->config_value( reporter => setup => state_store => 'driver' ) || $data_db{db_driver};
76 $state_db{db_host}   = $sc->config_value( reporter => setup => state_store => 'host'   ) || $data_db{db_host};
77 $state_db{db_port}   = $sc->config_value( reporter => setup => state_store => 'port'   ) || $data_db{db_port};
78 $state_db{db_name}   = $sc->config_value( reporter => setup => state_store => 'db'     );
79 if (!$state_db{db_name}) {
80     $state_db{db_name} = $sc->config_value( reporter => setup => state_store => 'name' ) || $data_db{db_name};
81 }
82 $state_db{db_user}   = $sc->config_value( reporter => setup => state_store => 'user'   ) || $data_db{db_user};
83 $state_db{db_pw}     = $sc->config_value( reporter => setup => state_store => 'pw'     ) || $data_db{db_pw};
84 $state_db{db_app}    = $sc->config_value( reporter => setup => state_store => 'application_name' )
85                          || $data_db{db_app};
86
87
88 die "Unable to retrieve database connection information from the settings server"
89     unless ($state_db{db_driver} && $state_db{db_host} && $state_db{db_port} && $state_db{db_name} && $state_db{db_user} &&
90         $data_db{db_driver} && $data_db{db_host} && $data_db{db_port} && $data_db{db_name} && $data_db{db_user});
91
92 my $email_server     = $sc->config_value( email_notify => 'smtp_server' );
93 my $email_sender     = $sc->config_value( email_notify => 'sender_address' );
94 my $success_template = $sc->config_value( reporter => setup => files => 'success_template' );
95 my $fail_template    = $sc->config_value( reporter => setup => files => 'fail_template' );
96 my $output_base      = $sc->config_value( reporter => setup => files => 'output_base' );
97 my $base_uri         = $sc->config_value( reporter => setup => 'base_uri' );
98
99 my $state_dsn = "dbi:" . $state_db{db_driver} . ":dbname=" . $state_db{db_name} .';host=' . $state_db{db_host} . ';port=' . $state_db{db_port};
100 $state_dsn .= ";application_name='$state_db{db_app}'" if $state_db{db_app};
101 my $data_dsn  = "dbi:" .  $data_db{db_driver} . ":dbname=" .  $data_db{db_name} .';host=' .  $data_db{db_host} . ';port=' .  $data_db{db_port};
102 $data_dsn .= ";application_name='$data_db{db_app}'" if $data_db{db_app};
103
104 my $count               = $opt_count //
105                           $sc->config_value( reporter => setup => 'parallel' ) //
106                           1;
107 $count = 1 unless $count =~ /^\d+$/ && $count > 0;
108 my $statement_timeout   = $opt_statement_timeout //
109                           $sc->config_value( reporter => setup => 'statement_timeout' ) //
110                           60;
111 $statement_timeout = 60 unless $statement_timeout =~ /^\d+$/;
112 my $max_rows_for_charts = $opt_max_rows_for_charts //
113                           $sc->config_value( reporter => setup => 'max_rows_for_charts' ) //
114                           1000;
115 $max_rows_for_charts = 1000 unless $max_rows_for_charts =~ /^\d+$/;
116 my $resultset_limit     = $opt_resultset_limit //
117                           $sc->config_value( reporter => setup => 'resultset_limit' ) //
118                           0;
119 $resultset_limit = 0 unless $resultset_limit =~ /^\d+$/; # 0 means no limit
120
121 # What follows is an emperically-derived magic number; if
122 # the row count is larger than this, the table-sorting JavaScript
123 # won't be loaded to excessive churn when viewing HTML reports
124 # in the staff client or web browser.
125 my $sortable_limit = 10000;
126
127 my ($dbh,$running,$sth,@reports,$run, $current_time);
128
129 if ($daemon) {
130         daemonize("Clark Kent, waiting for trouble");
131         open(F, ">$lockfile") or die "Cannot write lockfile '$lockfile'";
132         print F $$;
133         close F;
134 }
135
136
137 DAEMON:
138
139 $dbh = DBI->connect(
140         $state_dsn,
141         $state_db{db_user},
142         $state_db{db_pw},
143         { AutoCommit => 1,
144           pg_expand_array => 0,
145           pg_enable_utf8 => 1,
146           RaiseError => 1
147         }
148 );
149
150 $current_time = DateTime->from_epoch( epoch => time() )->strftime('%FT%T%z');
151
152 # make sure we're not already running $count reports
153 ($running) = $dbh->selectrow_array(<<SQL);
154 SELECT  count(*)
155   FROM  reporter.schedule
156   WHERE start_time IS NOT NULL AND complete_time IS NULL;
157 SQL
158
159 if ($count <= $running) {
160         if ($daemon) {
161                 $dbh->disconnect;
162                 sleep 1;
163                 POSIX::waitpid( -1, POSIX::WNOHANG );
164                 sleep $sleep_interval;
165                 goto DAEMON;
166         }
167         print "Already running maximum ($running) concurrent reports\n";
168         exit 1;
169 }
170
171 # if we have some open slots then generate the sql
172 $run = $count - $running;
173
174 $sth = $dbh->prepare(<<SQL);
175 SELECT  *
176   FROM  reporter.schedule
177   WHERE start_time IS NULL AND run_time < NOW()
178   ORDER BY run_time
179   LIMIT $run;
180 SQL
181
182 $sth->execute;
183
184 @reports = ();
185 while (my $r = $sth->fetchrow_hashref) {
186         my $s3 = $dbh->selectrow_hashref(<<"    SQL", {}, $r->{report});
187                 SELECT * FROM reporter.report WHERE id = ?;
188         SQL
189
190         my $s2 = $dbh->selectrow_hashref(<<"    SQL", {}, $s3->{template});
191                 SELECT * FROM reporter.template WHERE id = ?;
192         SQL
193
194         $s3->{template} = $s2;
195         $r->{report} = $s3;
196
197         my $b = OpenILS::Reporter::SQLBuilder->new;
198         my $report_data = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{data} );
199         $b->register_params( $report_data );
200
201         $r->{resultset} = $b->parse_report( OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} ) );
202         $r->{resultset}->set_do_rollup($report_data->{__do_rollup}) if $report_data->{__do_rollup};
203         $r->{resultset}->set_pivot_data($report_data->{__pivot_data}) if $report_data->{__pivot_data};
204         $r->{resultset}->set_pivot_label($report_data->{__pivot_label}) if $report_data->{__pivot_label};
205         $r->{resultset}->set_pivot_default($report_data->{__pivot_default}) if $report_data->{__pivot_default};
206         $r->{resultset}->relative_time($r->{run_time});
207         $r->{resultset}->resultset_limit($resultset_limit) if $resultset_limit;
208         push @reports, $r;
209 }
210
211 $sth->finish;
212
213 $dbh->disconnect;
214
215 # Now we spawn the report runners
216
217 for my $r ( @reports ) {
218         next if (safe_fork());
219
220         # This is the child (runner) process;
221         daemonize("Clark Kent reporting: $r->{report}->{name}");
222
223         my $state_dbh = DBI->connect(
224                 $state_dsn,
225                 $state_db{db_user},
226                 $state_db{db_pw},
227                 { AutoCommit => 1,
228                   pg_expand_array => 0,
229                   pg_enable_utf8 => 1,
230                   RaiseError => 1
231                 }
232         );
233
234         my $data_dbh = DBI->connect(
235                 $data_dsn,
236                 $data_db{db_user},
237                 $data_db{db_pw},
238                 { AutoCommit => 1,
239                   pg_expand_array => 0,
240                   pg_enable_utf8 => 1,
241                   RaiseError => 1
242                 }
243         );
244         $data_dbh->do('SET statement_timeout = ?', {}, ($statement_timeout * 60 * 1000));
245
246         try {
247                 $state_dbh->do(<<'              SQL',{}, $r->{id});
248                         UPDATE  reporter.schedule
249                           SET   start_time = now()
250                           WHERE id = ?;
251                 SQL
252
253             $logger->debug('Report SQL: ' . $r->{resultset}->toSQL);
254                 $sth = $data_dbh->prepare($r->{resultset}->toSQL);
255
256                 $sth->execute;
257                 $r->{data} = $sth->fetchall_arrayref;
258
259                 $r->{column_labels} = [$r->{resultset}->column_label_list];
260
261                 if ($r->{resultset}->pivot_data && $r->{resultset}->pivot_label) {
262                         my @labels = $r->{resultset}->column_label_list;
263                         my $newdata = pivot_data(
264                                 { columns => $r->{column_labels}, data => $r->{data}},
265                                 $r->{resultset}->pivot_label,
266                                 $r->{resultset}->pivot_data,
267                                 $r->{resultset}->pivot_default
268                         );
269
270                         $r->{column_labels} = $newdata->{columns};
271                         $r->{data} = $newdata->{data};
272                         $r->{group_by_list} = $newdata->{group_by_list};
273                 } else {
274                         $r->{group_by_list} = [$r->{resultset}->group_by_list(0)];
275                 }
276
277                 my $s2 = $r->{report}->{template}->{id};
278                 my $s3 = $r->{report}->{id};
279                 my $output = $r->{id};
280
281                 mkdir($output_base);
282                 mkdir("$output_base/$s2");
283                 mkdir("$output_base/$s2/$s3");
284                 mkdir("$output_base/$s2/$s3/$output");
285         
286                 my $output_dir = "$output_base/$s2/$s3/$output";
287
288                 if ( $r->{csv_format} ) {
289                         build_csv("$output_dir/report-data.csv", $r);
290                 }
291
292                 if ( $r->{excel_format} ) {
293                         build_excel("$output_dir/report-data.xlsx", $r);
294                 }
295
296                 build_html("$output_dir/report-data.html", $r);
297
298                 $state_dbh->begin_work;
299
300                 if ($r->{report}->{recur} ) {
301                         my $sql = <<'                   SQL';
302                                 INSERT INTO reporter.schedule (
303                                                 report,
304                                                 folder,
305                                                 runner,
306                                                 run_time,
307                                                 email,
308                                                 csv_format,
309                                                 excel_format,
310                                                 html_format,
311                                                 chart_pie,
312                                                 chart_bar,
313                                                 chart_line )
314                                         VALUES ( ?, ?, ?, ?::TIMESTAMPTZ + ?, ?, ?, ?, ?, ?, ?, ? );
315                         SQL
316
317                         $state_dbh->do(
318                                 $sql,
319                                 {},
320                                 $r->{report}->{id},
321                                 $r->{folder},
322                                 $r->{runner},
323                                 $r->{run_time},
324                                 $r->{report}->{recurrence},
325                                 $r->{email},
326                                 $r->{csv_format},
327                                 $r->{excel_format},
328                                 $r->{html_format},
329                                 $r->{chart_pie},
330                                 $r->{chart_bar},
331                                 $r->{chart_line},
332                         );
333                 }
334
335                 $state_dbh->do(<<'              SQL',{}, $r->{id});
336                         UPDATE  reporter.schedule
337                           SET   complete_time = now()
338                           WHERE id = ?;
339                 SQL
340
341                 $state_dbh->commit;
342
343                 my $new_r = $state_dbh->selectrow_hashref(<<"           SQL", {}, $r->{id});
344                         SELECT * FROM reporter.schedule WHERE id = ?;
345                 SQL
346
347                 $r->{start_time}    = $new_r->{start_time};
348                 $r->{complete_time} = $new_r->{complete_time};
349
350                 if ($r->{email}) {
351                         send_success($r);
352                 }
353
354         } otherwise {
355                 my $e = shift;
356                 $r->{error_text} = ''.$e;
357                 if (!$state_dbh->{AutoCommit}) {
358                         $state_dbh->rollback;
359                 }
360                 $state_dbh->do(<<'              SQL',{}, $e, $r->{id});
361                         UPDATE  reporter.schedule
362                           SET   error_text = ?,
363                                 complete_time = now(),
364                                 error_code = 1
365                           WHERE id = ?;
366                 SQL
367
368                 my $new_r = $state_dbh->selectrow_hashref(<<"           SQL", {}, $r->{id});
369                         SELECT * FROM reporter.schedule WHERE id = ?;
370                 SQL
371
372                 $r->{error_text}    = $new_r->{error_text};
373                 $r->{complete_time} = $new_r->{complete_time};
374
375                 if ($r->{email}) {
376                         send_fail($r);
377                 }
378
379         };
380
381         $state_dbh->disconnect;
382         $data_dbh->disconnect;
383
384         exit; # leave the child
385 }
386
387 if ($daemon) {
388         sleep 1;
389         POSIX::waitpid( -1, POSIX::WNOHANG );
390         sleep $sleep_interval;
391         goto DAEMON;
392 }
393
394 #-------------------------------------------------------------------
395
396 sub send_success {
397         my $r = shift;
398         open F, $success_template or die "Cannot read '$success_template'";
399         my $tmpl = join('',<F>);
400         close F;
401
402         my $url = $base_uri . '/' .
403                 $r->{report}->{template}->{id} . '/' .
404                 $r->{report}->{id} . '/' .
405                 $r->{id} . '/report-data.html';
406
407         $tmpl =~ s/{TO}/$r->{email}/smog;
408         $tmpl =~ s/{FROM}/$email_sender/smog;
409         $tmpl =~ s/{REPLY_TO}/$email_sender/smog;
410         $tmpl =~ s/{REPORT_NAME}/$r->{report}->{name} -- $r->{report}->{template}->{name}/smog;
411         $tmpl =~ s/{RUN_TIME}/$r->{run_time}/smog;
412         $tmpl =~ s/{COMPLETE_TIME}/$r->{complete_time}/smog;
413         $tmpl =~ s/{OUTPUT_URL}/$url/smog;
414
415         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
416         if ($$tdata{version} >= 4) {
417                 $tmpl =~ s/{EXTERNAL_URL}/$$tdata{doc_url}/smog;
418         }
419
420         my $sender = Email::Send->new({mailer => 'SMTP'});
421         $sender->mailer_args([Host => $email_server]);
422         $sender->send($tmpl);
423 }
424
425 sub send_fail {
426         my $r = shift;
427         open F, $fail_template or die "Cannot read '$fail_template'";
428         my $tmpl = join('',<F>);
429         close F;
430
431         my $sql = $r->{resultset}->toSQL;
432
433         $tmpl =~ s/{TO}/$r->{email}/smog;
434         $tmpl =~ s/{FROM}/$email_sender/smog;
435         $tmpl =~ s/{REPLY_TO}/$email_sender/smog;
436         $tmpl =~ s/{REPORT_NAME}/$r->{report}->{name} -- $r->{report}->{template}->{name}/smog;
437         $tmpl =~ s/{RUN_TIME}/$r->{run_time}/smog;
438         $tmpl =~ s/{ERROR_TEXT}/$r->{error_text}/smog;
439         $tmpl =~ s/{SQL}/$sql/smog;
440
441         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
442         if ($$tdata{version} >= 4) {
443                 $tmpl =~ s/{EXTERNAL_URL}/$$tdata{doc_url}/smog;
444         }
445
446         my $sender = Email::Send->new({mailer => 'SMTP'});
447         $sender->mailer_args([Host => $email_server]);
448         $sender->send($tmpl);
449 }
450
451 sub build_csv {
452         my $file = shift;
453         my $r = shift;
454
455         my $csv = Text::CSV_XS->new({ always_quote => 1, eol => "\015\012" });
456
457         return unless ($csv);
458         
459         my $f = new FileHandle (">$file") or die "Cannot write to '$file'";
460
461         $csv->print($f, $r->{column_labels});
462         $csv->print($f, $_) for (@{$r->{data}});
463
464         $f->close;
465 }
466 sub build_excel {
467         my $file = shift;
468         my $r = shift;
469         my $xls = Excel::Writer::XLSX->new($file);
470
471         my $sheetname = substr($r->{report}->{name},0,30);
472         $sheetname =~ s/\W/_/gos;
473         
474         my $sheet = $xls->add_worksheet($sheetname);
475         # don't try to write formulas, just write anything that starts with = as a text cell
476         $sheet->add_write_handler(qr/^=/, sub { return shift->write_string(@_); } );
477
478         $sheet->write_row('A1', $r->{column_labels});
479
480         $sheet->write_col('A2', $r->{data});
481
482         $xls->close;
483 }
484
485 sub build_html {
486         my $file = shift;
487         my $r = shift;
488
489         my $index = new FileHandle (">$file") or die "Cannot write to '$file'";
490
491         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
492         
493         # index header
494         print $index <<"        HEADER";
495 <html>
496         <head>
497                 <meta charset='utf-8'>
498                 <title>$$r{report}{name}</title>
499                 <style>
500                         table { border-collapse: collapse; }
501                         th { background-color: lightgray; }
502                         td,th { border: solid black 1px; }
503                         * { font-family: sans-serif; font-size: 10px; }
504                         .dim { color: lightblue; }
505                 </style>
506         </head>
507         <body>
508                 <center>
509                 <h2><u>$$r{report}{name}</u></h2>
510                 $$r{report}{description}<br/>
511         HEADER
512
513         if ($$tdata{version} >= 4 and $$tdata{doc_url}) {
514                 print $index "<a target='_blank' href='$$tdata{doc_url}'>External template documentation</a><br/>";
515         }
516
517         print $index "<br/><br/>";
518
519         my @links;
520
521     my $br4 = '<br/>' x 4;
522         # add a link to the raw output html
523         push @links, "<a href='report-data.html.raw.html'>Tabular Output</a>" if ($r->{html_format});
524
525         # add a link to the CSV output
526         push @links, "<a href='report-data.xlsx'>Excel Output</a>" if ($r->{excel_format});
527
528         # add a link to the CSV output
529         push @links, "<a href='report-data.csv'>CSV Output</a>" if ($r->{csv_format});
530
531         # debugging output
532         push @links, "<a class='dim' href='report-data.html.debug.html'>Debugging Info</a>";
533
534         my $debug = new FileHandle (">$file.debug.html") or die "Cannot write to '$file.debug.html'";
535         print $debug "<html><head><meta charset='utf-8'><title>DEBUG: $$r{report}{name}</title></head><body>";
536
537         {       no warnings;
538                 if ($$tdata{version} >= 4 and $$tdata{doc_url}) {
539                         print $debug "<b><a target='_blank' href='$$tdata{doc_url}'>External template documentation</a></b><br/><a href='report-data.html'>Back to output index</a><hr/>";
540                 }
541
542                 print $debug '<h1>Generated SQL</h1><pre>' . $r->{resultset}->toSQL() . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
543                 print $debug '<h1>Template</h1><pre>' . Dumper( $r->{report}->{template} ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
544                 print $debug '<h1>Template Data</h1><pre>' . Dumper( $tdata ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
545                 print $debug '<h1>Report Parameter</h1><pre>' . Dumper( $r->{report} ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
546                 print $debug '<h1>Report Parameter Data</h1><pre>' . Dumper( $tdata ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
547                 print $debug '<h1>Report Run Time</h1><pre>' . $r->{resultset}->relative_time . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
548                 print $debug '<h1>OpenILS::Reporter::SQLBuilder::ResultSet Object</h1><pre>' . Dumper( $r->{resultset} ) . "</pre><a href='report-data.html'>Back to output index</a>";
549         }
550
551         print $debug '</body></html>';
552
553         $debug->close;
554
555         print $index join(' -- ', @links);
556         print $index "$br4</center>";
557
558         if ($r->{html_format}) {
559                 # create the raw output html file
560                 my $raw = new FileHandle (">$file.raw.html") or die "Cannot write to '$file.raw.html'";
561                 print $raw "<html><head><meta charset='utf-8'><title>$$r{report}{name}</title>";
562
563                 print $raw <<'          CSS';
564                         <style>
565                                 table { border-collapse: collapse; }
566                                 th { background-color: lightgray; }
567                                 td,th { border: solid black 1px; }
568                                 * { font-family: sans-serif; }
569                         </style>
570                         <link rel="stylesheet" href="/js/sortable/sortable-theme-minimal.css" />
571                 CSS
572
573                 print $raw "</head><body><a href='report-data.html'>Back to output index</a><br/><table class='sortable-theme-minimal' data-sortable>";
574
575                 {       no warnings;
576                         print $raw "<thead><tr><th>".join('</th><th>', @{$r->{column_labels}})."</th></tr></thead>\n<tbody>";
577                         print $raw "<tr><td>".join('</td><td>', @$_)."</td></tr>\n" for (@{$r->{data}});
578                 }
579
580                 print $raw '</tbody></table>';
581                 if (@{ $r->{data} } <= $sortable_limit) {
582                         print $raw '<script src="/js/sortable/sortable.min.js"></script>';
583                 }
584                 print $raw '</body></html>';
585         
586                 $raw->close;
587         }
588
589         # Time for a pie chart
590         if ($r->{chart_pie}) {
591                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
592                         print $index "<strong>Report output has too many rows to make a pie chart</strong>$br4";
593                 } else {
594                         my $pics = draw_pie($r, $file);
595                         for my $pic (@$pics) {
596                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
597                         }
598                 }
599         }
600
601         print $index $br4;
602         # Time for a bar chart
603         if ($r->{chart_bar}) {
604                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
605                         print $index "<strong>Report output has too many rows to make a bar chart</strong>$br4";
606                 } else {
607                         my $pics = draw_bars($r, $file);
608                         for my $pic (@$pics) {
609                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
610                         }
611                 }
612         }
613
614         print $index $br4;
615         # Time for a bar chart
616         if ($r->{chart_line}) {
617                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
618                         print $index "<strong>Report output has too many rows to make a line chart</strong>$br4";
619                 } else {
620                         my $pics = draw_lines($r, $file);
621                         for my $pic (@$pics) {
622                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
623                         }
624             }
625         }
626
627         # and that's it!
628         print $index '</body></html>';
629         
630         $index->close;
631 }
632
633 sub draw_pie {
634         my $r = shift;
635         my $file = shift;
636
637         my $data = $r->{data};
638
639         my @groups = @{ $r->{group_by_list} };
640         
641         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
642         delete @values[@groups];
643
644         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
645         
646         my @pics;
647         for my $vcol (@values) {
648                 next unless (defined $vcol);
649
650                 my @pic_data = ([],[]);
651                 for my $row (@$data) {
652                         next if (!defined($$row[$vcol]) || $$row[$vcol] == 0);
653                         my $val = $$row[$vcol];
654                         push @{$pic_data[0]}, join(" -- ", @$row[@groups])." ($val)";
655                         push @{$pic_data[1]}, $val;
656                 }
657
658                 next unless (@{$pic_data[0]});
659
660                 my $size = 300;
661                 my $split = int(scalar(@{$pic_data[0]}) / $size);
662                 my $last = scalar(@{$pic_data[0]}) % $size;
663
664                 for my $sub_graph (0 .. $split) {
665                         
666                         if ($sub_graph == $split) {
667                                 $size = $last;
668                         }
669
670                         my @sub_data;
671                         for my $set (@pic_data) {
672                                 push @sub_data, [ splice(@$set,0,$size) ];
673                         }
674
675                         my $pic = new GD::Graph::pie;
676
677                         $pic->set(
678                                 label                   => $r->{column_labels}->[$vcol],
679                                 start_angle             => 180,
680                                 legend_placement        => 'R',
681                                 #logo                   => $logo,
682                                 #logo_position          => 'TL',
683                                 #logo_resize            => 0.5,
684                                 show_values             => 1,
685                         );
686
687                         my $format = $pic->export_format;
688
689                         open(IMG, ">$file.pie.$vcol.$sub_graph.$format") or die "Cannot write '$file.pie.$vcol.$sub_graph.$format'";
690                         binmode IMG;
691
692                         my $forgetit = 0;
693                         try {
694                                 $pic->plot(\@sub_data) or die $pic->error;
695                                 print IMG $pic->gd->$format;
696                         } otherwise {
697                                 my $e = shift;
698                                 warn "Couldn't draw $file.pie.$vcol.$sub_graph.$format : $e";
699                                 $forgetit = 1;
700                         };
701
702                         close IMG;
703
704
705                         push @pics,
706                                 { file => "pie.$vcol.$sub_graph.$format",
707                                   name => $r->{column_labels}->[$vcol].' (Pie)',
708                                 } unless ($forgetit);
709
710                         last if ($sub_graph == $split);
711                 }
712
713         }
714         
715         return \@pics;
716 }
717
718 sub draw_bars {
719         my $r = shift;
720         my $file = shift;
721         my $data = $r->{data};
722
723         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
724
725         my @groups = @{ $r->{group_by_list} };
726
727         
728         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
729         splice(@values,$_,1) for (reverse @groups);
730
731         my @pic_data;
732         {       no warnings;
733                 for my $row (@$data) {
734                         push @{$pic_data[0]}, join(' -- ', @$row[@groups]);
735                 }
736         }
737
738         my @leg;
739         my $set = 1;
740
741         my %trim_candidates;
742
743         my $max_y = 0;
744         for my $vcol (@values) {
745                 next unless (defined $vcol);
746                 $pic_data[$set] ||= [];
747
748                 my $pos = 0;
749                 for my $row (@$data) {
750                         my $val = $$row[$vcol] ? $$row[$vcol] : 0;
751                         push @{$pic_data[$set]}, $val;
752                         $max_y = $val if ($val > $max_y);
753                         $trim_candidates{$pos}++ if ($val == 0);
754                         $pos++;
755                 }
756
757                 $set++;
758         }
759         my $set_count = scalar(@pic_data) - 1;
760         my @trim_cols = grep { $trim_candidates{$_} == $set_count } keys %trim_candidates;
761
762         my @new_data;
763         my @use_me;
764         my @no_use;
765         my $set_index = 0;
766         for my $dataset (@pic_data) {
767                 splice(@$dataset,$_,1) for (reverse sort @trim_cols);
768
769                 if (grep { $_ } @$dataset) {
770                         push @new_data, $dataset;
771                         push @use_me, $set_index if ($set_index > 0);
772                 } else {
773                         push @no_use, $set_index;
774                 }
775                 $set_index++;
776                 
777         }
778
779         return [] unless ($new_data[0] && @{$new_data[0]});
780
781         for my $col (@use_me) {
782                 push @leg, $r->{column_labels}->[$values[$col - 1]];
783         }
784
785         my $w = 100 + 10 * scalar(@{$new_data[0]});
786         $w = 400 if ($w < 400);
787
788         my $h = 10 * (scalar(@new_data) / 2);
789
790         $h = 0 if ($h < 0);
791
792         my $pic = new GD::Graph::bars3d ($w + 250, $h + 500);
793
794         $pic->set(
795                 title                   => $r->{report}{name},
796                 x_labels_vertical       => 1,
797                 shading                 => 1,
798                 bar_depth               => 5,
799                 bar_spacing             => 2,
800                 y_max_value             => $max_y,
801                 legend_placement        => 'TR',
802                 boxclr                  => 'lgray',
803                 #logo                   => $logo,
804                 #logo_position          => 'R',
805                 #logo_resize            => 0.5,
806                 show_values             => 1,
807                 overwrite               => 1,
808         );
809         $pic->set_legend(@leg);
810
811         my $format = $pic->export_format;
812
813         open(IMG, ">$file.bar.$format") or die "Cannot write '$file.bar.$format'";
814         binmode IMG;
815
816         try {
817                 $pic->plot(\@new_data) or die $pic->error;
818                 print IMG $pic->gd->$format;
819         } otherwise {
820                 my $e = shift;
821                 warn "Couldn't draw $file.bar.$format : $e";
822         };
823
824         close IMG;
825
826         return [{ file => "bar.$format",
827                   name => $r->{report}{name}.' (Bar)',
828                 }];
829
830 }
831
832 sub draw_lines {
833         my $r    = shift;
834         my $file = shift;
835         my $data = $r->{data};
836
837         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
838
839         my @groups = @{ $r->{group_by_list} };
840         
841         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
842         splice(@values,$_,1) for (reverse @groups);
843
844         my @pic_data;
845         {       no warnings;
846                 for my $row (@$data) {
847                         push @{$pic_data[0]}, join(' -- ', @$row[@groups]);
848                 }
849         }
850
851         my @leg;
852         my $set = 1;
853
854         my $max_y = 0;
855         for my $vcol (@values) {
856                 next unless (defined $vcol);
857                 $pic_data[$set] ||= [];
858
859
860                 for my $row (@$data) {
861                         my $val = $$row[$vcol] ? $$row[$vcol] : 0;
862                         push @{$pic_data[$set]}, $val;
863                         $max_y = $val if ($val > $max_y);
864                 }
865
866                 $set++;
867         }
868         my $set_count = scalar(@pic_data) - 1;
869
870         my @new_data;
871         my @use_me;
872         my @no_use;
873         my $set_index = 0;
874         for my $dataset (@pic_data) {
875
876                 if (grep { $_ } @$dataset) {
877                         push @new_data, $dataset;
878                         push @use_me, $set_index if ($set_index > 0);
879                 } else {
880                         push @no_use, $set_index;
881                 }
882                 $set_index++;
883                 
884         }
885
886         return [] unless ($new_data[0] && @{$new_data[0]});
887
888         for my $col (@use_me) {
889                 push @leg, $r->{column_labels}->[$values[$col - 1]];
890         }
891
892         my $w = 100 + 10 * scalar(@{$new_data[0]});
893         $w = 400 if ($w < 400);
894
895         my $h = 10 * (scalar(@new_data) / 2);
896
897         $h = 0 if ($h < 0);
898
899         my $pic = new GD::Graph::lines3d ($w + 250, $h + 500);
900
901         $pic->set(
902                 title                   => $r->{report}{name},
903                 x_labels_vertical       => 1,
904                 shading                 => 1,
905                 line_depth              => 5,
906                 y_max_value             => $max_y,
907                 legend_placement        => 'TR',
908                 boxclr                  => 'lgray',
909                 #logo                   => $logo,
910                 #logo_position          => 'R',
911                 #logo_resize            => 0.5,
912                 show_values             => 1,
913                 overwrite               => 1,
914         );
915         $pic->set_legend(@leg);
916
917         my $format = $pic->export_format;
918
919         open(IMG, ">$file.line.$format") or die "Cannot write '$file.line.$format'";
920         binmode IMG;
921
922         try {
923                 $pic->plot(\@new_data) or die $pic->error;
924                 print IMG $pic->gd->$format;
925         } otherwise {
926                 my $e = shift;
927                 warn "Couldn't draw $file.line.$format : $e";
928         };
929
930         close IMG;
931
932         return [{ file => "line.$format",
933                   name => $r->{report}{name}.' (Bar)',
934                 }];
935
936 }
937
938
939 sub pivot_data {
940         my $blob        = shift;
941         my $pivot_label = shift;
942         my $pivot_data  = shift;
943         my $default     = shift;
944         $default = 0 unless (defined $default);
945
946         my $data = $$blob{data};
947         my $cols = $$blob{columns};
948
949         my @keep_labels =  @$cols;
950         splice(@keep_labels, $_ - 1, 1) for (reverse sort ($pivot_label, $pivot_data));
951
952         my @keep_cols = (0 .. @$cols - 1);
953         splice(@keep_cols, $_ - 1, 1) for (reverse sort ($pivot_label, $pivot_data));
954
955         my @gb = ( 0 .. @keep_cols - 1);
956
957         #first, find the unique list of pivot values
958         my %tmp;
959         for my $row (@$data) {
960                 $tmp{ $$row[$pivot_label - 1] } = 1;
961         }
962         my @new_cols = sort keys %tmp;
963
964         tie my %split_data, 'Tie::IxHash';
965         for my $row (@$data) {
966
967                 my $row_fp = ''. join('', map { defined($$row[$_]) ? $$row[$_] : '' } @keep_cols);
968                 $split_data{$row_fp} ||= [];
969
970                 push @{ $split_data{$row_fp} }, $row;
971         }
972
973
974         #now loop over the data, building a new result set
975         tie my %new_data, 'Tie::IxHash';
976
977         for my $fp ( keys %split_data ) {
978
979                 $new_data{$fp} = [];
980
981                 for my $col (@keep_cols) {
982                         push @{ $new_data{$fp} }, $split_data{$fp}[0][$col];
983                 }
984
985                 for my $col (@new_cols) {
986
987                         my ($datum) = map { $_->[$pivot_data - 1] } grep { $_->[$pivot_label - 1] eq $col } @{ $split_data{$fp} };
988                         $datum ||= $default;
989                         push @{ $new_data{$fp} }, $datum;
990                 }
991         }
992
993         push @keep_labels, @new_cols;
994
995         return { columns => \@keep_labels, data => [ values %new_data ], group_by_list => \@gb };
996 }
997
998