fixed variable masking warnings found by perl -w
[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.11;
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 get_sql );
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 $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
87 open (COLUMNS,$full_path_to_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         $query = "SELECT * FROM saved_sql WHERE id = ?";
451         $sth = $dbh->prepare($query);
452         $sth->execute($id);
453         $data = $sth->fetchrow_hashref();
454     $sth->finish();
455         return ($perl,$data->{'report_name'},$data->{'notes'}); 
456 }       
457
458 sub delete_report {
459         my ( $id ) = @_;
460         my $dbh = C4::Context->dbh();
461         my $query = "DELETE FROM saved_sql WHERE id = ?";
462         my $sth = $dbh->prepare($query);
463         $sth->execute($id);
464         $sth->finish();
465 }       
466
467 sub get_saved_reports {
468     my $dbh   = C4::Context->dbh();
469     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
470     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
471     ORDER by date_created";
472     my $sth   = $dbh->prepare($query);
473     $sth->execute();
474     my @reports;
475     while ( my $data = $sth->fetchrow_hashref() ) {
476         push @reports, $data;
477     }
478     $sth->finish();
479     return ( \@reports );
480 }
481
482 sub get_saved_report {
483     my ($id)  = @_;
484     my $dbh   = C4::Context->dbh();
485     my $query = " SELECT * FROM saved_sql WHERE id = ?";
486     my $sth   = $dbh->prepare($query);
487     $sth->execute($id);
488     my $data = $sth->fetchrow_hashref();
489     $sth->finish();
490     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
491 }
492
493 =item create_compound($masterID,$subreportID)
494
495 This will take 2 reports and create a compound report using both of them
496
497 =cut
498
499 sub create_compound {
500         my ($masterID,$subreportID) = @_;
501         my $dbh = C4::Context->dbh();
502         # get the reports
503         my ($mastersql,$mastertype) = get_saved_report($masterID);
504         my ($subsql,$subtype) = get_saved_report($subreportID);
505         
506         # now we have to do some checking to see how these two will fit together
507         # or if they will
508         my ($mastertables,$subtables);
509         if ($mastersql =~ / from (.*) where /i){ 
510                 $mastertables = $1;
511         }
512         if ($subsql =~ / from (.*) where /i){
513                 $subtables = $1;
514         }
515         return ($mastertables,$subtables);
516 }
517
518 =item get_column_type($column)
519
520 This takes a column name of the format table.column and will return what type it is
521 (free text, set values, date)
522
523 =cut
524
525 sub get_column_type {
526         my ($tablecolumn) = @_;
527         my ($table,$column) = split(/\./,$tablecolumn);
528         my $dbh = C4::Context->dbh();
529         my $catalog;
530         my $schema;
531
532         # mysql doesnt support a column selection, set column to %
533         my $tempcolumn='%';
534         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
535         while (my $info = $sth->fetchrow_hashref()){
536                 if ($info->{'COLUMN_NAME'} eq $column){
537                         #column we want
538                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
539                                 $info->{'TYPE_NAME'} = 'distinct';
540                         }
541                         return $info->{'TYPE_NAME'};            
542                 }
543         }
544         $sth->finish();
545 }
546
547 =item get_distinct_values($column)
548
549 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
550 with the distinct values of the column
551
552 =cut
553
554 sub get_distinct_values {
555         my ($tablecolumn) = @_;
556         my ($table,$column) = split(/\./,$tablecolumn);
557         my $dbh = C4::Context->dbh();
558         my $query =
559           "SELECT distinct($column) as availablevalues FROM $table";
560         my $sth = $dbh->prepare($query);
561         $sth->execute();
562         my @values;
563         while ( my $row = $sth->fetchrow_hashref() ) {
564                 push @values, $row;
565         }
566         $sth->finish();
567         return \@values;
568 }       
569
570 sub save_dictionary {
571         my ($name,$description,$sql,$area) = @_;
572         my $dbh = C4::Context->dbh();
573         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
574   VALUES (?,?,?,?,now(),now())";
575     my $sth = $dbh->prepare($query);
576     $sth->execute($name,$description,$sql,$area) || return 0;
577     $sth->finish();
578     return 1;
579 }
580
581 sub get_from_dictionary {
582         my ($area,$id) = @_;
583         my $dbh = C4::Context->dbh();
584         my $query = "SELECT * FROM reports_dictionary";
585         if ($area){
586                 $query.= " WHERE area = ?";
587         }
588         elsif ($id){
589                 $query.= " WHERE id = ?"
590         }
591         my $sth = $dbh->prepare($query);
592         if ($id){
593                 $sth->execute($id);
594         }
595         elsif ($area) {
596                 $sth->execute($area);
597         }
598         else {
599                 $sth->execute();
600         }
601         my @loop;
602         while (my $data = $sth->fetchrow_hashref()){
603                 push @loop,$data;
604                 
605                 }
606         $sth->finish();
607         return (\@loop);
608 }
609
610 sub delete_definition {
611         my ($id) = @_;
612         my $dbh = C4::Context->dbh();
613         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
614         my $sth = $dbh->prepare($query);
615         $sth->execute($id);
616         $sth->finish();
617 }
618
619 sub get_sql {
620         my ($id) = @_;
621         my $dbh = C4::Context->dbh();
622         my $query = "SELECT * FROM saved_sql WHERE id = ?";
623         my $sth = $dbh->prepare($query);
624         $sth->execute($id);
625         my $data=$sth->fetchrow_hashref();
626         $sth->finish(); 
627         return $data->{'savedsql'};
628 }
629
630 =head1 AUTHOR
631
632 Chris Cormack <crc@liblime.com>
633
634 =cut
635
636 1;