Allowing users to edit saved sql in guided reports. Bug 1545
[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 = get_sql($id);
96         $template->param(
97                 'sql'     => $sql,
98                 'id'      => $id,
99                 'editsql' => 1,
100     );
101 }
102
103 elsif ( $phase eq 'Update SQL'){
104     my $id = $input->param('id');
105     my $sql = $input->param('sql');
106     my @errors;
107     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
108         push @errors, {sqlerr => $1};
109     }
110     elsif ($sql !~ /^(SELECT)/i) {
111         push @errors, {queryerr => 1};
112     }
113     if (@errors) {
114         $template->param(
115             'errors'    => \@errors,
116             'sql'       => $sql,
117         );
118     }
119     else {
120         update_sql( $id, $sql );
121         $template->param(
122             'save_successful'       => 1,
123         );
124     }
125     
126 }
127
128 elsif ($phase eq 'retrieve results') {
129         my $id = $input->param('id');
130         my ($results,$name,$notes) = format_results($id);
131         # do something
132         $template->param(
133                 'retresults' => 1,
134                 'results' => $results,
135                 'name' => $name,
136                 'notes' => $notes,
137     );
138 }
139
140 elsif ( $phase eq 'Report on this Area' ) {
141
142     # they have choosen a new report and the area to report on
143     $template->param(
144         'build2' => 1,
145         'area'   => $input->param('areas'),
146         'types'  => get_report_types(),
147     );
148 }
149
150 elsif ( $phase eq 'Choose this type' ) {
151
152     # they have chosen type and area
153     # get area and type and pass them to the template
154     my $area = $input->param('area');
155     my $type = $input->param('types');
156     $template->param(
157         'build3' => 1,
158         'area'   => $area,
159         'type'   => $type,
160         columns  => get_columns($area,$input),
161     );
162 }
163
164 elsif ( $phase eq 'Choose these columns' ) {
165
166     # we now know type, area, and columns
167     # next step is the constraints
168     my $area    = $input->param('area');
169     my $type    = $input->param('type');
170     my @columns = $input->param('columns');
171     my $column  = join( ',', @columns );
172     $template->param(
173         'build4' => 1,
174         'area'   => $area,
175         'type'   => $type,
176         'column' => $column,
177         definitions => get_from_dictionary($area),
178         criteria    => get_criteria($area,$input),
179     );
180 }
181
182 elsif ( $phase eq 'Choose these criteria' ) {
183     my $area     = $input->param('area');
184     my $type     = $input->param('type');
185     my $column   = $input->param('column');
186         my @definitions = $input->param('definition');
187         my $definition = join (',',@definitions);
188     my @criteria = $input->param('criteria_column');
189         my $query_criteria;
190     foreach my $crit (@criteria) {
191         my $value = $input->param( $crit . "_value" );
192         ($value) or next;
193         if ($value =~ C4::Dates->regexp('syspref')) { 
194             $value = C4::Dates->new($value)->output("iso");
195         }
196         $query_criteria .= " AND $crit='$value'";
197     }
198
199     $template->param(
200         'build5'         => 1,
201         'area'           => $area,
202         'type'           => $type,
203         'column'         => $column,
204         'definition'     => $definition,
205         'criteriastring' => $query_criteria,
206     );
207
208     # get columns
209     my @columns = split( ',', $column );
210     my @total_by;
211
212     # build structue for use by tmpl_loop to choose columns to order by
213     # need to do something about the order of the order :)
214         # we also want to use the %columns hash to get the plain english names
215     foreach my $col (@columns) {
216         my %total = (name => $col);
217         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
218         $total{'select'} = \@selects;
219         push @total_by, \%total;
220     }
221
222     $template->param( 'total_by' => \@total_by );
223 }
224
225 elsif ( $phase eq 'Choose These Operations' ) {
226     my $area     = $input->param('area');
227     my $type     = $input->param('type');
228     my $column   = $input->param('column');
229     my $criteria = $input->param('criteria');
230         my $definition = $input->param('definition');
231     my @total_by = $input->param('total_by');
232     my $totals;
233     foreach my $total (@total_by) {
234         my $value = $input->param( $total . "_tvalue" );
235         $totals .= "$value($total),";
236     }
237
238     $template->param(
239         'build6'         => 1,
240         'area'           => $area,
241         'type'           => $type,
242         'column'         => $column,
243         'criteriastring' => $criteria,
244         'totals'         => $totals,
245         'definition'     => $definition,
246     );
247
248     # get columns
249     my @columns = split( ',', $column );
250     my @order_by;
251
252     # build structue for use by tmpl_loop to choose columns to order by
253     # need to do something about the order of the order :)
254     foreach my $col (@columns) {
255         my %order = (name => $col);
256         my @selects = map {+{ value => $_ }} (qw(asc desc));
257         $order{'select'} = \@selects;
258         push @order_by, \%order;
259     }
260
261     $template->param( 'order_by' => \@order_by );
262 }
263
264 elsif ( $phase eq 'Build Report' ) {
265
266     # now we have all the info we need and can build the sql
267     my $area     = $input->param('area');
268     my $type     = $input->param('type');
269     my $column   = $input->param('column');
270     my $crit     = $input->param('criteria');
271     my $totals   = $input->param('totals');
272         my $definition = $input->param('definition');
273 #    my @criteria = split( ',', $crit );
274     my $query_criteria=$crit;
275     # split the columns up by ,
276     my @columns = split( ',', $column );
277     my @order_by = $input->param('order_by');
278
279     my $query_orderby;
280     foreach my $order (@order_by) {
281         my $value = $input->param( $order . "_ovalue" );
282         if ($query_orderby) {
283             $query_orderby .= ",$order $value";
284         }
285         else {
286             $query_orderby = " ORDER BY $order $value";
287         }
288     }
289
290     # get the sql
291     my $sql =
292       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
293     $template->param(
294         'showreport' => 1,
295         'sql'        => $sql,
296         'type'       => $type
297     );
298 }
299
300 elsif ( $phase eq 'Save' ) {
301         # Save the report that has just been built
302     my $sql  = $input->param('sql');
303     my $type = $input->param('type');
304     $template->param(
305         'save' => 1,
306         'sql'  => $sql,
307         'type' => $type
308     );
309 }
310
311 elsif ( $phase eq 'Save Report' ) {
312     # save the sql pasted in by a user 
313     my $sql  = $input->param('sql');
314     my $name = $input->param('reportname');
315     my $type = $input->param('types');
316     my $notes = $input->param('notes');
317     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
318         push @errors, {sqlerr => $1};
319     }
320     elsif ($sql !~ /^(SELECT)/i) {
321         push @errors, {queryerr => 1};
322     }
323     if (@errors) {
324         $template->param(
325             'errors'    => \@errors,
326             'sql'       => $sql,
327             'reportname'=> $name,
328             'type'      => $type,
329             'notes'     => $notes,
330         );
331     }
332     else {
333         save_report( $sql, $name, $type, $notes );
334         $template->param(
335             'save_successful'       => 1,
336         );
337     }
338 }
339
340 elsif ($phase eq 'Run this report'){
341     # execute a saved report
342     my $limit  = 20;    # page size. # TODO: move to DB or syspref?
343     my $offset = 0;
344     my $report = $input->param('reports');
345     # offset algorithm
346     if ($input->param('page')) {
347         $offset = ($input->param('page') - 1) * $limit;
348     }
349     my ($sql,$type,$name,$notes) = get_saved_report($report);
350     unless ($sql) {
351         push @errors, {no_sql_for_id=>$report};   
352     } 
353     my @rows = ();
354     my ($sth, $errors) = execute_query($sql, $offset, $limit);
355     my $total = select_2_select_count_value($sql) || 0;
356     unless ($sth) {
357         die "execute_query failed to return sth for report $report: $sql";
358     } else {
359         my $headref = $sth->{NAME} || [];
360         my @headers = map { +{ cell => $_ } } @$headref;
361         $template->param(header_row => \@headers);
362         while (my $row = $sth->fetchrow_arrayref()) {
363             my @cells = map { +{ cell => $_ } } @$row;
364             push @rows, { cells => \@cells };
365         }
366     }
367
368     my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
369     my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
370     $template->param(
371         'results' => \@rows,
372         'sql'     => $sql,
373         'execute' => 1,
374         'name'    => $name,
375         'notes'   => $notes,
376         'errors'  => $errors,
377         'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
378         'unlimited_total' => $total,
379     );
380 }       
381
382 elsif ($phase eq 'Export'){
383     binmode STDOUT, ':utf8';
384
385         # export results to tab separated text or CSV
386         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
387     my $format = $input->param('format');
388         my ($sth, $q_errors) = execute_query($sql);
389     unless ($q_errors and @$q_errors) {
390         print $input->header(       -type => 'application/octet-stream',
391                                     -attachment=>"reportresults.$format"
392                             );
393         if ($format eq 'tab') {
394             print join("\t", header_cell_values($sth)), "\n";
395             while (my $row = $sth->fetchrow_arrayref()) {
396                 print join("\t", @$row), "\n";
397             }
398         } else {
399             my $csv = Text::CSV->new({binary => 1});
400             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
401             if ($csv->combine(header_cell_values($sth))) {
402                 print $csv->string(), "\n";
403             } else {
404                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
405             }
406             while (my $row = $sth->fetchrow_arrayref()) {
407                 if ($csv->combine(@$row)) {
408                     print $csv->string(), "\n"; 
409                 } else {
410                     push @$q_errors, { combine => $csv->error_diag() } ;
411                 }
412             }
413         }
414         foreach my $err (@$q_errors, @errors) {
415             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
416         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
417         exit;
418     }
419     $template->param(
420         'sql'           => $sql,
421         'execute'       => 1,
422         'name'          => 'Error exporting report!',
423         'notes'         => '',
424         'errors'        => $q_errors,
425     );
426 }
427
428 elsif ($phase eq 'Create report from SQL') {
429         # allow the user to paste in sql
430     if ($input->param('sql')) {
431         $template->param(
432             'sql'           => $input->param('sql'),
433             'reportname'    => $input->param('reportname'),
434             'notes'         => $input->param('notes'),
435         );
436     }
437         $template->param('create' => 1);
438 }
439
440 elsif ($phase eq 'Create Compound Report'){
441         $template->param( 'savedreports' => get_saved_reports(),
442                 'compound' => 1,
443         );
444 }
445
446 elsif ($phase eq 'Save Compound'){
447     my $master    = $input->param('master');
448         my $subreport = $input->param('subreport');
449         my ($mastertables,$subtables) = create_compound($master,$subreport);
450         $template->param( 'save_compound' => 1,
451                 master=>$mastertables,
452                 subsql=>$subtables
453         );
454 }
455
456 # pass $sth, get back an array of names for the column headers
457 sub header_cell_values {
458     my $sth = shift or return ();
459     return @{$sth->{NAME}};
460 }
461
462 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
463 sub header_cell_loop {
464     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
465     return \@headers;
466 }
467
468 foreach (1..6) {
469     $template->param('build' . $_) and $template->param(buildx => $_) and last;
470 }
471 $template->param(   'referer' => $input->referer(),
472                     'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
473                 );
474
475 output_html_with_http_headers $input, $cookie, $template->output;