]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/reporter/clark-kent.pl
LP1809288: Make some brt fields read-only
[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_pivot_data($report_data->{__pivot_data}) if $report_data->{__pivot_data};
203         $r->{resultset}->set_pivot_label($report_data->{__pivot_label}) if $report_data->{__pivot_label};
204         $r->{resultset}->set_pivot_default($report_data->{__pivot_default}) if $report_data->{__pivot_default};
205         $r->{resultset}->relative_time($r->{run_time});
206         $r->{resultset}->resultset_limit($resultset_limit) if $resultset_limit;
207         push @reports, $r;
208 }
209
210 $sth->finish;
211
212 $dbh->disconnect;
213
214 # Now we spawn the report runners
215
216 for my $r ( @reports ) {
217         next if (safe_fork());
218
219         # This is the child (runner) process;
220         daemonize("Clark Kent reporting: $r->{report}->{name}");
221
222         my $state_dbh = DBI->connect(
223                 $state_dsn,
224                 $state_db{db_user},
225                 $state_db{db_pw},
226                 { AutoCommit => 1,
227                   pg_expand_array => 0,
228                   pg_enable_utf8 => 1,
229                   RaiseError => 1
230                 }
231         );
232
233         my $data_dbh = DBI->connect(
234                 $data_dsn,
235                 $data_db{db_user},
236                 $data_db{db_pw},
237                 { AutoCommit => 1,
238                   pg_expand_array => 0,
239                   pg_enable_utf8 => 1,
240                   RaiseError => 1
241                 }
242         );
243         $data_dbh->do('SET statement_timeout = ?', {}, ($statement_timeout * 60 * 1000));
244
245         try {
246                 $state_dbh->do(<<'              SQL',{}, $r->{id});
247                         UPDATE  reporter.schedule
248                           SET   start_time = now()
249                           WHERE id = ?;
250                 SQL
251
252             $logger->debug('Report SQL: ' . $r->{resultset}->toSQL);
253                 $sth = $data_dbh->prepare($r->{resultset}->toSQL);
254
255                 $sth->execute;
256                 $r->{data} = $sth->fetchall_arrayref;
257
258                 $r->{column_labels} = [$r->{resultset}->column_label_list];
259
260                 if ($r->{resultset}->pivot_data && $r->{resultset}->pivot_label) {
261                         my @labels = $r->{resultset}->column_label_list;
262                         my $newdata = pivot_data(
263                                 { columns => $r->{column_labels}, data => $r->{data}},
264                                 $r->{resultset}->pivot_label,
265                                 $r->{resultset}->pivot_data,
266                                 $r->{resultset}->pivot_default
267                         );
268
269                         $r->{column_labels} = $newdata->{columns};
270                         $r->{data} = $newdata->{data};
271                         $r->{group_by_list} = $newdata->{group_by_list};
272                 } else {
273                         $r->{group_by_list} = [$r->{resultset}->group_by_list(0)];
274                 }
275
276                 my $s2 = $r->{report}->{template}->{id};
277                 my $s3 = $r->{report}->{id};
278                 my $output = $r->{id};
279
280                 mkdir($output_base);
281                 mkdir("$output_base/$s2");
282                 mkdir("$output_base/$s2/$s3");
283                 mkdir("$output_base/$s2/$s3/$output");
284         
285                 my $output_dir = "$output_base/$s2/$s3/$output";
286
287                 if ( $r->{csv_format} ) {
288                         build_csv("$output_dir/report-data.csv", $r);
289                 }
290
291                 if ( $r->{excel_format} ) {
292                         build_excel("$output_dir/report-data.xlsx", $r);
293                 }
294
295                 build_html("$output_dir/report-data.html", $r);
296
297                 $state_dbh->begin_work;
298
299                 if ($r->{report}->{recur} ) {
300                         my $sql = <<'                   SQL';
301                                 INSERT INTO reporter.schedule (
302                                                 report,
303                                                 folder,
304                                                 runner,
305                                                 run_time,
306                                                 email,
307                                                 csv_format,
308                                                 excel_format,
309                                                 html_format,
310                                                 chart_pie,
311                                                 chart_bar,
312                                                 chart_line )
313                                         VALUES ( ?, ?, ?, ?::TIMESTAMPTZ + ?, ?, ?, ?, ?, ?, ?, ? );
314                         SQL
315
316                         $state_dbh->do(
317                                 $sql,
318                                 {},
319                                 $r->{report}->{id},
320                                 $r->{folder},
321                                 $r->{runner},
322                                 $r->{run_time},
323                                 $r->{report}->{recurrence},
324                                 $r->{email},
325                                 $r->{csv_format},
326                                 $r->{excel_format},
327                                 $r->{html_format},
328                                 $r->{chart_pie},
329                                 $r->{chart_bar},
330                                 $r->{chart_line},
331                         );
332                 }
333
334                 $state_dbh->do(<<'              SQL',{}, $r->{id});
335                         UPDATE  reporter.schedule
336                           SET   complete_time = now()
337                           WHERE id = ?;
338                 SQL
339
340                 $state_dbh->commit;
341
342                 my $new_r = $state_dbh->selectrow_hashref(<<"           SQL", {}, $r->{id});
343                         SELECT * FROM reporter.schedule WHERE id = ?;
344                 SQL
345
346                 $r->{start_time}    = $new_r->{start_time};
347                 $r->{complete_time} = $new_r->{complete_time};
348
349                 if ($r->{email}) {
350                         send_success($r);
351                 }
352
353         } otherwise {
354                 my $e = shift;
355                 $r->{error_text} = ''.$e;
356                 if (!$state_dbh->{AutoCommit}) {
357                         $state_dbh->rollback;
358                 }
359                 $state_dbh->do(<<'              SQL',{}, $e, $r->{id});
360                         UPDATE  reporter.schedule
361                           SET   error_text = ?,
362                                 complete_time = now(),
363                                 error_code = 1
364                           WHERE id = ?;
365                 SQL
366
367                 my $new_r = $state_dbh->selectrow_hashref(<<"           SQL", {}, $r->{id});
368                         SELECT * FROM reporter.schedule WHERE id = ?;
369                 SQL
370
371                 $r->{error_text}    = $new_r->{error_text};
372                 $r->{complete_time} = $new_r->{complete_time};
373
374                 if ($r->{email}) {
375                         send_fail($r);
376                 }
377
378         };
379
380         $state_dbh->disconnect;
381         $data_dbh->disconnect;
382
383         exit; # leave the child
384 }
385
386 if ($daemon) {
387         sleep 1;
388         POSIX::waitpid( -1, POSIX::WNOHANG );
389         sleep $sleep_interval;
390         goto DAEMON;
391 }
392
393 #-------------------------------------------------------------------
394
395 sub send_success {
396         my $r = shift;
397         open F, $success_template or die "Cannot read '$success_template'";
398         my $tmpl = join('',<F>);
399         close F;
400
401         my $url = $base_uri . '/' .
402                 $r->{report}->{template}->{id} . '/' .
403                 $r->{report}->{id} . '/' .
404                 $r->{id} . '/report-data.html';
405
406         $tmpl =~ s/{TO}/$r->{email}/smog;
407         $tmpl =~ s/{FROM}/$email_sender/smog;
408         $tmpl =~ s/{REPLY_TO}/$email_sender/smog;
409         $tmpl =~ s/{REPORT_NAME}/$r->{report}->{name} -- $r->{report}->{template}->{name}/smog;
410         $tmpl =~ s/{RUN_TIME}/$r->{run_time}/smog;
411         $tmpl =~ s/{COMPLETE_TIME}/$r->{complete_time}/smog;
412         $tmpl =~ s/{OUTPUT_URL}/$url/smog;
413
414         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
415         if ($$tdata{version} >= 4) {
416                 $tmpl =~ s/{EXTERNAL_URL}/$$tdata{doc_url}/smog;
417         }
418
419         my $sender = Email::Send->new({mailer => 'SMTP'});
420         $sender->mailer_args([Host => $email_server]);
421         $sender->send($tmpl);
422 }
423
424 sub send_fail {
425         my $r = shift;
426         open F, $fail_template or die "Cannot read '$fail_template'";
427         my $tmpl = join('',<F>);
428         close F;
429
430         my $sql = $r->{resultset}->toSQL;
431
432         $tmpl =~ s/{TO}/$r->{email}/smog;
433         $tmpl =~ s/{FROM}/$email_sender/smog;
434         $tmpl =~ s/{REPLY_TO}/$email_sender/smog;
435         $tmpl =~ s/{REPORT_NAME}/$r->{report}->{name} -- $r->{report}->{template}->{name}/smog;
436         $tmpl =~ s/{RUN_TIME}/$r->{run_time}/smog;
437         $tmpl =~ s/{ERROR_TEXT}/$r->{error_text}/smog;
438         $tmpl =~ s/{SQL}/$sql/smog;
439
440         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
441         if ($$tdata{version} >= 4) {
442                 $tmpl =~ s/{EXTERNAL_URL}/$$tdata{doc_url}/smog;
443         }
444
445         my $sender = Email::Send->new({mailer => 'SMTP'});
446         $sender->mailer_args([Host => $email_server]);
447         $sender->send($tmpl);
448 }
449
450 sub build_csv {
451         my $file = shift;
452         my $r = shift;
453
454         my $csv = Text::CSV_XS->new({ always_quote => 1, eol => "\015\012" });
455
456         return unless ($csv);
457         
458         my $f = new FileHandle (">$file") or die "Cannot write to '$file'";
459
460         $csv->print($f, $r->{column_labels});
461         $csv->print($f, $_) for (@{$r->{data}});
462
463         $f->close;
464 }
465 sub build_excel {
466         my $file = shift;
467         my $r = shift;
468         my $xls = Excel::Writer::XLSX->new($file);
469
470         my $sheetname = substr($r->{report}->{name},0,30);
471         $sheetname =~ s/\W/_/gos;
472         
473         my $sheet = $xls->add_worksheet($sheetname);
474         # don't try to write formulas, just write anything that starts with = as a text cell
475         $sheet->add_write_handler(qr/^=/, sub { return shift->write_string(@_); } );
476
477         $sheet->write_row('A1', $r->{column_labels});
478
479         $sheet->write_col('A2', $r->{data});
480
481         $xls->close;
482 }
483
484 sub build_html {
485         my $file = shift;
486         my $r = shift;
487
488         my $index = new FileHandle (">$file") or die "Cannot write to '$file'";
489
490         my $tdata = OpenSRF::Utils::JSON->JSON2perl( $r->{report}->{template}->{data} );
491         
492         # index header
493         print $index <<"        HEADER";
494 <html>
495         <head>
496                 <meta charset='utf-8'>
497                 <title>$$r{report}{name}</title>
498                 <style>
499                         table { border-collapse: collapse; }
500                         th { background-color: lightgray; }
501                         td,th { border: solid black 1px; }
502                         * { font-family: sans-serif; font-size: 10px; }
503                         .dim { color: lightblue; }
504                 </style>
505         </head>
506         <body>
507                 <center>
508                 <h2><u>$$r{report}{name}</u></h2>
509                 $$r{report}{description}<br/>
510         HEADER
511
512         if ($$tdata{version} >= 4 and $$tdata{doc_url}) {
513                 print $index "<a target='_blank' href='$$tdata{doc_url}'>External template documentation</a><br/>";
514         }
515
516         print $index "<br/><br/>";
517
518         my @links;
519
520     my $br4 = '<br/>' x 4;
521         # add a link to the raw output html
522         push @links, "<a href='report-data.html.raw.html'>Tabular Output</a>" if ($r->{html_format});
523
524         # add a link to the CSV output
525         push @links, "<a href='report-data.xlsx'>Excel Output</a>" if ($r->{excel_format});
526
527         # add a link to the CSV output
528         push @links, "<a href='report-data.csv'>CSV Output</a>" if ($r->{csv_format});
529
530         # debugging output
531         push @links, "<a class='dim' href='report-data.html.debug.html'>Debugging Info</a>";
532
533         my $debug = new FileHandle (">$file.debug.html") or die "Cannot write to '$file.debug.html'";
534         print $debug "<html><head><meta charset='utf-8'><title>DEBUG: $$r{report}{name}</title></head><body>";
535
536         {       no warnings;
537                 if ($$tdata{version} >= 4 and $$tdata{doc_url}) {
538                         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/>";
539                 }
540
541                 print $debug '<h1>Generated SQL</h1><pre>' . $r->{resultset}->toSQL() . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
542                 print $debug '<h1>Template</h1><pre>' . Dumper( $r->{report}->{template} ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
543                 print $debug '<h1>Template Data</h1><pre>' . Dumper( $tdata ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
544                 print $debug '<h1>Report Parameter</h1><pre>' . Dumper( $r->{report} ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
545                 print $debug '<h1>Report Parameter Data</h1><pre>' . Dumper( $tdata ) . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
546                 print $debug '<h1>Report Run Time</h1><pre>' . $r->{resultset}->relative_time . "</pre><a href='report-data.html'>Back to output index</a><hr/>";
547                 print $debug '<h1>OpenILS::Reporter::SQLBuilder::ResultSet Object</h1><pre>' . Dumper( $r->{resultset} ) . "</pre><a href='report-data.html'>Back to output index</a>";
548         }
549
550         print $debug '</body></html>';
551
552         $debug->close;
553
554         print $index join(' -- ', @links);
555         print $index "$br4</center>";
556
557         if ($r->{html_format}) {
558                 # create the raw output html file
559                 my $raw = new FileHandle (">$file.raw.html") or die "Cannot write to '$file.raw.html'";
560                 print $raw "<html><head><meta charset='utf-8'><title>$$r{report}{name}</title>";
561
562                 print $raw <<'          CSS';
563                         <style>
564                                 table { border-collapse: collapse; }
565                                 th { background-color: lightgray; }
566                                 td,th { border: solid black 1px; }
567                                 * { font-family: sans-serif; }
568                         </style>
569                         <link rel="stylesheet" href="/js/sortable/sortable-theme-minimal.css" />
570                 CSS
571
572                 print $raw "</head><body><a href='report-data.html'>Back to output index</a><br/><table class='sortable-theme-minimal' data-sortable>";
573
574                 {       no warnings;
575                         print $raw "<thead><tr><th>".join('</th><th>', @{$r->{column_labels}})."</th></tr></thead>\n<tbody>";
576                         print $raw "<tr><td>".join('</td><td>', @$_)."</td></tr>\n" for (@{$r->{data}});
577                 }
578
579                 print $raw '</tbody></table>';
580                 if (@{ $r->{data} } <= $sortable_limit) {
581                         print $raw '<script src="/js/sortable/sortable.min.js"></script>';
582                 }
583                 print $raw '</body></html>';
584         
585                 $raw->close;
586         }
587
588         # Time for a pie chart
589         if ($r->{chart_pie}) {
590                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
591                         print $index "<strong>Report output has too many rows to make a pie chart</strong>$br4";
592                 } else {
593                         my $pics = draw_pie($r, $file);
594                         for my $pic (@$pics) {
595                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
596                         }
597                 }
598         }
599
600         print $index $br4;
601         # Time for a bar chart
602         if ($r->{chart_bar}) {
603                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
604                         print $index "<strong>Report output has too many rows to make a bar chart</strong>$br4";
605                 } else {
606                         my $pics = draw_bars($r, $file);
607                         for my $pic (@$pics) {
608                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
609                         }
610                 }
611         }
612
613         print $index $br4;
614         # Time for a bar chart
615         if ($r->{chart_line}) {
616                 if (scalar(@{$r->{data}}) > $max_rows_for_charts) {
617                         print $index "<strong>Report output has too many rows to make a line chart</strong>$br4";
618                 } else {
619                         my $pics = draw_lines($r, $file);
620                         for my $pic (@$pics) {
621                                 print $index "<img src='report-data.html.$pic->{file}' alt='$pic->{name}'/>$br4";
622                         }
623             }
624         }
625
626         # and that's it!
627         print $index '</body></html>';
628         
629         $index->close;
630 }
631
632 sub draw_pie {
633         my $r = shift;
634         my $file = shift;
635
636         my $data = $r->{data};
637
638         my @groups = @{ $r->{group_by_list} };
639         
640         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
641         delete @values[@groups];
642
643         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
644         
645         my @pics;
646         for my $vcol (@values) {
647                 next unless (defined $vcol);
648
649                 my @pic_data = ([],[]);
650                 for my $row (@$data) {
651                         next if (!defined($$row[$vcol]) || $$row[$vcol] == 0);
652                         my $val = $$row[$vcol];
653                         push @{$pic_data[0]}, join(" -- ", @$row[@groups])." ($val)";
654                         push @{$pic_data[1]}, $val;
655                 }
656
657                 next unless (@{$pic_data[0]});
658
659                 my $size = 300;
660                 my $split = int(scalar(@{$pic_data[0]}) / $size);
661                 my $last = scalar(@{$pic_data[0]}) % $size;
662
663                 for my $sub_graph (0 .. $split) {
664                         
665                         if ($sub_graph == $split) {
666                                 $size = $last;
667                         }
668
669                         my @sub_data;
670                         for my $set (@pic_data) {
671                                 push @sub_data, [ splice(@$set,0,$size) ];
672                         }
673
674                         my $pic = new GD::Graph::pie;
675
676                         $pic->set(
677                                 label                   => $r->{column_labels}->[$vcol],
678                                 start_angle             => 180,
679                                 legend_placement        => 'R',
680                                 #logo                   => $logo,
681                                 #logo_position          => 'TL',
682                                 #logo_resize            => 0.5,
683                                 show_values             => 1,
684                         );
685
686                         my $format = $pic->export_format;
687
688                         open(IMG, ">$file.pie.$vcol.$sub_graph.$format") or die "Cannot write '$file.pie.$vcol.$sub_graph.$format'";
689                         binmode IMG;
690
691                         my $forgetit = 0;
692                         try {
693                                 $pic->plot(\@sub_data) or die $pic->error;
694                                 print IMG $pic->gd->$format;
695                         } otherwise {
696                                 my $e = shift;
697                                 warn "Couldn't draw $file.pie.$vcol.$sub_graph.$format : $e";
698                                 $forgetit = 1;
699                         };
700
701                         close IMG;
702
703
704                         push @pics,
705                                 { file => "pie.$vcol.$sub_graph.$format",
706                                   name => $r->{column_labels}->[$vcol].' (Pie)',
707                                 } unless ($forgetit);
708
709                         last if ($sub_graph == $split);
710                 }
711
712         }
713         
714         return \@pics;
715 }
716
717 sub draw_bars {
718         my $r = shift;
719         my $file = shift;
720         my $data = $r->{data};
721
722         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
723
724         my @groups = @{ $r->{group_by_list} };
725
726         
727         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
728         splice(@values,$_,1) for (reverse @groups);
729
730         my @pic_data;
731         {       no warnings;
732                 for my $row (@$data) {
733                         push @{$pic_data[0]}, join(' -- ', @$row[@groups]);
734                 }
735         }
736
737         my @leg;
738         my $set = 1;
739
740         my %trim_candidates;
741
742         my $max_y = 0;
743         for my $vcol (@values) {
744                 next unless (defined $vcol);
745                 $pic_data[$set] ||= [];
746
747                 my $pos = 0;
748                 for my $row (@$data) {
749                         my $val = $$row[$vcol] ? $$row[$vcol] : 0;
750                         push @{$pic_data[$set]}, $val;
751                         $max_y = $val if ($val > $max_y);
752                         $trim_candidates{$pos}++ if ($val == 0);
753                         $pos++;
754                 }
755
756                 $set++;
757         }
758         my $set_count = scalar(@pic_data) - 1;
759         my @trim_cols = grep { $trim_candidates{$_} == $set_count } keys %trim_candidates;
760
761         my @new_data;
762         my @use_me;
763         my @no_use;
764         my $set_index = 0;
765         for my $dataset (@pic_data) {
766                 splice(@$dataset,$_,1) for (reverse sort @trim_cols);
767
768                 if (grep { $_ } @$dataset) {
769                         push @new_data, $dataset;
770                         push @use_me, $set_index if ($set_index > 0);
771                 } else {
772                         push @no_use, $set_index;
773                 }
774                 $set_index++;
775                 
776         }
777
778         return [] unless ($new_data[0] && @{$new_data[0]});
779
780         for my $col (@use_me) {
781                 push @leg, $r->{column_labels}->[$values[$col - 1]];
782         }
783
784         my $w = 100 + 10 * scalar(@{$new_data[0]});
785         $w = 400 if ($w < 400);
786
787         my $h = 10 * (scalar(@new_data) / 2);
788
789         $h = 0 if ($h < 0);
790
791         my $pic = new GD::Graph::bars3d ($w + 250, $h + 500);
792
793         $pic->set(
794                 title                   => $r->{report}{name},
795                 x_labels_vertical       => 1,
796                 shading                 => 1,
797                 bar_depth               => 5,
798                 bar_spacing             => 2,
799                 y_max_value             => $max_y,
800                 legend_placement        => 'TR',
801                 boxclr                  => 'lgray',
802                 #logo                   => $logo,
803                 #logo_position          => 'R',
804                 #logo_resize            => 0.5,
805                 show_values             => 1,
806                 overwrite               => 1,
807         );
808         $pic->set_legend(@leg);
809
810         my $format = $pic->export_format;
811
812         open(IMG, ">$file.bar.$format") or die "Cannot write '$file.bar.$format'";
813         binmode IMG;
814
815         try {
816                 $pic->plot(\@new_data) or die $pic->error;
817                 print IMG $pic->gd->$format;
818         } otherwise {
819                 my $e = shift;
820                 warn "Couldn't draw $file.bar.$format : $e";
821         };
822
823         close IMG;
824
825         return [{ file => "bar.$format",
826                   name => $r->{report}{name}.' (Bar)',
827                 }];
828
829 }
830
831 sub draw_lines {
832         my $r    = shift;
833         my $file = shift;
834         my $data = $r->{data};
835
836         #my $logo = $doc->findvalue('/reporter/setup/files/chart_logo');
837
838         my @groups = @{ $r->{group_by_list} };
839         
840         my @values = (0 .. (scalar(@{$r->{column_labels}}) - 1));
841         splice(@values,$_,1) for (reverse @groups);
842
843         my @pic_data;
844         {       no warnings;
845                 for my $row (@$data) {
846                         push @{$pic_data[0]}, join(' -- ', @$row[@groups]);
847                 }
848         }
849
850         my @leg;
851         my $set = 1;
852
853         my $max_y = 0;
854         for my $vcol (@values) {
855                 next unless (defined $vcol);
856                 $pic_data[$set] ||= [];
857
858
859                 for my $row (@$data) {
860                         my $val = $$row[$vcol] ? $$row[$vcol] : 0;
861                         push @{$pic_data[$set]}, $val;
862                         $max_y = $val if ($val > $max_y);
863                 }
864
865                 $set++;
866         }
867         my $set_count = scalar(@pic_data) - 1;
868
869         my @new_data;
870         my @use_me;
871         my @no_use;
872         my $set_index = 0;
873         for my $dataset (@pic_data) {
874
875                 if (grep { $_ } @$dataset) {
876                         push @new_data, $dataset;
877                         push @use_me, $set_index if ($set_index > 0);
878                 } else {
879                         push @no_use, $set_index;
880                 }
881                 $set_index++;
882                 
883         }
884
885         return [] unless ($new_data[0] && @{$new_data[0]});
886
887         for my $col (@use_me) {
888                 push @leg, $r->{column_labels}->[$values[$col - 1]];
889         }
890
891         my $w = 100 + 10 * scalar(@{$new_data[0]});
892         $w = 400 if ($w < 400);
893
894         my $h = 10 * (scalar(@new_data) / 2);
895
896         $h = 0 if ($h < 0);
897
898         my $pic = new GD::Graph::lines3d ($w + 250, $h + 500);
899
900         $pic->set(
901                 title                   => $r->{report}{name},
902                 x_labels_vertical       => 1,
903                 shading                 => 1,
904                 line_depth              => 5,
905                 y_max_value             => $max_y,
906                 legend_placement        => 'TR',
907                 boxclr                  => 'lgray',
908                 #logo                   => $logo,
909                 #logo_position          => 'R',
910                 #logo_resize            => 0.5,
911                 show_values             => 1,
912                 overwrite               => 1,
913         );
914         $pic->set_legend(@leg);
915
916         my $format = $pic->export_format;
917
918         open(IMG, ">$file.line.$format") or die "Cannot write '$file.line.$format'";
919         binmode IMG;
920
921         try {
922                 $pic->plot(\@new_data) or die $pic->error;
923                 print IMG $pic->gd->$format;
924         } otherwise {
925                 my $e = shift;
926                 warn "Couldn't draw $file.line.$format : $e";
927         };
928
929         close IMG;
930
931         return [{ file => "line.$format",
932                   name => $r->{report}{name}.' (Bar)',
933                 }];
934
935 }
936
937
938 sub pivot_data {
939         my $blob        = shift;
940         my $pivot_label = shift;
941         my $pivot_data  = shift;
942         my $default     = shift;
943         $default = 0 unless (defined $default);
944
945         my $data = $$blob{data};
946         my $cols = $$blob{columns};
947
948         my @keep_labels =  @$cols;
949         splice(@keep_labels, $_ - 1, 1) for (reverse sort ($pivot_label, $pivot_data));
950
951         my @keep_cols = (0 .. @$cols - 1);
952         splice(@keep_cols, $_ - 1, 1) for (reverse sort ($pivot_label, $pivot_data));
953
954         my @gb = ( 0 .. @keep_cols - 1);
955
956         #first, find the unique list of pivot values
957         my %tmp;
958         for my $row (@$data) {
959                 $tmp{ $$row[$pivot_label - 1] } = 1;
960         }
961         my @new_cols = sort keys %tmp;
962
963         tie my %split_data, 'Tie::IxHash';
964         for my $row (@$data) {
965
966                 my $row_fp = ''. join('', map { defined($$row[$_]) ? $$row[$_] : '' } @keep_cols);
967                 $split_data{$row_fp} ||= [];
968
969                 push @{ $split_data{$row_fp} }, $row;
970         }
971
972
973         #now loop over the data, building a new result set
974         tie my %new_data, 'Tie::IxHash';
975
976         for my $fp ( keys %split_data ) {
977
978                 $new_data{$fp} = [];
979
980                 for my $col (@keep_cols) {
981                         push @{ $new_data{$fp} }, $split_data{$fp}[0][$col];
982                 }
983
984                 for my $col (@new_cols) {
985
986                         my ($datum) = map { $_->[$pivot_data - 1] } grep { $_->[$pivot_label - 1] eq $col } @{ $split_data{$fp} };
987                         $datum ||= $default;
988                         push @{ $new_data{$fp} }, $datum;
989                 }
990         }
991
992         push @keep_labels, @new_cols;
993
994         return { columns => \@keep_labels, data => [ values %new_data ], group_by_list => \@gb };
995 }
996
997