Bug 3066 - Overhaul guided reports
[koha-equinox.git] / C4 / Reports / Guided.pm
1 package C4::Reports::Guided;
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: this module needs a lot of repair to run clean under warnings
22 use CGI;
23 use Carp;
24
25 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Context;
27 use C4::Output;
28 use C4::Dates;
29 use XML::Simple;
30 use XML::Dumper;
31 use C4::Debug;
32 # use Smart::Comments;
33 # use Data::Dumper;
34
35 BEGIN {
36         # set the version for version checking
37         $VERSION = 0.12;
38         require Exporter;
39         @ISA = qw(Exporter);
40         @EXPORT = qw(
41                 get_report_types get_report_areas get_columns build_query get_criteria
42                 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
43                 get_column_type get_distinct_values save_dictionary get_from_dictionary
44                 delete_definition delete_report format_results get_sql
45         select_2_select_count_value
46         );
47 }
48
49 our %table_areas;
50 $table_areas{'1'} =
51   [ 'borrowers', 'statistics','items', 'biblioitems' ];    # circulation
52 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ];   # catalogue
53 $table_areas{'3'} = [ 'borrowers' ];        # patrons
54 $table_areas{'4'} = ['aqorders', 'biblio', 'items'];        # acquisitions
55 $table_areas{'5'} = [ 'borrowers', 'accountlines' ];        # accounts
56 our %keys;
57 $keys{'1'} = [
58     'statistics.borrowernumber=borrowers.borrowernumber',
59     'items.itemnumber = statistics.itemnumber',
60     'biblioitems.biblioitemnumber = items.biblioitemnumber'
61 ];
62 $keys{'2'} = [
63     'items.biblioitemnumber=biblioitems.biblioitemnumber',
64     'biblioitems.biblionumber=biblio.biblionumber'
65 ];
66 $keys{'3'} = [ ];
67 $keys{'4'} = [
68         'aqorders.biblionumber=biblio.biblionumber',
69         'biblio.biblionumber=items.biblionumber'
70 ];
71 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
72
73 # have to do someting here to know if its dropdown, free text, date etc
74
75 our %criteria;
76 $criteria{'1'} = [
77     'statistics.type',   'borrowers.categorycode',
78     'statistics.branch',
79     'biblioitems.publicationyear|date',
80     'items.dateaccessioned|date'
81 ];
82 $criteria{'2'} =
83   [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
84 $criteria{'3'} = ['borrowers.branchcode'];
85 $criteria{'4'} = ['aqorders.datereceived|date'];
86 $criteria{'5'} = ['borrowers.branchcode'];
87
88 if (C4::Context->preference('item-level_itypes')) {
89     unshift @{ $criteria{'1'} }, 'items.itype';
90     unshift @{ $criteria{'2'} }, 'items.itype';
91 } else {
92     unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
93     unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
94 }
95
96 =head1 NAME
97    
98 C4::Reports::Guided - Module for generating guided reports 
99
100 =head1 SYNOPSIS
101
102   use C4::Reports::Guided;
103
104 =head1 DESCRIPTION
105
106
107 =head1 METHODS
108
109 =over 2
110
111 =cut
112
113 =item get_report_types()
114
115 This will return a list of all the available report types
116
117 =cut
118
119 sub get_report_types {
120     my $dbh = C4::Context->dbh();
121
122     # FIXME these should be in the database perhaps
123     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
124     my @reports2;
125     for ( my $i = 0 ; $i < 3 ; $i++ ) {
126         my %hashrep;
127         $hashrep{id}   = $i + 1;
128         $hashrep{name} = $reports[$i];
129         push @reports2, \%hashrep;
130     }
131     return ( \@reports2 );
132
133 }
134
135 =item get_report_areas()
136
137 This will return a list of all the available report areas
138
139 =cut
140
141 sub get_report_areas {
142     my $dbh = C4::Context->dbh();
143
144     # FIXME these should be in the database
145     my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
146     my @reports2;
147     for ( my $i = 0 ; $i < 5 ; $i++ ) {
148         my %hashrep;
149         $hashrep{id}   = $i + 1;
150         $hashrep{name} = $reports[$i];
151         push @reports2, \%hashrep;
152     }
153     return ( \@reports2 );
154
155 }
156
157 =item get_all_tables()
158
159 This will return a list of all tables in the database 
160
161 =cut
162
163 sub get_all_tables {
164     my $dbh   = C4::Context->dbh();
165     my $query = "SHOW TABLES";
166     my $sth   = $dbh->prepare($query);
167     $sth->execute();
168     my @tables;
169     while ( my $data = $sth->fetchrow_arrayref() ) {
170         push @tables, $data->[0];
171     }
172     $sth->finish();
173     return ( \@tables );
174
175 }
176
177 =item get_columns($area)
178
179 This will return a list of all columns for a report area
180
181 =cut
182
183 sub get_columns {
184
185     # this calls the internal fucntion _get_columns
186     my ($area,$cgi) = @_;
187     my $tables = $table_areas{$area};
188     my @allcolumns;
189     my $first = 1;
190     foreach my $table (@$tables) {
191         my @columns = _get_columns($table,$cgi, $first);
192         $first = 0;
193         push @allcolumns, @columns;
194     }
195     return ( \@allcolumns );
196 }
197
198 sub _get_columns {
199     my ($tablename,$cgi, $first) = @_;
200     my $dbh         = C4::Context->dbh();
201     my $sth         = $dbh->prepare("show columns from $tablename");
202     $sth->execute();
203     my @columns;
204         my $column_defs = _get_column_defs($cgi);
205         my %tablehash;
206         $tablehash{'table'}=$tablename;
207     $tablehash{'__first__'} = $first;
208         push @columns, \%tablehash;
209     while ( my $data = $sth->fetchrow_arrayref() ) {
210         my %temphash;
211         $temphash{'name'}        = "$tablename.$data->[0]";
212         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
213         push @columns, \%temphash;
214     }
215     $sth->finish();
216     return (@columns);
217 }
218
219 =item build_query($columns,$criteria,$orderby,$area)
220
221 This will build the sql needed to return the results asked for, 
222 $columns is expected to be of the format tablename.columnname.
223 This is what get_columns returns.
224
225 =cut
226
227 sub build_query {
228     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
229 ### $orderby
230     my $keys   = $keys{$area};
231     my $tables = $table_areas{$area};
232
233     my $sql =
234       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
235     return ($sql);
236 }
237
238 sub _build_query {
239     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
240 ### $orderby
241     # $keys is an array of joining constraints
242     my $dbh           = C4::Context->dbh();
243     my $joinedtables  = join( ',', @$tables );
244     my $joinedcolumns = join( ',', @$columns );
245     my $joinedkeys    = join( ' AND ', @$keys );
246     my $query =
247       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
248         for (my $i=1;$i<@$tables;$i++){
249                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
250         }
251
252     if ($criteria) {
253                 $criteria =~ s/AND/WHERE/;
254         $query .= " $criteria";
255     }
256         if ($definition){
257                 my @definitions = split(',',$definition);
258                 my $deftext;
259                 foreach my $def (@definitions){
260                         my $defin=get_from_dictionary('',$def);
261                         $deftext .=" ".$defin->[0]->{'saved_sql'};
262                 }
263                 if ($query =~ /WHERE/i){
264                         $query .= $deftext;
265                 }
266                 else {
267                         $deftext  =~ s/AND/WHERE/;
268                         $query .= $deftext;                     
269                 }
270         }
271     if ($totals) {
272         my $groupby;
273         my @totcolumns = split( ',', $totals );
274         foreach my $total (@totcolumns) {
275             if ( $total =~ /\((.*)\)/ ) {
276                 if ( $groupby eq '' ) {
277                     $groupby = " GROUP BY $1";
278                 }
279                 else {
280                     $groupby .= ",$1";
281                 }
282             }
283         }
284         $query .= $groupby;
285     }
286     if ($orderby) {
287         $query .= $orderby;
288     }
289     return ($query);
290 }
291
292 =item get_criteria($area,$cgi);
293
294 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
295
296 =cut
297
298 sub get_criteria {
299     my ($area,$cgi) = @_;
300     my $dbh    = C4::Context->dbh();
301     my $crit   = $criteria{$area};
302         my $column_defs = _get_column_defs($cgi);
303     my @criteria_array;
304     foreach my $localcrit (@$crit) {
305         my ( $value, $type )   = split( /\|/, $localcrit );
306         my ( $table, $column ) = split( /\./, $value );
307         if ( $type eq 'date' ) {
308                         my %temp;
309             $temp{'name'}   = $value;
310             $temp{'date'}   = 1;
311                         $temp{'description'} = $column_defs->{$value};
312             push @criteria_array, \%temp;
313         }
314         else {
315
316             my $query =
317               "SELECT distinct($column) as availablevalues FROM $table";
318             my $sth = $dbh->prepare($query);
319             $sth->execute();
320             my @values;
321             while ( my $row = $sth->fetchrow_hashref() ) {
322                 push @values, $row;
323                 ### $row;
324             }
325             $sth->finish();
326             my %temp;
327             $temp{'name'}   = $value;
328                         $temp{'description'} = $column_defs->{$value};
329             $temp{'values'} = \@values;
330             push @criteria_array, \%temp;
331         }
332     }
333     return ( \@criteria_array );
334 }
335
336 =item execute_query
337
338 =over
339
340 ($results, $total, $error) = execute_query($sql, $offset, $limit)
341
342 =back
343
344     When passed C<$sql>, this function returns an array ref containing a result set
345     suitably formatted for display in html or for output as a flat file when passed in
346     C<$format> and C<$id>. It also returns the C<$total> records available for the
347     supplied query. If passed any query other than a SELECT, or if there is a db error,
348     C<$errors> an array ref is returned containing the error after this manner:
349
350     C<$error->{'sqlerr'}> contains the offending SQL keyword.
351     C<$error->{'queryerr'}> contains the native db engine error returned for the query.
352     
353     Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
354     C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
355     in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
356     the user in a user-supplied SQL query WILL apply in any case.
357
358 =cut
359
360 # returns $sql, $offset, $limit
361 # $sql returned will be transformed to:
362 #  ~ remove any LIMIT clause
363 #  ~ repace SELECT clause w/ SELECT count(*)
364
365 sub select_2_select_count_value ($) {
366     my $sql = shift or return;
367     my $countsql = select_2_select_count($sql);
368     $debug and warn "original query: $sql\ncount query: $countsql\n";
369     my $sth1 = C4::Context->dbh->prepare($countsql);
370     $sth1->execute();
371     my $total = $sth1->fetchrow();
372     $debug and warn "total records for this query: $total\n";
373     return $total;
374 }
375 sub select_2_select_count ($) {
376     # Modify the query passed in to create a count query... (I think this covers all cases -crn)
377     my ($sql) = strip_limit(shift) or return;
378     $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
379     return $sql;
380 }
381 sub strip_limit ($) {
382     my $sql = shift or return;
383     ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
384     $sql =~ s/\bLIMIT\b\s*\d+(\,\s*\d+)?\s*/ /ig;
385     return ($sql, (defined $1 ? $1 : 0), $2);   # offset can default to 0, LIMIT cannot!
386 }
387
388 sub execute_query ($;$$$) {
389
390     my ( $sql, $offset, $limit, $no_count ) = @_;
391
392     # check parameters
393     unless ($sql) {
394         carp "execute_query() called without SQL argument";
395         return;
396     }
397     $offset = 0    unless $offset;
398     $limit  = 9999 unless $limit;
399     $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
400     if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
401         return (undef, {  sqlerr => $1} );
402     } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
403         return (undef, { queryerr => 'Missing SELECT'} );
404     }
405
406     my ($useroffset, $userlimit);
407
408     # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
409     ($sql, $useroffset, $userlimit) = strip_limit($sql);
410     $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
411         $useroffset,
412         (defined($userlimit ) ? $userlimit  : 'UNDEF');
413     $offset += $useroffset;
414     my $total;
415     if (defined($userlimit)) {
416         if ($offset + $limit > $userlimit ) {
417             $limit = $userlimit - $offset;
418         }
419         $total = $userlimit if $userlimit < $total;     # we will never exceed a user defined LIMIT and...
420         $userlimit = $total if $userlimit > $total;     # we will never exceed the total number of records available to satisfy the query
421     }
422     $sql .= " LIMIT ?, ?";
423
424     my $sth = C4::Context->dbh->prepare($sql);
425     $sth->execute($offset, $limit);
426     return ( $sth );
427     # my @xmlarray = ... ;
428     # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
429     # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
430     # store_results($id,$xml);
431 }
432
433 =item save_report($sql,$name,$type,$notes)
434
435 Given some sql and a name this will saved it so that it can resued
436
437 =cut
438
439 sub save_report {
440     my ( $sql, $name, $type, $notes ) = @_;
441     my $dbh = C4::Context->dbh();
442     $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
443     my $query =
444 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
445     my $sth = $dbh->prepare($query);
446     $sth->execute( 0, $sql, $name, $type, $notes );
447 }
448
449 sub store_results {
450         my ($id,$xml)=@_;
451         my $dbh = C4::Context->dbh();
452         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
453         my $sth = $dbh->prepare($query);
454         $sth->execute($id);
455         if (my $data=$sth->fetchrow_hashref()){
456                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
457                 my $sth2 = $dbh->prepare($query2);
458             $sth2->execute($xml,$id);
459         }
460         else {
461                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
462                 my $sth2 = $dbh->prepare($query2);
463                 $sth2->execute($id,$xml);
464         }
465 }
466
467 sub format_results {
468         my ($id) = @_;
469         my $dbh = C4::Context->dbh();
470         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
471         my $sth = $dbh->prepare($query);
472         $sth->execute($id);
473         my $data = $sth->fetchrow_hashref();
474         my $dump = new XML::Dumper;
475         my $perl = $dump->xml2pl( $data->{'report'} );
476         foreach my $row (@$perl) {
477                 my $htmlrow="<tr>";
478                 foreach my $key (keys %$row){
479                         $htmlrow .= "<td>$row->{$key}</td>";
480                 }
481                 $htmlrow .= "</tr>";
482                 $row->{'row'} = $htmlrow;
483         }
484         $sth->finish;
485         $query = "SELECT * FROM saved_sql WHERE id = ?";
486         $sth = $dbh->prepare($query);
487         $sth->execute($id);
488         $data = $sth->fetchrow_hashref();
489         return ($perl,$data->{'report_name'},$data->{'notes'}); 
490 }       
491
492 sub delete_report {
493         my ( $id ) = @_;
494         my $dbh = C4::Context->dbh();
495         my $query = "DELETE FROM saved_sql WHERE id = ?";
496         my $sth = $dbh->prepare($query);
497         $sth->execute($id);
498 }       
499
500 sub get_saved_reports {
501     my $dbh   = C4::Context->dbh();
502     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
503     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
504     ORDER by date_created";
505     my $sth   = $dbh->prepare($query);
506     $sth->execute();
507     return $sth->fetchall_arrayref({});
508 }
509
510 sub get_saved_report {
511     my ($id)  = @_;
512     my $dbh   = C4::Context->dbh();
513     my $query = " SELECT * FROM saved_sql WHERE id = ?";
514     my $sth   = $dbh->prepare($query);
515     $sth->execute($id);
516     my $data = $sth->fetchrow_hashref();
517     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
518 }
519
520 =item create_compound($masterID,$subreportID)
521
522 This will take 2 reports and create a compound report using both of them
523
524 =cut
525
526 sub create_compound {
527         my ($masterID,$subreportID) = @_;
528         my $dbh = C4::Context->dbh();
529         # get the reports
530         my ($mastersql,$mastertype) = get_saved_report($masterID);
531         my ($subsql,$subtype) = get_saved_report($subreportID);
532         
533         # now we have to do some checking to see how these two will fit together
534         # or if they will
535         my ($mastertables,$subtables);
536         if ($mastersql =~ / from (.*) where /i){ 
537                 $mastertables = $1;
538         }
539         if ($subsql =~ / from (.*) where /i){
540                 $subtables = $1;
541         }
542         return ($mastertables,$subtables);
543 }
544
545 =item get_column_type($column)
546
547 This takes a column name of the format table.column and will return what type it is
548 (free text, set values, date)
549
550 =cut
551
552 sub get_column_type {
553         my ($tablecolumn) = @_;
554         my ($table,$column) = split(/\./,$tablecolumn);
555         my $dbh = C4::Context->dbh();
556         my $catalog;
557         my $schema;
558
559         # mysql doesnt support a column selection, set column to %
560         my $tempcolumn='%';
561         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
562         while (my $info = $sth->fetchrow_hashref()){
563                 if ($info->{'COLUMN_NAME'} eq $column){
564                         #column we want
565                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
566                                 $info->{'TYPE_NAME'} = 'distinct';
567                         }
568                         return $info->{'TYPE_NAME'};            
569                 }
570         }
571 }
572
573 =item get_distinct_values($column)
574
575 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
576 with the distinct values of the column
577
578 =cut
579
580 sub get_distinct_values {
581         my ($tablecolumn) = @_;
582         my ($table,$column) = split(/\./,$tablecolumn);
583         my $dbh = C4::Context->dbh();
584         my $query =
585           "SELECT distinct($column) as availablevalues FROM $table";
586         my $sth = $dbh->prepare($query);
587         $sth->execute();
588     return $sth->fetchall_arrayref({});
589 }       
590
591 sub save_dictionary {
592         my ($name,$description,$sql,$area) = @_;
593         my $dbh = C4::Context->dbh();
594         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
595   VALUES (?,?,?,?,now(),now())";
596     my $sth = $dbh->prepare($query);
597     $sth->execute($name,$description,$sql,$area) || return 0;
598     return 1;
599 }
600
601 sub get_from_dictionary {
602         my ($area,$id) = @_;
603         my $dbh = C4::Context->dbh();
604         my $query = "SELECT * FROM reports_dictionary";
605         if ($area){
606                 $query.= " WHERE area = ?";
607         }
608         elsif ($id){
609                 $query.= " WHERE id = ?"
610         }
611         my $sth = $dbh->prepare($query);
612         if ($id){
613                 $sth->execute($id);
614         }
615         elsif ($area) {
616                 $sth->execute($area);
617         }
618         else {
619                 $sth->execute();
620         }
621         my @loop;
622         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
623         while (my $data = $sth->fetchrow_hashref()){
624                 $data->{'areaname'}=$reports[$data->{'area'}-1];
625                 push @loop,$data;
626                 
627         }
628         return (\@loop);
629 }
630
631 sub delete_definition {
632         my ($id) = @_ or return;
633         my $dbh = C4::Context->dbh();
634         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
635         my $sth = $dbh->prepare($query);
636         $sth->execute($id);
637 }
638
639 sub get_sql {
640         my ($id) = @_ or return;
641         my $dbh = C4::Context->dbh();
642         my $query = "SELECT * FROM saved_sql WHERE id = ?";
643         my $sth = $dbh->prepare($query);
644         $sth->execute($id);
645         my $data=$sth->fetchrow_hashref();
646         return $data->{'savedsql'};
647 }
648
649 sub _get_column_defs {
650         my ($cgi) = @_;
651         my %columns;
652         my $columns_def_file = "columns.def";
653         my $htdocs = C4::Context->config('intrahtdocs');                       
654         my $section='intranet';
655         my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
656
657         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
658         open (COLUMNS,$full_path_to_columns_def_file);
659         while (my $input = <COLUMNS>){
660                 my @row =split(/\t/,$input);
661                 $columns{$row[0]}=$row[1];
662         }
663
664         close COLUMNS;
665         return \%columns;
666 }
667 1;
668 __END__
669
670 =back
671
672 =head1 AUTHOR
673
674 Chris Cormack <crc@liblime.com>
675
676 =cut