Moving item : no need for ModOrder, as the itemnumber now stays the same
[koha_fer] / 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         
197         # If value is not defined, then it may be range values
198         if (!$value) {
199
200             my $fromvalue = $input->param( "from_" . $crit . "_value" );
201             my $tovalue   = $input->param( "to_"   . $crit . "_value" );
202             
203             # If the range values are dates
204             if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) { 
205                 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
206                 $tovalue = C4::Dates->new($tovalue)->output("iso");
207             }
208
209             if ($fromvalue && $tovalue) {
210                 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
211             }
212
213         } else {
214
215             # If value is a date
216             if ($value =~ C4::Dates->regexp('syspref')) { 
217                 $value = C4::Dates->new($value)->output("iso");
218             }
219             $query_criteria .= " AND $crit='$value'";
220         }
221         warn $query_criteria;
222     }
223
224     $template->param(
225         'build5'         => 1,
226         'area'           => $area,
227         'type'           => $type,
228         'column'         => $column,
229         'definition'     => $definition,
230         'criteriastring' => $query_criteria,
231     );
232
233     # get columns
234     my @columns = split( ',', $column );
235     my @total_by;
236
237     # build structue for use by tmpl_loop to choose columns to order by
238     # need to do something about the order of the order :)
239         # we also want to use the %columns hash to get the plain english names
240     foreach my $col (@columns) {
241         my %total = (name => $col);
242         my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
243         $total{'select'} = \@selects;
244         push @total_by, \%total;
245     }
246
247     $template->param( 'total_by' => \@total_by );
248 }
249
250 elsif ( $phase eq 'Choose These Operations' ) {
251     my $area     = $input->param('area');
252     my $type     = $input->param('type');
253     my $column   = $input->param('column');
254     my $criteria = $input->param('criteria');
255         my $definition = $input->param('definition');
256     my @total_by = $input->param('total_by');
257     my $totals;
258     foreach my $total (@total_by) {
259         my $value = $input->param( $total . "_tvalue" );
260         $totals .= "$value($total),";
261     }
262
263     $template->param(
264         'build6'         => 1,
265         'area'           => $area,
266         'type'           => $type,
267         'column'         => $column,
268         'criteriastring' => $criteria,
269         'totals'         => $totals,
270         'definition'     => $definition,
271     );
272
273     # get columns
274     my @columns = split( ',', $column );
275     my @order_by;
276
277     # build structue for use by tmpl_loop to choose columns to order by
278     # need to do something about the order of the order :)
279     foreach my $col (@columns) {
280         my %order = (name => $col);
281         my @selects = map {+{ value => $_ }} (qw(asc desc));
282         $order{'select'} = \@selects;
283         push @order_by, \%order;
284     }
285
286     $template->param( 'order_by' => \@order_by );
287 }
288
289 elsif ( $phase eq 'Build Report' ) {
290
291     # now we have all the info we need and can build the sql
292     my $area     = $input->param('area');
293     my $type     = $input->param('type');
294     my $column   = $input->param('column');
295     my $crit     = $input->param('criteria');
296     my $totals   = $input->param('totals');
297         my $definition = $input->param('definition');
298 #    my @criteria = split( ',', $crit );
299     my $query_criteria=$crit;
300     # split the columns up by ,
301     my @columns = split( ',', $column );
302     my @order_by = $input->param('order_by');
303
304     my $query_orderby;
305     foreach my $order (@order_by) {
306         my $value = $input->param( $order . "_ovalue" );
307         if ($query_orderby) {
308             $query_orderby .= ",$order $value";
309         }
310         else {
311             $query_orderby = " ORDER BY $order $value";
312         }
313     }
314
315     # get the sql
316     my $sql =
317       build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
318     $template->param(
319         'showreport' => 1,
320         'sql'        => $sql,
321         'type'       => $type
322     );
323 }
324
325 elsif ( $phase eq 'Save' ) {
326         # Save the report that has just been built
327     my $sql  = $input->param('sql');
328     my $type = $input->param('type');
329     $template->param(
330         'save' => 1,
331         'sql'  => $sql,
332         'type' => $type
333     );
334 }
335
336 elsif ( $phase eq 'Save Report' ) {
337     # save the sql pasted in by a user 
338     my $sql  = $input->param('sql');
339     my $name = $input->param('reportname');
340     my $type = $input->param('types');
341     my $notes = $input->param('notes');
342     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
343         push @errors, {sqlerr => $1};
344     }
345     elsif ($sql !~ /^(SELECT)/i) {
346         push @errors, {queryerr => 1};
347     }
348     if (@errors) {
349         $template->param(
350             'errors'    => \@errors,
351             'sql'       => $sql,
352             'reportname'=> $name,
353             'type'      => $type,
354             'notes'     => $notes,
355         );
356     }
357     else {
358         save_report( $borrowernumber, $sql, $name, $type, $notes );
359         $template->param(
360             'save_successful'       => 1,
361         );
362     }
363 }
364
365 elsif ($phase eq 'Run this report'){
366     # execute a saved report
367     my $limit  = 20;    # page size. # TODO: move to DB or syspref?
368     my $offset = 0;
369     my $report = $input->param('reports');
370     # offset algorithm
371     if ($input->param('page')) {
372         $offset = ($input->param('page') - 1) * $limit;
373     }
374     my ($sql,$type,$name,$notes) = get_saved_report($report);
375     unless ($sql) {
376         push @errors, {no_sql_for_id=>$report};   
377     } 
378     my @rows = ();
379     my ($sth, $errors) = execute_query($sql, $offset, $limit);
380     my $total = select_2_select_count_value($sql) || 0;
381     unless ($sth) {
382         die "execute_query failed to return sth for report $report: $sql";
383     } else {
384         my $headref = $sth->{NAME} || [];
385         my @headers = map { +{ cell => $_ } } @$headref;
386         $template->param(header_row => \@headers);
387         while (my $row = $sth->fetchrow_arrayref()) {
388             my @cells = map { +{ cell => $_ } } @$row;
389             push @rows, { cells => \@cells };
390         }
391     }
392
393     my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
394     my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
395     $template->param(
396         'results' => \@rows,
397         'sql'     => $sql,
398         'execute' => 1,
399         'name'    => $name,
400         'notes'   => $notes,
401         'errors'  => $errors,
402         'pagination_bar'  => pagination_bar($url, $totpages, $input->param('page')),
403         'unlimited_total' => $total,
404     );
405 }       
406
407 elsif ($phase eq 'Export'){
408     binmode STDOUT, ':utf8';
409
410         # export results to tab separated text or CSV
411         my $sql    = $input->param('sql');  # FIXME: use sql from saved report ID#, not new user-supplied SQL!
412     my $format = $input->param('format');
413         my ($sth, $q_errors) = execute_query($sql);
414     unless ($q_errors and @$q_errors) {
415         print $input->header(       -type => 'application/octet-stream',
416                                     -attachment=>"reportresults.$format"
417                             );
418         if ($format eq 'tab') {
419             print join("\t", header_cell_values($sth)), "\n";
420             while (my $row = $sth->fetchrow_arrayref()) {
421                 print join("\t", @$row), "\n";
422             }
423         } else {
424             my $csv = Text::CSV->new({binary => 1});
425             $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
426             if ($csv->combine(header_cell_values($sth))) {
427                 print $csv->string(), "\n";
428             } else {
429                 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
430             }
431             while (my $row = $sth->fetchrow_arrayref()) {
432                 if ($csv->combine(@$row)) {
433                     print $csv->string(), "\n"; 
434                 } else {
435                     push @$q_errors, { combine => $csv->error_diag() } ;
436                 }
437             }
438         }
439         foreach my $err (@$q_errors, @errors) {
440             print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
441         }   # here we print all the non-fatal errors at the end.  Not super smooth, but better than nothing.
442         exit;
443     }
444     $template->param(
445         'sql'           => $sql,
446         'execute'       => 1,
447         'name'          => 'Error exporting report!',
448         'notes'         => '',
449         'errors'        => $q_errors,
450     );
451 }
452
453 elsif ($phase eq 'Create report from SQL') {
454         # allow the user to paste in sql
455     if ($input->param('sql')) {
456         $template->param(
457             'sql'           => $input->param('sql'),
458             'reportname'    => $input->param('reportname'),
459             'notes'         => $input->param('notes'),
460         );
461     }
462         $template->param('create' => 1);
463 }
464
465 elsif ($phase eq 'Create Compound Report'){
466         $template->param( 'savedreports' => get_saved_reports(),
467                 'compound' => 1,
468         );
469 }
470
471 elsif ($phase eq 'Save Compound'){
472     my $master    = $input->param('master');
473         my $subreport = $input->param('subreport');
474         my ($mastertables,$subtables) = create_compound($master,$subreport);
475         $template->param( 'save_compound' => 1,
476                 master=>$mastertables,
477                 subsql=>$subtables
478         );
479 }
480
481 # pass $sth, get back an array of names for the column headers
482 sub header_cell_values {
483     my $sth = shift or return ();
484     return @{$sth->{NAME}};
485 }
486
487 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
488 sub header_cell_loop {
489     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
490     return \@headers;
491 }
492
493 # pass $sth, get back an array of names for the column headers
494 sub header_cell_values {
495     my $sth = shift or return ();
496     return @{$sth->{NAME}};
497 }
498
499 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
500 sub header_cell_loop {
501     my @headers = map { +{ cell => $_ } } header_cell_values (shift);
502     return \@headers;
503 }
504
505 foreach (1..6) {
506     $template->param('build' . $_) and $template->param(buildx => $_) and last;
507 }
508 $template->param(   'referer' => $input->referer(),
509                     'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
510                 );
511
512 output_html_with_http_headers $input, $cookie, $template->output;