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