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 $phase = $input->param('phase');
46 if ( $phase eq 'Build new' ) {
47 $flagsrequired = 'create_report';
49 elsif ( $phase eq 'Use saved' ) {
50 $flagsrequired = 'execute_report';
55 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
57 template_name => "reports/guided_reports_start.tmpl",
61 flagsrequired => { reports => $flagsrequired },
68 $template->param( 'start' => 1 );
71 elsif ( $phase eq 'Build new' ) {
73 $template->param( 'build1' => 1 );
74 $template->param( 'areas' => get_report_areas() );
76 elsif ( $phase eq 'Use saved' ) {
78 # get list of reports and display them
79 $template->param( 'saved1' => 1 );
80 $template->param( 'savedreports' => get_saved_reports() );
83 elsif ( $phase eq 'Delete Saved') {
85 # delete a report from the saved reports list
86 my $id = $input->param('reports');
88 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
92 elsif ( $phase eq 'Show SQL'){
94 my $id = $input->param('reports');
95 my $sql = get_sql($id);
102 elsif ( $phase eq 'Edit SQL'){
104 my $id = $input->param('reports');
105 my ($sql,$type,$reportname,$notes) = get_saved_report($id);
108 'reportname' => $reportname,
115 elsif ( $phase eq 'Update SQL'){
116 my $id = $input->param('id');
117 my $sql = $input->param('sql');
118 my $reportname = $input->param('reportname');
119 my $notes = $input->param('notes');
121 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
122 push @errors, {sqlerr => $1};
124 elsif ($sql !~ /^(SELECT)/i) {
125 push @errors, {queryerr => 1};
129 'errors' => \@errors,
134 update_sql( $id, $sql, $reportname, $notes );
136 'save_successful' => 1,
142 elsif ($phase eq 'retrieve results') {
143 my $id = $input->param('id');
144 my ($results,$name,$notes) = format_results($id);
148 'results' => $results,
154 elsif ( $phase eq 'Report on this Area' ) {
156 # they have choosen a new report and the area to report on
159 'area' => $input->param('areas'),
160 'types' => get_report_types(),
164 elsif ( $phase eq 'Choose this type' ) {
166 # they have chosen type and area
167 # get area and type and pass them to the template
168 my $area = $input->param('area');
169 my $type = $input->param('types');
174 columns => get_columns($area,$input),
178 elsif ( $phase eq 'Choose these columns' ) {
180 # we now know type, area, and columns
181 # next step is the constraints
182 my $area = $input->param('area');
183 my $type = $input->param('type');
184 my @columns = $input->param('columns');
185 my $column = join( ',', @columns );
191 definitions => get_from_dictionary($area),
192 criteria => get_criteria($area,$input),
196 elsif ( $phase eq 'Choose these criteria' ) {
197 my $area = $input->param('area');
198 my $type = $input->param('type');
199 my $column = $input->param('column');
200 my @definitions = $input->param('definition');
201 my $definition = join (',',@definitions);
202 my @criteria = $input->param('criteria_column');
204 foreach my $crit (@criteria) {
205 my $value = $input->param( $crit . "_value" );
207 # If value is not defined, then it may be range values
210 my $fromvalue = $input->param( "from_" . $crit . "_value" );
211 my $tovalue = $input->param( "to_" . $crit . "_value" );
213 # If the range values are dates
214 if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) {
215 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
216 $tovalue = C4::Dates->new($tovalue)->output("iso");
219 if ($fromvalue && $tovalue) {
220 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
226 if ($value =~ C4::Dates->regexp('syspref')) {
227 $value = C4::Dates->new($value)->output("iso");
229 $query_criteria .= " AND $crit='$value'";
231 warn $query_criteria;
239 'definition' => $definition,
240 'criteriastring' => $query_criteria,
244 my @columns = split( ',', $column );
247 # build structue for use by tmpl_loop to choose columns to order by
248 # need to do something about the order of the order :)
249 # we also want to use the %columns hash to get the plain english names
250 foreach my $col (@columns) {
251 my %total = (name => $col);
252 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
253 $total{'select'} = \@selects;
254 push @total_by, \%total;
257 $template->param( 'total_by' => \@total_by );
260 elsif ( $phase eq 'Choose These Operations' ) {
261 my $area = $input->param('area');
262 my $type = $input->param('type');
263 my $column = $input->param('column');
264 my $criteria = $input->param('criteria');
265 my $definition = $input->param('definition');
266 my @total_by = $input->param('total_by');
268 foreach my $total (@total_by) {
269 my $value = $input->param( $total . "_tvalue" );
270 $totals .= "$value($total),";
278 'criteriastring' => $criteria,
280 'definition' => $definition,
284 my @columns = split( ',', $column );
287 # build structue for use by tmpl_loop to choose columns to order by
288 # need to do something about the order of the order :)
289 foreach my $col (@columns) {
290 my %order = (name => $col);
291 my @selects = map {+{ value => $_ }} (qw(asc desc));
292 $order{'select'} = \@selects;
293 push @order_by, \%order;
296 $template->param( 'order_by' => \@order_by );
299 elsif ( $phase eq 'Build Report' ) {
301 # now we have all the info we need and can build the sql
302 my $area = $input->param('area');
303 my $type = $input->param('type');
304 my $column = $input->param('column');
305 my $crit = $input->param('criteria');
306 my $totals = $input->param('totals');
307 my $definition = $input->param('definition');
308 # my @criteria = split( ',', $crit );
309 my $query_criteria=$crit;
310 # split the columns up by ,
311 my @columns = split( ',', $column );
312 my @order_by = $input->param('order_by');
315 foreach my $order (@order_by) {
316 my $value = $input->param( $order . "_ovalue" );
317 if ($query_orderby) {
318 $query_orderby .= ",$order $value";
321 $query_orderby = " ORDER BY $order $value";
327 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
335 elsif ( $phase eq 'Save' ) {
336 # Save the report that has just been built
337 my $sql = $input->param('sql');
338 my $type = $input->param('type');
346 elsif ( $phase eq 'Save Report' ) {
347 # save the sql pasted in by a user
348 my $sql = $input->param('sql');
349 my $name = $input->param('reportname');
350 my $type = $input->param('types');
351 my $notes = $input->param('notes');
352 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
353 push @errors, {sqlerr => $1};
355 elsif ($sql !~ /^(SELECT)/i) {
356 push @errors, {queryerr => 1};
360 'errors' => \@errors,
362 'reportname'=> $name,
368 save_report( $borrowernumber, $sql, $name, $type, $notes );
370 'save_successful' => 1,
375 elsif ($phase eq 'Run this report'){
376 # execute a saved report
377 my $limit = 20; # page size. # TODO: move to DB or syspref?
379 my $report = $input->param('reports');
381 if ($input->param('page')) {
382 $offset = ($input->param('page') - 1) * $limit;
384 my ($sql,$type,$name,$notes) = get_saved_report($report);
386 push @errors, {no_sql_for_id=>$report};
389 my ($sth, $errors) = execute_query($sql, $offset, $limit);
390 my $total = select_2_select_count_value($sql) || 0;
392 die "execute_query failed to return sth for report $report: $sql";
394 my $headref = $sth->{NAME} || [];
395 my @headers = map { +{ cell => $_ } } @$headref;
396 $template->param(header_row => \@headers);
397 while (my $row = $sth->fetchrow_arrayref()) {
398 my @cells = map { +{ cell => $_ } } @$row;
399 push @rows, { cells => \@cells };
403 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
404 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report&phase=Run%20this%20report";
412 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
413 'unlimited_total' => $total,
417 elsif ($phase eq 'Export'){
418 binmode STDOUT, ':utf8';
420 # export results to tab separated text or CSV
421 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
422 my $format = $input->param('format');
423 my ($sth, $q_errors) = execute_query($sql);
424 unless ($q_errors and @$q_errors) {
425 print $input->header( -type => 'application/octet-stream',
426 -attachment=>"reportresults.$format"
428 if ($format eq 'tab') {
429 print join("\t", header_cell_values($sth)), "\n";
430 while (my $row = $sth->fetchrow_arrayref()) {
431 print join("\t", @$row), "\n";
434 my $csv = Text::CSV->new({binary => 1});
435 $csv or die "Text::CSV->new({binary => 1}) FAILED: " . Text::CSV->error_diag();
436 if ($csv->combine(header_cell_values($sth))) {
437 print $csv->string(), "\n";
439 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
441 while (my $row = $sth->fetchrow_arrayref()) {
442 if ($csv->combine(@$row)) {
443 print $csv->string(), "\n";
445 push @$q_errors, { combine => $csv->error_diag() } ;
449 foreach my $err (@$q_errors, @errors) {
450 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
451 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
457 'name' => 'Error exporting report!',
459 'errors' => $q_errors,
463 elsif ($phase eq 'Create report from SQL') {
464 # allow the user to paste in sql
465 if ($input->param('sql')) {
467 'sql' => $input->param('sql'),
468 'reportname' => $input->param('reportname'),
469 'notes' => $input->param('notes'),
472 $template->param('create' => 1);
475 elsif ($phase eq 'Create Compound Report'){
476 $template->param( 'savedreports' => get_saved_reports(),
481 elsif ($phase eq 'Save Compound'){
482 my $master = $input->param('master');
483 my $subreport = $input->param('subreport');
484 my ($mastertables,$subtables) = create_compound($master,$subreport);
485 $template->param( 'save_compound' => 1,
486 master=>$mastertables,
491 # pass $sth, get back an array of names for the column headers
492 sub header_cell_values {
493 my $sth = shift or return ();
494 return @{$sth->{NAME}};
497 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
498 sub header_cell_loop {
499 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
503 # pass $sth, get back an array of names for the column headers
504 sub header_cell_values {
505 my $sth = shift or return ();
506 return @{$sth->{NAME}};
509 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
510 sub header_cell_loop {
511 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
516 $template->param('build' . $_) and $template->param(buildx => $_) and last;
518 $template->param( 'referer' => $input->referer(),
519 'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
522 output_html_with_http_headers $input, $cookie, $template->output;