Fix broken guided_reports.pl
[koha.git] / reports / guided_reports.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime ltd
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 # use warnings;  # FIXME
22 use CGI;
23 use Text::CSV;
24 use C4::Reports::Guided;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Dates;
28 use C4::Debug;
29
30 =head1 NAME
31
32 guided_reports.pl
33
34 =head1 DESCRIPTION
35
36 Script to control the guided report creation
37
38 =over2
39
40 =cut
41
42 my $input = new CGI;
43
44 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
45     {
46         template_name   => "reports/guided_reports_start.tmpl",
47         query           => $input,
48         type            => "intranet",
49         authnotrequired => 0,
50         flagsrequired   => { reports => 1 },
51         debug           => 1,
52     }
53 );
54
55     my @errors = ();
56 my $phase = $input->param('phase');
57 if ( !$phase ) {
58     $template->param( 'start' => 1 );
59     # show welcome page
60 }
61 elsif ( $phase eq 'Build new' ) {
62     # build a new report
63     $template->param( 'build1' => 1 );
64     $template->param( 'areas' => get_report_areas() );
65 }
66 elsif ( $phase eq 'Use saved' ) {
67     # use a saved report
68     # get list of reports and display them
69     $template->param( 'saved1' => 1 );
70     $template->param( 'savedreports' => get_saved_reports() ); 
71 }
72
73 elsif ( $phase eq 'Delete Saved') {
74         
75         # delete a report from the saved reports list
76         my $id = $input->param('reports');
77         delete_report($id);
78     print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
79         exit;
80 }               
81
82 elsif ( $phase eq 'Show SQL'){
83         
84         my $id = $input->param('reports');
85         my $sql = get_sql($id);
86         $template->param(
87                 'sql' => $sql,
88                 'showsql' => 1,
89     );
90 }
91
92 elsif ( $phase eq 'Edit SQL'){
93         
94     my $id = $input->param('reports');
95     my ($sql,$type,$reportname,$notes) = get_saved_report($id);
96     $template->param(
97             'sql'        => $sql,
98             'reportname' => $reportname,
99         'notes'      => $notes,
100         'id'         => $id,
101             'editsql'    => 1,
102     );
103 }
104
105 elsif ( $phase eq 'Update SQL'){
106     my $id         = $input->param('id');
107     my $sql        = $input->param('sql');
108     my $reportname = $input->param('reportname');
109     my $notes      = $input->param('notes');
110     my @errors;
111     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
112         push @errors, {sqlerr => $1};
113     }
114     elsif ($sql !~ /^(SELECT)/i) {
115         push @errors, {queryerr => 1};
116     }
117     if (@errors) {
118         $template->param(
119             'errors'    => \@errors,
120             'sql'       => $sql,
121         );
122     }
123     else {
124         update_sql( $id, $sql, $reportname, $notes );
125         $template->param(
126             'save_successful'       => 1,
127         );
128     }
129     
130 }
131
132 elsif ($phase eq 'retrieve results') {
133         my $id = $input->param('id');
134         my ($results,$name,$notes) = format_results($id);
135         # do something
136         $template->param(
137                 'retresults' => 1,
138                 'results' => $results,
139                 'name' => $name,
140                 'notes' => $notes,
141     );
142 }
143
144 elsif ( $phase eq 'Report on this Area' ) {
145
146     # they have choosen a new report and the area to report on
147     $template->param(
148         'build2' => 1,
149         'area'   => $input->param('areas'),
150         'types'  => get_report_types(),
151     );
152 }
153
154 elsif ( $phase eq 'Choose this type' ) {
155
156     # they have chosen type and area
157     # get area and type and pass them to the template
158     my $area = $input->param('area');
159     my $type = $input->param('types');
160     $template->param(
161         'build3' => 1,
162         'area'   => $area,
163         'type'   => $type,
164         columns  => get_columns($area,$input),
165     );
166 }
167
168 elsif ( $phase eq 'Choose these columns' ) {
169
170     # we now know type, area, and columns
171     # next step is the constraints
172     my $area    = $input->param('area');
173     my $type    = $input->param('type');
174     my @columns = $input->param('columns');
175     my $column  = join( ',', @columns );
176     $template->param(
177         'build4' => 1,
178         'area'   => $area,
179         'type'   => $type,
180         'column' => $column,
181         definitions => get_from_dictionary($area),
182         criteria    => get_criteria($area,$input),
183     );
184 }
185
186 elsif ( $phase eq 'Choose these criteria' ) {
187     my $area     = $input->param('area');
188     my $type     = $input->param('type');
189     my $column   = $input->param('column');
190         my @definitions = $input->param('definition');
191         my $definition = join (',',@definitions);
192     my @criteria = $input->param('criteria_column');
193         my $query_criteria;
194     foreach my $crit (@criteria) {
195         my $value = $input->param( $crit . "_value" );
196         ($value) or next;
197         if ($value =~ C4::Dates->regexp('syspref')) { 
198             $value = C4::Dates->new($value)->output("iso");
199         }
200         $query_criteria .= " AND $crit='$value'";
201     }
202
203     $template->param(
204         'build5'         => 1,
205         'area'           => $area,
206         'type'           => $type,
207         'column'         => $column,
208         'definition'     => $definition,
209         'criteriastring' => $query_criteria,
210     );
211
212     # get columns
213     my @columns = split( ',', $column );
214     my @total_by;
215
216     # build structue for use by tmpl_loop to choose columns to order by
217     # need to do something about the order of the order :)
218         # we also want to use the %columns hash to get the plain english names
219     foreach my $col (@columns) {
220         my %total = (name => $col);
221         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
222         $total{'select'} = \@selects;
223         push @total_by, \%total;
224     }
225
226     $template->param( 'total_by' => \@total_by );
227 }
228
229 elsif ( $phase eq 'Choose These Operations' ) {
230     my $area     = $input->param('area');
231     my $type     = $input->param('type');
232     my $column   = $input->param('column');
233     my $criteria = $input->param('criteria');
234         my $definition = $input->param('definition');
235     my @total_by = $input->param('total_by');
236     my $totals;
237     foreach my $total (@total_by) {
238         my $value = $input->param( $total . "_tvalue" );
239         $totals .= "$value($total),";
240     }
241
242     $template->param(
243         'build6'         => 1,
244         'area'           => $area,
245         'type'           => $type,
246         'column'         => $column,
247         'criteriastring' => $criteria,
248         'totals'         => $totals,
249         'definition'     => $definition,
250     );
251
252     # get columns
253     my @columns = split( ',', $column );
254     my @order_by;
255
256     # build structue for use by tmpl_loop to choose columns to order by
257     # need to do something about the order of the order :)
258     foreach my $col (@columns) {
259         my %order = (name => $col);
260         my @selects = map {+{ value => $_ }} (qw(asc desc));
261         $order{'select'} = \@selects;
262         push @order_by, \%order;
263     }
264
265     $template->param( 'order_by' => \@order_by );
266 }
267
268 elsif ( $phase eq 'Build Report' ) {
269
270     # now we have all the info we need and can build the sql
271     my $area     = $input->param('area');
272     my $type     = $input->param('type');
273     my $column   = $input->param('column');
274     my $crit     = $input->param('criteria');
275     my $totals   = $input->param('totals');
276         my $definition = $input->param('definition');
277 #    my @criteria = split( ',', $crit );
278     my $query_criteria=$crit;
279     # split the columns up by ,
280     my @columns = split( ',', $column );
281     my @order_by = $input->param('order_by');
282
283     my $query_orderby;
284     foreach my $order (@order_by) {
285         my $value = $input->param( $order . "_ovalue" );
286         if ($query_orderby) {
287             $query_orderby .= ",$order $value";
288         }
289         else {
290             $query_orderby = " ORDER BY $order $value";
291         }
292     }
293
294     # get the sql
295     my $sql =
296       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
297     $template->param(
298         'showreport' => 1,
299         'sql'        => $sql,
300         'type'       => $type
301     );
302 }
303
304 elsif ( $phase eq 'Save' ) {
305         # Save the report that has just been built
306     my $sql  = $input->param('sql');
307     my $type = $input->param('type');
308     $template->param(
309         'save' => 1,
310         'sql'  => $sql,
311         'type' => $type
312     );
313 }
314
315 elsif ( $phase eq 'Save Report' ) {
316     # save the sql pasted in by a user 
317     my $sql  = $input->param('sql');
318     my $name = $input->param('reportname');
319     my $type = $input->param('types');
320     my $notes = $input->param('notes');
321     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
322         push @errors, {sqlerr => $1};
323     }
324     elsif ($sql !~ /^(SELECT)/i) {
325         push @errors, {queryerr => 1};
326     }
327     if (@errors) {
328         $template->param(
329             'errors'    => \@errors,
330             'sql'       => $sql,
331             'reportname'=> $name,
332             'type'      => $type,
333             'notes'     => $notes,
334         );
335     }
336     else {
337         save_report( $borrowernumber, $sql, $name, $type, $notes );
338         $template->param(
339             'save_successful'       => 1,
340         );
341     }
342 }
343
344 elsif ($phase eq 'Run this report'){
345     # execute a saved report
346     my $limit  = 20;    # page size. # TODO: move to DB or syspref?
347     my $offset = 0;
348     my $report = $input->param('reports');
349     # offset algorithm
350     if ($input->param('page')) {
351         $offset = ($input->param('page') - 1) * $limit;
352     }
353     my ($sql,$type,$name,$notes) = get_saved_report($report);
354     unless ($sql) {
355         push @errors, {no_sql_for_id=>$report};   
356     } 
357     my @rows = ();
358     my ($sth, $errors) = execute_query($sql, $offset, $limit);
359     my $total = select_2_select_count_value($sql) || 0;
360     unless ($sth) {
361         die "execute_query failed to return sth for report $report: $sql";
362     } else {
363         my $headref = $sth->{NAME} || [];
364         my @headers = map { +{ cell => $_ } } @$headref;
365         $template->param(header_row => \@headers);
366         while (my $row = $sth->fetchrow_arrayref()) {
367             my @cells = map { +{ cell => $_ } } @$row;
368             push @rows, { cells => \@cells };
369         }
370     }
371
372     my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
373     my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
374     $template->param(
375         'results' => \@rows,
376         'sql'     => $sql,
377         'execute' => 1,
378         'name'    => $name,
379         'notes'   => $notes,
380         'errors'  => $errors,
381         'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
382         'unlimited_total' => $total,
383     );
384 }       
385
386 elsif ($phase eq 'Export'){
387     binmode STDOUT, ':utf8';
388
389         # export results to tab separated text or CSV
390         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
391     my $format = $input->param('format');
392         my ($sth, $q_errors) = execute_query($sql);
393     unless ($q_errors and @$q_errors) {
394         print $input->header(       -type => 'application/octet-stream',
395                                     -attachment=>"reportresults.$format"
396                             );
397         if ($format eq 'tab') {
398             print join("\t", header_cell_values($sth)), "\n";
399             while (my $row = $sth->fetchrow_arrayref()) {
400                 print join("\t", @$row), "\n";
401             }
402         } else {
403             my $csv = Text::CSV->new({binary => 1});
404             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
405             if ($csv->combine(header_cell_values($sth))) {
406                 print $csv->string(), "\n";
407             } else {
408                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
409             }
410             while (my $row = $sth->fetchrow_arrayref()) {
411                 if ($csv->combine(@$row)) {
412                     print $csv->string(), "\n"; 
413                 } else {
414                     push @$q_errors, { combine => $csv->error_diag() } ;
415                 }
416             }
417         }
418         foreach my $err (@$q_errors, @errors) {
419             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
420         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
421         exit;
422     }
423     $template->param(
424         'sql'           => $sql,
425         'execute'       => 1,
426         'name'          => 'Error exporting report!',
427         'notes'         => '',
428         'errors'        => $q_errors,
429     );
430 }
431
432 elsif ($phase eq 'Create report from SQL') {
433         # allow the user to paste in sql
434     if ($input->param('sql')) {
435         $template->param(
436             'sql'           => $input->param('sql'),
437             'reportname'    => $input->param('reportname'),
438             'notes'         => $input->param('notes'),
439         );
440     }
441         $template->param('create' => 1);
442 }
443
444 elsif ($phase eq 'Create Compound Report'){
445         $template->param( 'savedreports' => get_saved_reports(),
446                 'compound' => 1,
447         );
448 }
449
450 elsif ($phase eq 'Save Compound'){
451     my $master    = $input->param('master');
452         my $subreport = $input->param('subreport');
453         my ($mastertables,$subtables) = create_compound($master,$subreport);
454         $template->param( 'save_compound' => 1,
455                 master=>$mastertables,
456                 subsql=>$subtables
457         );
458 }
459
460 # pass $sth, get back an array of names for the column headers
461 sub header_cell_values {
462     my $sth = shift or return ();
463     return @{$sth->{NAME}};
464 }
465
466 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
467 sub header_cell_loop {
468     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
469     return \@headers;
470 }
471
472 # pass $sth, get back an array of names for the column headers
473 sub header_cell_values {
474     my $sth = shift or return ();
475     return @{$sth->{NAME}};
476 }
477
478 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
479 sub header_cell_loop {
480     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
481     return \@headers;
482 }
483
484 foreach (1..6) {
485     $template->param('build' . $_) and $template->param(buildx => $_) and last;
486 }
487 $template->param(   'referer' => $input->referer(),
488                     'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
489                 );
490
491 output_html_with_http_headers $input, $cookie, $template->output;