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