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');
58 $template->param( 'start' => 1 );
61 elsif ( $phase eq 'Build new' ) {
63 $template->param( 'build1' => 1 );
64 $template->param( 'areas' => get_report_areas() );
66 elsif ( $phase eq 'Use saved' ) {
68 # get list of reports and display them
69 $template->param( 'saved1' => 1 );
70 $template->param( 'savedreports' => get_saved_reports() );
73 elsif ( $phase eq 'Delete Saved') {
75 # delete a report from the saved reports list
76 my $id = $input->param('reports');
78 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
82 elsif ( $phase eq 'Show SQL'){
84 my $id = $input->param('reports');
85 my $sql = get_sql($id);
92 elsif ( $phase eq 'Edit SQL'){
94 my $id = $input->param('reports');
95 my ($sql,$type,$reportname,$notes) = get_saved_report($id);
98 'reportname' => $reportname,
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');
111 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
112 push @errors, {sqlerr => $1};
114 elsif ($sql !~ /^(SELECT)/i) {
115 push @errors, {queryerr => 1};
119 'errors' => \@errors,
124 update_sql( $id, $sql, $reportname, $notes );
126 'save_successful' => 1,
132 elsif ($phase eq 'retrieve results') {
133 my $id = $input->param('id');
134 my ($results,$name,$notes) = format_results($id);
138 'results' => $results,
144 elsif ( $phase eq 'Report on this Area' ) {
146 # they have choosen a new report and the area to report on
149 'area' => $input->param('areas'),
150 'types' => get_report_types(),
154 elsif ( $phase eq 'Choose this type' ) {
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');
164 columns => get_columns($area,$input),
168 elsif ( $phase eq 'Choose these columns' ) {
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 );
181 definitions => get_from_dictionary($area),
182 criteria => get_criteria($area,$input),
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');
194 foreach my $crit (@criteria) {
195 my $value = $input->param( $crit . "_value" );
197 # If value is not defined, then it may be range values
200 my $fromvalue = $input->param( "from_" . $crit . "_value" );
201 my $tovalue = $input->param( "to_" . $crit . "_value" );
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");
209 if ($fromvalue && $tovalue) {
210 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
216 if ($value =~ C4::Dates->regexp('syspref')) {
217 $value = C4::Dates->new($value)->output("iso");
219 $query_criteria .= " AND $crit='$value'";
221 warn $query_criteria;
229 'definition' => $definition,
230 'criteriastring' => $query_criteria,
234 my @columns = split( ',', $column );
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;
247 $template->param( 'total_by' => \@total_by );
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');
258 foreach my $total (@total_by) {
259 my $value = $input->param( $total . "_tvalue" );
260 $totals .= "$value($total),";
268 'criteriastring' => $criteria,
270 'definition' => $definition,
274 my @columns = split( ',', $column );
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;
286 $template->param( 'order_by' => \@order_by );
289 elsif ( $phase eq 'Build Report' ) {
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');
305 foreach my $order (@order_by) {
306 my $value = $input->param( $order . "_ovalue" );
307 if ($query_orderby) {
308 $query_orderby .= ",$order $value";
311 $query_orderby = " ORDER BY $order $value";
317 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
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');
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};
345 elsif ($sql !~ /^(SELECT)/i) {
346 push @errors, {queryerr => 1};
350 'errors' => \@errors,
352 'reportname'=> $name,
358 save_report( $borrowernumber, $sql, $name, $type, $notes );
360 'save_successful' => 1,
365 elsif ($phase eq 'Run this report'){
366 # execute a saved report
367 my $limit = 20; # page size. # TODO: move to DB or syspref?
369 my $report = $input->param('reports');
371 if ($input->param('page')) {
372 $offset = ($input->param('page') - 1) * $limit;
374 my ($sql,$type,$name,$notes) = get_saved_report($report);
376 push @errors, {no_sql_for_id=>$report};
379 my ($sth, $errors) = execute_query($sql, $offset, $limit);
380 my $total = select_2_select_count_value($sql) || 0;
382 die "execute_query failed to return sth for report $report: $sql";
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 };
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";
402 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
403 'unlimited_total' => $total,
407 elsif ($phase eq 'Export'){
408 binmode STDOUT, ':utf8';
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"
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";
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";
429 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
431 while (my $row = $sth->fetchrow_arrayref()) {
432 if ($csv->combine(@$row)) {
433 print $csv->string(), "\n";
435 push @$q_errors, { combine => $csv->error_diag() } ;
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.
447 'name' => 'Error exporting report!',
449 'errors' => $q_errors,
453 elsif ($phase eq 'Create report from SQL') {
454 # allow the user to paste in sql
455 if ($input->param('sql')) {
457 'sql' => $input->param('sql'),
458 'reportname' => $input->param('reportname'),
459 'notes' => $input->param('notes'),
462 $template->param('create' => 1);
465 elsif ($phase eq 'Create Compound Report'){
466 $template->param( 'savedreports' => get_saved_reports(),
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,
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}};
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);
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}};
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);
506 $template->param('build' . $_) and $template->param(buildx => $_) and last;
508 $template->param( 'referer' => $input->referer(),
509 'DHTMLcalendar_dateformat' => C4::Dates->DHTMLcalendar(),
512 output_html_with_http_headers $input, $cookie, $template->output;