bug 2004: changes to guided reports on items
[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',
74     'biblioitems.publicationyear|date',
75     'items.dateaccessioned|date'
76 ];
77 $criteria{'2'} =
78   [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
79 $criteria{'3'} = ['borrowers.branchcode'];
80 $criteria{'4'} = ['aqorders.datereceived|date'];
81 $criteria{'5'} = ['borrowers.branchcode'];
82
83 if (C4::Context->preference('item-level_itypes')) {
84     unshift @{ $criteria{'1'} }, 'items.itype';
85     unshift @{ $criteria{'2'} }, 'items.itype';
86 } else {
87     unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
88     unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
89 }
90
91 =head1 NAME
92    
93 C4::Reports - Module for generating reports 
94
95 =head1 SYNOPSIS
96
97   use C4::Reports;
98
99 =head1 DESCRIPTION
100
101
102 =head1 METHODS
103
104 =over 2
105
106 =cut
107
108 =item get_report_types()
109
110 This will return a list of all the available report types
111
112 =cut
113
114 sub get_report_types {
115     my $dbh = C4::Context->dbh();
116
117     # FIXME these should be in the database perhaps
118     my @reports = ( 'Tabular', 'Summary', 'Matrix' );
119     my @reports2;
120     for ( my $i = 0 ; $i < 3 ; $i++ ) {
121         my %hashrep;
122         $hashrep{id}   = $i + 1;
123         $hashrep{name} = $reports[$i];
124         push @reports2, \%hashrep;
125     }
126     return ( \@reports2 );
127
128 }
129
130 =item get_report_areas()
131
132 This will return a list of all the available report areas
133
134 =cut
135
136 sub get_report_areas {
137     my $dbh = C4::Context->dbh();
138
139     # FIXME these should be in the database
140     my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
141     my @reports2;
142     for ( my $i = 0 ; $i < 5 ; $i++ ) {
143         my %hashrep;
144         $hashrep{id}   = $i + 1;
145         $hashrep{name} = $reports[$i];
146         push @reports2, \%hashrep;
147     }
148     return ( \@reports2 );
149
150 }
151
152 =item get_all_tables()
153
154 This will return a list of all tables in the database 
155
156 =cut
157
158 sub get_all_tables {
159     my $dbh   = C4::Context->dbh();
160     my $query = "SHOW TABLES";
161     my $sth   = $dbh->prepare($query);
162     $sth->execute();
163     my @tables;
164     while ( my $data = $sth->fetchrow_arrayref() ) {
165         push @tables, $data->[0];
166     }
167     $sth->finish();
168     return ( \@tables );
169
170 }
171
172 =item get_columns($area)
173
174 This will return a list of all columns for a report area
175
176 =cut
177
178 sub get_columns {
179
180     # this calls the internal fucntion _get_columns
181     my ($area,$cgi) = @_;
182     my $tables = $table_areas{$area};
183     my @allcolumns;
184     my $first = 1;
185     foreach my $table (@$tables) {
186         my @columns = _get_columns($table,$cgi, $first);
187         $first = 0;
188         push @allcolumns, @columns;
189     }
190     return ( \@allcolumns );
191 }
192
193 sub _get_columns {
194     my ($tablename,$cgi, $first) = @_;
195     my $dbh         = C4::Context->dbh();
196     my $sth         = $dbh->prepare("show columns from $tablename");
197     $sth->execute();
198     my @columns;
199         my $column_defs = _get_column_defs($cgi);
200         my %tablehash;
201         $tablehash{'table'}=$tablename;
202     $tablehash{'__first__'} = $first;
203         push @columns, \%tablehash;
204     while ( my $data = $sth->fetchrow_arrayref() ) {
205         my %temphash;
206         $temphash{'name'}        = "$tablename.$data->[0]";
207         $temphash{'description'} = $column_defs->{"$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,$cgi);
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,$cgi) = @_;
295     my $dbh    = C4::Context->dbh();
296     my $crit   = $criteria{$area};
297         my $column_defs = _get_column_defs($cgi);
298     my @criteria_array;
299     foreach my $localcrit (@$crit) {
300         my ( $value, $type )   = split( /\|/, $localcrit );
301         my ( $table, $column ) = split( /\./, $value );
302         if ( $type eq 'date' ) {
303                         my %temp;
304             $temp{'name'}   = $value;
305             $temp{'date'}   = 1;
306                         $temp{'description'} = $column_defs->{$value};
307             push @criteria_array, \%temp;
308         }
309         else {
310
311             my $query =
312               "SELECT distinct($column) as availablevalues FROM $table";
313             my $sth = $dbh->prepare($query);
314             $sth->execute();
315             my @values;
316             while ( my $row = $sth->fetchrow_hashref() ) {
317                 push @values, $row;
318                 ### $row;
319             }
320             $sth->finish();
321             my %temp;
322             $temp{'name'}   = $value;
323                         $temp{'description'} = $column_defs->{$value};
324             $temp{'values'} = \@values;
325             push @criteria_array, \%temp;
326         }
327     }
328     return ( \@criteria_array );
329 }
330
331 sub execute_query {
332     my ( $sql, $type, $format, $id ) = @_;
333     my $dbh = C4::Context->dbh();
334
335     # take this line out when in production
336         if ($format eq 'csv' or $format eq 'tab'){
337                 }
338         else {
339                 $sql .= " LIMIT 20";
340         }
341     my $sth = $dbh->prepare($sql);
342     $sth->execute();
343         my $colnames=$sth->{'NAME'};
344         my @results;
345         my $row;
346         my %temphash;
347         $row = join ('</th><th>',@$colnames);
348         $row = "<tr><th>$row</th></tr>";
349         $temphash{'row'} = $row;
350         push @results, \%temphash;
351     my $string;
352         my @xmlarray;
353     while ( my @data = $sth->fetchrow_array() ) {
354
355             # tabular
356             my %temphash;
357             my $row = join( '</td><td>', @data );
358             $row = "<tr><td>$row</td></tr>";
359             $temphash{'row'} = $row;
360             if ( $format eq 'text' ) {
361                 $string .= "\n" . $row;
362             }
363                         if ($format eq 'tab' ){
364                                 $row = join("\t",@data);
365                                 $string .="\n" . $row;
366                         }
367                         if ($format eq 'csv' ){
368                                 $row = join(",",@data);
369                                 $string .="\n" . $row;
370                         }
371                 if ($format eq 'url'){
372                         my $temphash;
373                         @$temphash{@$colnames}=@data;
374                         push @xmlarray,$temphash;
375                 }
376             push @results, \%temphash;
377 #        }
378     }
379     $sth->finish();
380     if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
381         return $string;
382     }
383         elsif ($format eq 'url') {
384                 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
385                 my $dump = new XML::Dumper;
386                 my $xml = $dump->pl2xml( \@xmlarray );
387                 store_results($id,$xml);
388                 return $url;
389         }
390     else {
391         return ( \@results );
392     }
393 }
394
395 =item save_report($sql,$name,$type,$notes)
396
397 Given some sql and a name this will saved it so that it can resued
398
399 =cut
400
401 sub save_report {
402     my ( $sql, $name, $type, $notes ) = @_;
403     my $dbh = C4::Context->dbh();
404     my $query =
405 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
406     my $sth = $dbh->prepare($query);
407     $sth->execute( 0, $sql, $name, $type, $notes );
408     $sth->finish();
409
410 }
411
412 sub store_results {
413         my ($id,$xml)=@_;
414         my $dbh = C4::Context->dbh();
415         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
416         my $sth = $dbh->prepare($query);
417         $sth->execute($id);
418         if (my $data=$sth->fetchrow_hashref()){
419                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
420                 my $sth2 = $dbh->prepare($query2);
421             $sth2->execute($xml,$id);
422                 $sth2->finish();
423         }
424         else {
425                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
426                 my $sth2 = $dbh->prepare($query2);
427                 $sth2->execute($id,$xml);
428                 $sth2->finish();
429         }
430         $sth->finish();
431 }
432
433 sub format_results {
434         my ($id) = @_;
435         my $dbh = C4::Context->dbh();
436         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
437         my $sth = $dbh->prepare($query);
438         $sth->execute($id);
439         my $data = $sth->fetchrow_hashref();
440         my $dump = new XML::Dumper;
441         my $perl = $dump->xml2pl( $data->{'report'} );
442         foreach my $row (@$perl) {
443                 my $htmlrow="<tr>";
444                 foreach my $key (keys %$row){
445                         $htmlrow .= "<td>$row->{$key}</td>";
446                 }
447                 $htmlrow .= "</tr>";
448                 $row->{'row'} = $htmlrow;
449         }
450         $sth->finish;
451         $query = "SELECT * FROM saved_sql WHERE id = ?";
452         $sth = $dbh->prepare($query);
453         $sth->execute($id);
454         $data = $sth->fetchrow_hashref();
455     $sth->finish();
456         return ($perl,$data->{'report_name'},$data->{'notes'}); 
457 }       
458
459 sub delete_report {
460         my ( $id ) = @_;
461         my $dbh = C4::Context->dbh();
462         my $query = "DELETE FROM saved_sql WHERE id = ?";
463         my $sth = $dbh->prepare($query);
464         $sth->execute($id);
465         $sth->finish();
466 }       
467
468 sub get_saved_reports {
469     my $dbh   = C4::Context->dbh();
470     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
471     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
472     ORDER by date_created";
473     my $sth   = $dbh->prepare($query);
474     $sth->execute();
475     my @reports;
476     while ( my $data = $sth->fetchrow_hashref() ) {
477         push @reports, $data;
478     }
479     $sth->finish();
480     return ( \@reports );
481 }
482
483 sub get_saved_report {
484     my ($id)  = @_;
485     my $dbh   = C4::Context->dbh();
486     my $query = " SELECT * FROM saved_sql WHERE id = ?";
487     my $sth   = $dbh->prepare($query);
488     $sth->execute($id);
489     my $data = $sth->fetchrow_hashref();
490     $sth->finish();
491     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
492 }
493
494 =item create_compound($masterID,$subreportID)
495
496 This will take 2 reports and create a compound report using both of them
497
498 =cut
499
500 sub create_compound {
501         my ($masterID,$subreportID) = @_;
502         my $dbh = C4::Context->dbh();
503         # get the reports
504         my ($mastersql,$mastertype) = get_saved_report($masterID);
505         my ($subsql,$subtype) = get_saved_report($subreportID);
506         
507         # now we have to do some checking to see how these two will fit together
508         # or if they will
509         my ($mastertables,$subtables);
510         if ($mastersql =~ / from (.*) where /i){ 
511                 $mastertables = $1;
512         }
513         if ($subsql =~ / from (.*) where /i){
514                 $subtables = $1;
515         }
516         return ($mastertables,$subtables);
517 }
518
519 =item get_column_type($column)
520
521 This takes a column name of the format table.column and will return what type it is
522 (free text, set values, date)
523
524 =cut
525
526 sub get_column_type {
527         my ($tablecolumn) = @_;
528         my ($table,$column) = split(/\./,$tablecolumn);
529         my $dbh = C4::Context->dbh();
530         my $catalog;
531         my $schema;
532
533         # mysql doesnt support a column selection, set column to %
534         my $tempcolumn='%';
535         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
536         while (my $info = $sth->fetchrow_hashref()){
537                 if ($info->{'COLUMN_NAME'} eq $column){
538                         #column we want
539                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
540                                 $info->{'TYPE_NAME'} = 'distinct';
541                         }
542                         return $info->{'TYPE_NAME'};            
543                 }
544         }
545         $sth->finish();
546 }
547
548 =item get_distinct_values($column)
549
550 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
551 with the distinct values of the column
552
553 =cut
554
555 sub get_distinct_values {
556         my ($tablecolumn) = @_;
557         my ($table,$column) = split(/\./,$tablecolumn);
558         my $dbh = C4::Context->dbh();
559         my $query =
560           "SELECT distinct($column) as availablevalues FROM $table";
561         my $sth = $dbh->prepare($query);
562         $sth->execute();
563         my @values;
564         while ( my $row = $sth->fetchrow_hashref() ) {
565                 push @values, $row;
566         }
567         $sth->finish();
568         return \@values;
569 }       
570
571 sub save_dictionary {
572         my ($name,$description,$sql,$area) = @_;
573         my $dbh = C4::Context->dbh();
574         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
575   VALUES (?,?,?,?,now(),now())";
576     my $sth = $dbh->prepare($query);
577     $sth->execute($name,$description,$sql,$area) || return 0;
578     $sth->finish();
579     return 1;
580 }
581
582 sub get_from_dictionary {
583         my ($area,$id) = @_;
584         my $dbh = C4::Context->dbh();
585         my $query = "SELECT * FROM reports_dictionary";
586         if ($area){
587                 $query.= " WHERE area = ?";
588         }
589         elsif ($id){
590                 $query.= " WHERE id = ?"
591         }
592         my $sth = $dbh->prepare($query);
593         if ($id){
594                 $sth->execute($id);
595         }
596         elsif ($area) {
597                 $sth->execute($area);
598         }
599         else {
600                 $sth->execute();
601         }
602         my @loop;
603         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
604         while (my $data = $sth->fetchrow_hashref()){
605                 $data->{'areaname'}=$reports[$data->{'area'}-1];
606                 push @loop,$data;
607                 
608         }
609         $sth->finish();
610         return (\@loop);
611 }
612
613 sub delete_definition {
614         my ($id) = @_;
615         my $dbh = C4::Context->dbh();
616         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
617         my $sth = $dbh->prepare($query);
618         $sth->execute($id);
619         $sth->finish();
620 }
621
622 sub get_sql {
623         my ($id) = @_;
624         my $dbh = C4::Context->dbh();
625         my $query = "SELECT * FROM saved_sql WHERE id = ?";
626         my $sth = $dbh->prepare($query);
627         $sth->execute($id);
628         my $data=$sth->fetchrow_hashref();
629         $sth->finish(); 
630         return $data->{'savedsql'};
631 }
632
633 sub _get_column_defs {
634         my ($cgi) = @_;
635         my %columns;
636         my $columns_def_file = "columns.def";
637         my $htdocs = C4::Context->config('intrahtdocs');                       
638         my $section='intranet';
639         my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
640
641         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
642         open (COLUMNS,$full_path_to_columns_def_file);
643         while (my $input = <COLUMNS>){
644                 my @row =split(/\t/,$input);
645                 $columns{$row[0]}=$row[1];
646         }
647
648         close COLUMNS;
649         return \%columns;
650 }
651 1;
652 __END__
653
654 =head1 AUTHOR
655
656 Chris Cormack <crc@liblime.com>
657
658 =cut