3 # Copyright 2007 Liblime ltd
5 # This file is part of Koha.
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
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.
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
21 # use warnings; # FIXME
24 use C4::Reports::Guided;
36 Script to control the guided report creation
44 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
46 template_name => "reports/guided_reports_start.tmpl",
50 flagsrequired => { reports => 1 },
56 my $phase = $input->param('phase');
59 $template->param( 'start' => 1 );
62 elsif ( $phase eq 'Build new' ) {
64 $template->param( 'build1' => 1 );
65 $template->param( 'areas' => get_report_areas() );
67 elsif ( $phase eq 'Use saved' ) {
69 # get list of reports and display them
70 $template->param( 'saved1' => 1 );
71 $template->param( 'savedreports' => get_saved_reports() );
74 elsif ( $phase eq 'Delete Saved') {
76 # delete a report from the saved reports list
77 my $id = $input->param('reports');
79 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
83 elsif ( $phase eq 'Show SQL'){
85 my $id = $input->param('reports');
86 my $sql = get_sql($id);
93 elsif ($phase eq 'retrieve results') {
94 my $id = $input->param('id');
95 my ($results,$name,$notes) = format_results($id);
99 'results' => $results,
105 elsif ( $phase eq 'Report on this Area' ) {
107 # they have choosen a new report and the area to report on
110 'area' => $input->param('areas'),
111 'types' => get_report_types(),
115 elsif ( $phase eq 'Choose this type' ) {
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');
125 columns => get_columns($area,$input),
129 elsif ( $phase eq 'Choose these columns' ) {
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 );
142 definitions => get_from_dictionary($area),
143 criteria => get_criteria($area,$input),
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');
155 foreach my $crit (@criteria) {
156 my $value = $input->param( $crit . "_value" );
158 if ($value =~ C4::Dates->regexp('syspref')) {
159 $value = C4::Dates->new($value)->output("iso");
161 $query_criteria .= " AND $crit='$value'";
169 'definition' => $definition,
170 'criteriastring' => $query_criteria,
174 my @columns = split( ',', $column );
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;
187 $template->param( 'total_by' => \@total_by );
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');
198 foreach my $total (@total_by) {
199 my $value = $input->param( $total . "_tvalue" );
200 $totals .= "$value($total),";
208 'criteriastring' => $criteria,
210 'definition' => $definition,
214 my @columns = split( ',', $column );
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;
226 $template->param( 'order_by' => \@order_by );
229 elsif ( $phase eq 'Build Report' ) {
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');
245 foreach my $order (@order_by) {
246 my $value = $input->param( $order . "_ovalue" );
247 if ($query_orderby) {
248 $query_orderby .= ",$order $value";
251 $query_orderby = " ORDER BY $order $value";
257 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
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');
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};
285 elsif ($sql !~ /^(SELECT)/i) {
286 push @errors, {queryerr => 1};
290 'errors' => \@errors,
292 'reportname'=> $name,
298 save_report( $sql, $name, $type, $notes );
300 'save_successful' => 1,
305 elsif ($phase eq 'Run this report'){
306 # execute a saved report
307 my $limit = 20; # page size. # TODO: move to DB or syspref?
309 my $report = $input->param('reports');
311 if ($input->param('page')) {
312 $offset = ($input->param('page') - 1) * $limit;
314 my ($sql,$type,$name,$notes) = get_saved_report($report);
316 push @errors, {no_sql_for_id=>$report};
319 my ($sth, $errors) = execute_query($sql, $offset, $limit);
320 my $total = select_2_select_count_value($sql) || 0;
322 die "execute_query failed to return sth for report $report: $sql";
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 };
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";
342 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
343 'unlimited_total' => $total,
347 elsif ($phase eq 'Export'){
348 binmode STDOUT, ':utf8';
350 # export results to tab separated text
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.csv'
358 my $csv = Text::CSV->new({binary => 1});
359 $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
360 if ($csv->combine(header_cell_values($sth))) {
361 print $csv->string(), "\n";
363 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
365 while (my $row = $sth->fetchrow_arrayref()) {
366 if ($csv->combine(@$row)) {
367 print $csv->string(), "\n";
369 push @$q_errors, { combine => $csv->error_diag() } ;
372 foreach my $err (@$q_errors, @errors) {
373 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
374 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
380 'name' => 'Error exporting report!',
382 'errors' => $q_errors,
386 elsif ($phase eq 'Create report from SQL') {
387 # allow the user to paste in sql
388 if ($input->param('sql')) {
390 'sql' => $input->param('sql'),
391 'reportname' => $input->param('reportname'),
392 'notes' => $input->param('notes'),
395 $template->param('create' => 1);
398 elsif ($phase eq 'Create Compound Report'){
399 $template->param( 'savedreports' => get_saved_reports(),
404 elsif ($phase eq 'Save Compound'){
405 my $master = $input->param('master');
406 my $subreport = $input->param('subreport');
407 my ($mastertables,$subtables) = create_compound($master,$subreport);
408 $template->param( 'save_compound' => 1,
409 master=>$mastertables,
414 # pass $sth, get back an array of names for the column headers
415 sub header_cell_values ($) {
416 my $sth = shift or return ();
417 return @{$sth->{NAME}};
420 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
421 sub header_cell_loop ($) {
422 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
427 $template->param('build' . $_) and $template->param(buildx => $_) and last;
429 $template->param( 'referer' => $input->referer(),
430 'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
433 output_html_with_http_headers $input, $cookie, $template->output;