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