Adding reports code
[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 Smart::Comments;
27
28 # set the version for version checking
29 $VERSION = 0.01;
30
31 @ISA = qw(Exporter);
32 @EXPORT =
33   qw(get_report_types get_report_areas get_columns build_query get_criteria
34   save_report get_saved_reports execute_query get_saved_report create_compound run_compound);
35
36 our %table_areas;
37 $table_areas{'1'} =
38   [ 'borrowers', 'statistics','items', 'biblioitems' ];    # circulation
39 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ];   # catalogue
40 $table_areas{'3'} = [ 'borrowers', 'accountlines' ];        # patrons
41 $table_areas{'4'} = ['aqorders', 'biblio', 'items'];        # acquisitions
42
43 our %keys;
44 $keys{'1'} = [
45     'statistics.borrowernumber=borrowers.borrowernumber',
46     'items.itemnumber = statistics.itemnumber',
47     'biblioitems.biblioitemnumber = items.biblioitemnumber'
48 ];
49 $keys{'2'} = [
50     'items.biblioitemnumber=biblioitems.biblioitemnumber',
51     'biblioitems.biblionumber=biblio.biblionumber'
52 ];
53 $keys{'3'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
54 $keys{'4'} = [
55         'aqorders.biblionumber=biblio.biblionumber',
56         'biblio.biblionumber=items.biblionumber'
57 ];
58
59 # have to do someting here to know if its dropdown, free text, date etc
60
61 our %criteria;
62 $criteria{'1'} = [
63     'statistics.type',   'borrowers.categorycode',
64     'statistics.branch', 'biblioitems.itemtype',
65     'biblioitems.publicationyear|date',
66     'items.dateaccessioned|date'
67 ];
68 $criteria{'2'} =
69   [ 'biblioitems.itemtype', 'items.holdingbranch', 'items.homebranch' ,'items.itemlost'];
70 $criteria{'3'} = ['borrowers.branchcode'];
71 $criteria{'4'} = ['aqorders.datereceived|date'];
72
73
74 our %columns;
75 my $columns_def_file = "columns.def";
76 my $htdocs = C4::Context->config('intrahtdocs');                       
77 my $section='intranet';
78 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section);                                                                                 
79
80 my $columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
81 open (COLUMNS,$columns_def_file);
82 while (my $input = <COLUMNS>){
83         my @row =split(/\t/,$input);
84         $columns{$row[0]}=$row[1];
85 }
86
87 close COLUMNS;
88
89 =head1 NAME
90    
91 C4::Reports - Module for generating reports 
92
93 =head1 SYNOPSIS
94
95   use C4::Reports;
96
97 =head1 DESCRIPTION
98
99
100 =head1 METHODS
101
102 =over 2
103
104 =cut
105
106 =item get_report_types()
107
108 This will return a list of all the available report types
109
110 =cut
111
112 sub get_report_types {
113     my $dbh = C4::Context->dbh();
114
115     # FIXME these should be in the database perhaps
116     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
117     my @reports2;
118     for ( my $i = 0 ; $i < 3 ; $i++ ) {
119         my %hashrep;
120         $hashrep{id}   = $i + 1;
121         $hashrep{name} = $reports[$i];
122         push @reports2, \%hashrep;
123     }
124     return ( \@reports2 );
125
126 }
127
128 =item get_report_areas()
129
130 This will return a list of all the available report areas
131
132 =cut
133
134 sub get_report_areas {
135     my $dbh = C4::Context->dbh();
136
137     # FIXME these should be in the database
138     my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions' );
139     my @reports2;
140     for ( my $i = 0 ; $i < 4 ; $i++ ) {
141         my %hashrep;
142         $hashrep{id}   = $i + 1;
143         $hashrep{name} = $reports[$i];
144         push @reports2, \%hashrep;
145     }
146     return ( \@reports2 );
147
148 }
149
150 =item get_all_tables()
151
152 This will return a list of all tables in the database 
153
154 =cut
155
156 sub get_all_tables {
157     my $dbh   = C4::Context->dbh();
158     my $query = "SHOW TABLES";
159     my $sth   = $dbh->prepare($query);
160     $sth->execute();
161     my @tables;
162     while ( my $data = $sth->fetchrow_arrayref() ) {
163         push @tables, $data->[0];
164     }
165     $sth->finish();
166     return ( \@tables );
167
168 }
169
170 =item get_columns($area)
171
172 This will return a list of all columns for a report area
173
174 =cut
175
176 sub get_columns {
177
178     # this calls the internal fucntion _get_columns
179     my ($area) = @_;
180     my $tables = $table_areas{$area};
181     my @allcolumns;
182     foreach my $table (@$tables) {
183         my @columns = _get_columns($table);
184         push @allcolumns, @columns;
185     }
186     return ( \@allcolumns );
187 }
188
189 sub _get_columns {
190     my ($tablename) = @_;
191     my $dbh         = C4::Context->dbh();
192     my $sth         = $dbh->prepare("show columns from $tablename");
193     $sth->execute();
194     my @columns;
195         my %tablehash;
196         $tablehash{'table'}=$tablename;
197         push @columns, \%tablehash;
198     while ( my $data = $sth->fetchrow_arrayref() ) {
199         my %temphash;
200         $temphash{'name'}        = "$tablename.$data->[0]";
201         $temphash{'description'} = $columns{"$tablename.$data->[0]"};
202         push @columns, \%temphash;
203     }
204     $sth->finish();
205     return (@columns);
206 }
207
208 =item build_query($columns,$criteria,$orderby,$area)
209
210 This will build the sql needed to return the results asked for, 
211 $columns is expected to be of the format tablename.columnname.
212 This is what get_columns returns.
213
214 =cut
215
216 sub build_query {
217     my ( $columns, $criteria, $orderby, $area, $totals ) = @_;
218 ### $orderby
219     my $keys   = $keys{$area};
220     my $tables = $table_areas{$area};
221
222     my $sql =
223       _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals );
224     return ($sql);
225 }
226
227 sub _build_query {
228     my ( $tables, $columns, $criteria, $keys, $orderby, $totals ) = @_;
229 ### $orderby
230     # $keys is an array of joining constraints
231     my $dbh           = C4::Context->dbh();
232     my $joinedtables  = join( ',', @$tables );
233     my $joinedcolumns = join( ',', @$columns );
234     my $joinedkeys    = join( ' AND ', @$keys );
235     my $query =
236       "SELECT $totals $joinedcolumns FROM $tables->[0] ";
237         for (my $i=1;$i<@$tables;$i++){
238                 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
239         }
240
241     if ($criteria) {
242                 $criteria =~ s/AND/WHERE/;
243         $query .= " $criteria";
244     }
245     if ($totals) {
246         my $groupby;
247         my @totcolumns = split( ',', $totals );
248         foreach my $total (@totcolumns) {
249             if ( $total =~ /\((.*)\)/ ) {
250                 if ( $groupby eq '' ) {
251                     $groupby = " GROUP BY $1";
252                 }
253                 else {
254                     $groupby .= ",$1";
255                 }
256             }
257         }
258         $query .= $groupby;
259     }
260     if ($orderby) {
261         $query .= $orderby;
262     }
263     return ($query);
264 }
265
266 =item get_criteria($area);
267
268 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
269
270 =cut
271
272 sub get_criteria {
273     my ($area) = @_;
274     my $dbh    = C4::Context->dbh();
275     my $crit   = $criteria{$area};
276     my @criteria_array;
277     foreach my $localcrit (@$crit) {
278         my ( $value, $type )   = split( /\|/, $localcrit );
279         my ( $table, $column ) = split( /\./, $value );
280         if ( $type eq 'date' ) {
281                         my %temp;
282             $temp{'name'}   = $value;
283             $temp{'date'}   = 1;
284                         $temp{'description'} = $columns{$value};
285             push @criteria_array, \%temp;
286         }
287         else {
288
289             my $query =
290               "SELECT distinct($column) as availablevalues FROM $table";
291             my $sth = $dbh->prepare($query);
292             $sth->execute();
293             my @values;
294             while ( my $row = $sth->fetchrow_hashref() ) {
295                 push @values, $row;
296                 ### $row;
297             }
298             $sth->finish();
299             my %temp;
300             $temp{'name'}   = $value;
301                         $temp{'description'} = $columns{$value};
302             $temp{'values'} = \@values;
303             push @criteria_array, \%temp;
304         }
305     }
306     return ( \@criteria_array );
307 }
308
309 sub execute_query {
310     my ( $sql, $type, $format ) = @_;
311     my $dbh = C4::Context->dbh();
312
313     # take this line out when in production
314     $sql .= " LIMIT 10";
315     my $sth = $dbh->prepare($sql);
316     $sth->execute();
317         my $colnames=$sth->{'NAME'};
318         my @results;
319         my $row = join ('</th><th>',@$colnames);
320         $row = "<tr><th>$row</th></tr>";
321         my %temphash;
322         $temphash{'row'} = $row;
323         push @results, \%temphash;
324     
325     my $string;
326     while ( my @data = $sth->fetchrow_array() ) {
327
328             # tabular
329             my %temphash;
330             my $row = join( '</td><td>', @data );
331             $row = "<tr><td>$row</td></tr>";
332             $temphash{'row'} = $row;
333             if ( $format eq 'text' ) {
334                 $string .= "\n" . $row;
335             }
336                         if ($format eq 'tab' ){
337                                 $row = join("\t",@data);
338                                 $string .="\n" . $row;
339                         }
340                         if ($format eq 'csv' ){
341                                 $row = join(",",@data);
342                                 $string .="\n" . $row;
343                         }
344
345             push @results, \%temphash;
346 #        }
347     }
348     $sth->finish();
349     if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv') {
350         return $string;
351     }
352     else {
353         return ( \@results );
354     }
355 }
356
357 =item save_report($sql,$name,$type,$notes)
358
359 Given some sql and a name this will saved it so that it can resued
360
361 =cut
362
363 sub save_report {
364     my ( $sql, $name, $type, $notes ) = @_;
365     my $dbh = C4::Context->dbh();
366     my $query =
367 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
368     my $sth = $dbh->prepare($query);
369     $sth->execute( 0, $sql, $name, $type, $notes );
370     $sth->finish();
371
372 }
373
374 sub get_saved_reports {
375     my $dbh   = C4::Context->dbh();
376     my $query = "SELECT * FROM saved_sql ORDER by date_created";
377     my $sth   = $dbh->prepare($query);
378     $sth->execute();
379     my @reports;
380     while ( my $data = $sth->fetchrow_hashref() ) {
381         push @reports, $data;
382     }
383     $sth->finish();
384     return ( \@reports );
385 }
386
387 sub get_saved_report {
388     my ($id)  = @_;
389     my $dbh   = C4::Context->dbh();
390     my $query = " SELECT * FROM saved_sql WHERE id = ?";
391     my $sth   = $dbh->prepare($query);
392     $sth->execute($id);
393     my $data = $sth->fetchrow_hashref();
394     $sth->finish();
395     return ( $data->{'savedsql'}, $data->{'type'} );
396 }
397
398 =item create_compound($masterID,$subreportID)
399
400 This will take 2 reports and create a compound report using both of them
401
402 =cut
403
404 sub create_compound {
405         my ($masterID,$subreportID) = @_;
406         my $dbh = C4::Context->dbh();
407         # get the reports
408         my ($mastersql,$mastertype) = get_saved_report($masterID);
409         my ($subsql,$subtype) = get_saved_report($subreportID);
410         
411         # now we have to do some checking to see how these two will fit together
412         # or if they will
413         my ($mastertables,$subtables);
414         if ($mastersql =~ / from (.*) where /i){ 
415                 $mastertables = $1;
416         }
417         if ($subsql =~ / from (.*) where /i){
418                 $subtables = $1;
419         }
420         return ($mastertables,$subtables);
421 }
422
423 =head1 AUTHOR
424
425 Chris Cormack <crc@liblime.com>
426
427 =cut
428
429 1;