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