opac.css - button background fix for input.icon
[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     foreach my $table (@$tables) {
178         my @columns = _get_columns($table,$cgi);
179         push @allcolumns, @columns;
180     }
181     return ( \@allcolumns );
182 }
183
184 sub _get_columns {
185     my ($tablename,$cgi) = @_;
186     my $dbh         = C4::Context->dbh();
187     my $sth         = $dbh->prepare("show columns from $tablename");
188     $sth->execute();
189     my @columns;
190         my $column_defs = _get_column_defs($cgi);
191         my %tablehash;
192         $tablehash{'table'}=$tablename;
193         push @columns, \%tablehash;
194     while ( my $data = $sth->fetchrow_arrayref() ) {
195         my %temphash;
196         $temphash{'name'}        = "$tablename.$data->[0]";
197         $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
198         push @columns, \%temphash;
199     }
200     $sth->finish();
201     return (@columns);
202 }
203
204 =item build_query($columns,$criteria,$orderby,$area)
205
206 This will build the sql needed to return the results asked for, 
207 $columns is expected to be of the format tablename.columnname.
208 This is what get_columns returns.
209
210 =cut
211
212 sub build_query {
213     my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
214 ### $orderby
215     my $keys   = $keys{$area};
216     my $tables = $table_areas{$area};
217
218     my $sql =
219       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
220     return ($sql);
221 }
222
223 sub _build_query {
224     my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
225 ### $orderby
226     # $keys is an array of joining constraints
227     my $dbh           = C4::Context->dbh();
228     my $joinedtables  = join( ',', @$tables );
229     my $joinedcolumns = join( ',', @$columns );
230     my $joinedkeys    = join( ' AND ', @$keys );
231     my $query =
232       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
233         for (my $i=1;$i<@$tables;$i++){
234                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
235         }
236
237     if ($criteria) {
238                 $criteria =~ s/AND/WHERE/;
239         $query .= " $criteria";
240     }
241         if ($definition){
242                 my @definitions = split(',',$definition);
243                 my $deftext;
244                 foreach my $def (@definitions){
245                         my $defin=get_from_dictionary('',$def);
246                         $deftext .=" ".$defin->[0]->{'saved_sql'};
247                 }
248                 if ($query =~ /WHERE/i){
249                         $query .= $deftext;
250                 }
251                 else {
252                         $deftext  =~ s/AND/WHERE/;
253                         $query .= $deftext;                     
254                 }
255         }
256     if ($totals) {
257         my $groupby;
258         my @totcolumns = split( ',', $totals );
259         foreach my $total (@totcolumns) {
260             if ( $total =~ /\((.*)\)/ ) {
261                 if ( $groupby eq '' ) {
262                     $groupby = " GROUP BY $1";
263                 }
264                 else {
265                     $groupby .= ",$1";
266                 }
267             }
268         }
269         $query .= $groupby;
270     }
271     if ($orderby) {
272         $query .= $orderby;
273     }
274     return ($query);
275 }
276
277 =item get_criteria($area,$cgi);
278
279 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
280
281 =cut
282
283 sub get_criteria {
284     my ($area,$cgi) = @_;
285     my $dbh    = C4::Context->dbh();
286     my $crit   = $criteria{$area};
287         my $column_defs = _get_column_defs($cgi);
288     my @criteria_array;
289     foreach my $localcrit (@$crit) {
290         my ( $value, $type )   = split( /\|/, $localcrit );
291         my ( $table, $column ) = split( /\./, $value );
292         if ( $type eq 'date' ) {
293                         my %temp;
294             $temp{'name'}   = $value;
295             $temp{'date'}   = 1;
296                         $temp{'description'} = $column_defs->{$value};
297             push @criteria_array, \%temp;
298         }
299         else {
300
301             my $query =
302               "SELECT distinct($column) as availablevalues FROM $table";
303             my $sth = $dbh->prepare($query);
304             $sth->execute();
305             my @values;
306             while ( my $row = $sth->fetchrow_hashref() ) {
307                 push @values, $row;
308                 ### $row;
309             }
310             $sth->finish();
311             my %temp;
312             $temp{'name'}   = $value;
313                         $temp{'description'} = $column_defs->{$value};
314             $temp{'values'} = \@values;
315             push @criteria_array, \%temp;
316         }
317     }
318     return ( \@criteria_array );
319 }
320
321 sub execute_query {
322     my ( $sql, $type, $format, $id ) = @_;
323     my $dbh = C4::Context->dbh();
324
325     # take this line out when in production
326         if ($format eq 'url'){
327                 }
328         else {
329                 $sql .= " LIMIT 10";
330         }
331     my $sth = $dbh->prepare($sql);
332     $sth->execute();
333         my $colnames=$sth->{'NAME'};
334         my @results;
335         my $row;
336         my %temphash;
337         $row = join ('</th><th>',@$colnames);
338         $row = "<tr><th>$row</th></tr>";
339         $temphash{'row'} = $row;
340         push @results, \%temphash;
341     my $string;
342         my @xmlarray;
343     while ( my @data = $sth->fetchrow_array() ) {
344
345             # tabular
346             my %temphash;
347             my $row = join( '</td><td>', @data );
348             $row = "<tr><td>$row</td></tr>";
349             $temphash{'row'} = $row;
350             if ( $format eq 'text' ) {
351                 $string .= "\n" . $row;
352             }
353                         if ($format eq 'tab' ){
354                                 $row = join("\t",@data);
355                                 $string .="\n" . $row;
356                         }
357                         if ($format eq 'csv' ){
358                                 $row = join(",",@data);
359                                 $string .="\n" . $row;
360                         }
361                 if ($format eq 'url'){
362                         my $temphash;
363                         @$temphash{@$colnames}=@data;
364                         push @xmlarray,$temphash;
365                 }
366             push @results, \%temphash;
367 #        }
368     }
369     $sth->finish();
370     if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
371         return $string;
372     }
373         elsif ($format eq 'url') {
374                 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
375                 my $dump = new XML::Dumper;
376                 my $xml = $dump->pl2xml( \@xmlarray );
377                 store_results($id,$xml);
378                 return $url;
379         }
380     else {
381         return ( \@results );
382     }
383 }
384
385 =item save_report($sql,$name,$type,$notes)
386
387 Given some sql and a name this will saved it so that it can resued
388
389 =cut
390
391 sub save_report {
392     my ( $sql, $name, $type, $notes ) = @_;
393     my $dbh = C4::Context->dbh();
394     my $query =
395 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
396     my $sth = $dbh->prepare($query);
397     $sth->execute( 0, $sql, $name, $type, $notes );
398     $sth->finish();
399
400 }
401
402 sub store_results {
403         my ($id,$xml)=@_;
404         my $dbh = C4::Context->dbh();
405         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
406         my $sth = $dbh->prepare($query);
407         $sth->execute($id);
408         if (my $data=$sth->fetchrow_hashref()){
409                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
410                 my $sth2 = $dbh->prepare($query2);
411             $sth2->execute($xml,$id);
412                 $sth2->finish();
413         }
414         else {
415                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
416                 my $sth2 = $dbh->prepare($query2);
417                 $sth2->execute($id,$xml);
418                 $sth2->finish();
419         }
420         $sth->finish();
421 }
422
423 sub format_results {
424         my ($id) = @_;
425         my $dbh = C4::Context->dbh();
426         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
427         my $sth = $dbh->prepare($query);
428         $sth->execute($id);
429         my $data = $sth->fetchrow_hashref();
430         my $dump = new XML::Dumper;
431         my $perl = $dump->xml2pl( $data->{'report'} );
432         foreach my $row (@$perl) {
433                 my $htmlrow="<tr>";
434                 foreach my $key (keys %$row){
435                         $htmlrow .= "<td>$row->{$key}</td>";
436                 }
437                 $htmlrow .= "</tr>";
438                 $row->{'row'} = $htmlrow;
439         }
440         $sth->finish;
441         $query = "SELECT * FROM saved_sql WHERE id = ?";
442         $sth = $dbh->prepare($query);
443         $sth->execute($id);
444         $data = $sth->fetchrow_hashref();
445     $sth->finish();
446         return ($perl,$data->{'report_name'},$data->{'notes'}); 
447 }       
448
449 sub delete_report {
450         my ( $id ) = @_;
451         my $dbh = C4::Context->dbh();
452         my $query = "DELETE FROM saved_sql WHERE id = ?";
453         my $sth = $dbh->prepare($query);
454         $sth->execute($id);
455         $sth->finish();
456 }       
457
458 sub get_saved_reports {
459     my $dbh   = C4::Context->dbh();
460     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
461     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
462     ORDER by date_created";
463     my $sth   = $dbh->prepare($query);
464     $sth->execute();
465     my @reports;
466     while ( my $data = $sth->fetchrow_hashref() ) {
467         push @reports, $data;
468     }
469     $sth->finish();
470     return ( \@reports );
471 }
472
473 sub get_saved_report {
474     my ($id)  = @_;
475     my $dbh   = C4::Context->dbh();
476     my $query = " SELECT * FROM saved_sql WHERE id = ?";
477     my $sth   = $dbh->prepare($query);
478     $sth->execute($id);
479     my $data = $sth->fetchrow_hashref();
480     $sth->finish();
481     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
482 }
483
484 =item create_compound($masterID,$subreportID)
485
486 This will take 2 reports and create a compound report using both of them
487
488 =cut
489
490 sub create_compound {
491         my ($masterID,$subreportID) = @_;
492         my $dbh = C4::Context->dbh();
493         # get the reports
494         my ($mastersql,$mastertype) = get_saved_report($masterID);
495         my ($subsql,$subtype) = get_saved_report($subreportID);
496         
497         # now we have to do some checking to see how these two will fit together
498         # or if they will
499         my ($mastertables,$subtables);
500         if ($mastersql =~ / from (.*) where /i){ 
501                 $mastertables = $1;
502         }
503         if ($subsql =~ / from (.*) where /i){
504                 $subtables = $1;
505         }
506         return ($mastertables,$subtables);
507 }
508
509 =item get_column_type($column)
510
511 This takes a column name of the format table.column and will return what type it is
512 (free text, set values, date)
513
514 =cut
515
516 sub get_column_type {
517         my ($tablecolumn) = @_;
518         my ($table,$column) = split(/\./,$tablecolumn);
519         my $dbh = C4::Context->dbh();
520         my $catalog;
521         my $schema;
522
523         # mysql doesnt support a column selection, set column to %
524         my $tempcolumn='%';
525         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
526         while (my $info = $sth->fetchrow_hashref()){
527                 if ($info->{'COLUMN_NAME'} eq $column){
528                         #column we want
529                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
530                                 $info->{'TYPE_NAME'} = 'distinct';
531                         }
532                         return $info->{'TYPE_NAME'};            
533                 }
534         }
535         $sth->finish();
536 }
537
538 =item get_distinct_values($column)
539
540 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
541 with the distinct values of the column
542
543 =cut
544
545 sub get_distinct_values {
546         my ($tablecolumn) = @_;
547         my ($table,$column) = split(/\./,$tablecolumn);
548         my $dbh = C4::Context->dbh();
549         my $query =
550           "SELECT distinct($column) as availablevalues FROM $table";
551         my $sth = $dbh->prepare($query);
552         $sth->execute();
553         my @values;
554         while ( my $row = $sth->fetchrow_hashref() ) {
555                 push @values, $row;
556         }
557         $sth->finish();
558         return \@values;
559 }       
560
561 sub save_dictionary {
562         my ($name,$description,$sql,$area) = @_;
563         my $dbh = C4::Context->dbh();
564         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
565   VALUES (?,?,?,?,now(),now())";
566     my $sth = $dbh->prepare($query);
567     $sth->execute($name,$description,$sql,$area) || return 0;
568     $sth->finish();
569     return 1;
570 }
571
572 sub get_from_dictionary {
573         my ($area,$id) = @_;
574         my $dbh = C4::Context->dbh();
575         my $query = "SELECT * FROM reports_dictionary";
576         if ($area){
577                 $query.= " WHERE area = ?";
578         }
579         elsif ($id){
580                 $query.= " WHERE id = ?"
581         }
582         my $sth = $dbh->prepare($query);
583         if ($id){
584                 $sth->execute($id);
585         }
586         elsif ($area) {
587                 $sth->execute($area);
588         }
589         else {
590                 $sth->execute();
591         }
592         my @loop;
593         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
594         while (my $data = $sth->fetchrow_hashref()){
595                 $data->{'areaname'}=$reports[$data->{'area'}-1];
596                 push @loop,$data;
597                 
598         }
599         $sth->finish();
600         return (\@loop);
601 }
602
603 sub delete_definition {
604         my ($id) = @_;
605         my $dbh = C4::Context->dbh();
606         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
607         my $sth = $dbh->prepare($query);
608         $sth->execute($id);
609         $sth->finish();
610 }
611
612 sub get_sql {
613         my ($id) = @_;
614         my $dbh = C4::Context->dbh();
615         my $query = "SELECT * FROM saved_sql WHERE id = ?";
616         my $sth = $dbh->prepare($query);
617         $sth->execute($id);
618         my $data=$sth->fetchrow_hashref();
619         $sth->finish(); 
620         return $data->{'savedsql'};
621 }
622
623 sub _get_column_defs {
624         my ($cgi) = @_;
625         my %columns;
626         my $columns_def_file = "columns.def";
627         my $htdocs = C4::Context->config('intrahtdocs');                       
628         my $section='intranet';
629         my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
630
631         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
632         open (COLUMNS,$full_path_to_columns_def_file);
633         while (my $input = <COLUMNS>){
634                 my @row =split(/\t/,$input);
635                 $columns{$row[0]}=$row[1];
636         }
637
638         close COLUMNS;
639         return \%columns;
640 }
641 1;
642 __END__
643
644 =head1 AUTHOR
645
646 Chris Cormack <crc@liblime.com>
647
648 =cut