kohabug 1679 & 1680 Fixes date formatting in guided reports wizard
[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         # if the field is a date field, it needs formatting
355         foreach my $data (@data) {
356             next unless $data =~ C4::Dates->regexp("iso");
357             my $date = C4::Dates->new($data, "iso");
358             $data = $date->output();
359         }
360             # tabular
361             my %temphash;
362             my $row = join( '</td><td>', @data );
363             $row = "<tr><td>$row</td></tr>";
364             $temphash{'row'} = $row;
365             if ( $format eq 'text' ) {
366                 $string .= "\n" . $row;
367             }
368                         if ($format eq 'tab' ){
369                                 $row = join("\t",@data);
370                                 $string .="\n" . $row;
371                         }
372                         if ($format eq 'csv' ){
373                                 $row = join(",",@data);
374                                 $string .="\n" . $row;
375                         }
376                 if ($format eq 'url'){
377                         my $temphash;
378                         @$temphash{@$colnames}=@data;
379                         push @xmlarray,$temphash;
380                 }
381             push @results, \%temphash;
382 #        }
383     }
384     $sth->finish();
385     if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
386         return $string;
387     }
388         elsif ($format eq 'url') {
389                 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
390                 my $dump = new XML::Dumper;
391                 my $xml = $dump->pl2xml( \@xmlarray );
392                 store_results($id,$xml);
393                 return $url;
394         }
395     else {
396         return ( \@results );
397     }
398 }
399
400 =item save_report($sql,$name,$type,$notes)
401
402 Given some sql and a name this will saved it so that it can resued
403
404 =cut
405
406 sub save_report {
407     my ( $sql, $name, $type, $notes ) = @_;
408     my $dbh = C4::Context->dbh();
409     my $query =
410 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes)  VALUES (?,now(),now(),?,?,?,?)";
411     my $sth = $dbh->prepare($query);
412     $sth->execute( 0, $sql, $name, $type, $notes );
413     $sth->finish();
414
415 }
416
417 sub store_results {
418         my ($id,$xml)=@_;
419         my $dbh = C4::Context->dbh();
420         my $query = "SELECT * FROM saved_reports WHERE report_id=?";
421         my $sth = $dbh->prepare($query);
422         $sth->execute($id);
423         if (my $data=$sth->fetchrow_hashref()){
424                 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
425                 my $sth2 = $dbh->prepare($query2);
426             $sth2->execute($xml,$id);
427                 $sth2->finish();
428         }
429         else {
430                 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
431                 my $sth2 = $dbh->prepare($query2);
432                 $sth2->execute($id,$xml);
433                 $sth2->finish();
434         }
435         $sth->finish();
436 }
437
438 sub format_results {
439         my ($id) = @_;
440         my $dbh = C4::Context->dbh();
441         my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
442         my $sth = $dbh->prepare($query);
443         $sth->execute($id);
444         my $data = $sth->fetchrow_hashref();
445         my $dump = new XML::Dumper;
446         my $perl = $dump->xml2pl( $data->{'report'} );
447         foreach my $row (@$perl) {
448                 my $htmlrow="<tr>";
449                 foreach my $key (keys %$row){
450                         $htmlrow .= "<td>$row->{$key}</td>";
451                 }
452                 $htmlrow .= "</tr>";
453                 $row->{'row'} = $htmlrow;
454         }
455         $sth->finish;
456         $query = "SELECT * FROM saved_sql WHERE id = ?";
457         $sth = $dbh->prepare($query);
458         $sth->execute($id);
459         $data = $sth->fetchrow_hashref();
460     $sth->finish();
461         return ($perl,$data->{'report_name'},$data->{'notes'}); 
462 }       
463
464 sub delete_report {
465         my ( $id ) = @_;
466         my $dbh = C4::Context->dbh();
467         my $query = "DELETE FROM saved_sql WHERE id = ?";
468         my $sth = $dbh->prepare($query);
469         $sth->execute($id);
470         $sth->finish();
471 }       
472
473 sub get_saved_reports {
474     my $dbh   = C4::Context->dbh();
475     my $query = "SELECT *,saved_sql.id AS id FROM saved_sql 
476     LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
477     ORDER by date_created";
478     my $sth   = $dbh->prepare($query);
479     $sth->execute();
480     my @reports;
481     while ( my $data = $sth->fetchrow_hashref() ) {
482         push @reports, $data;
483     }
484     $sth->finish();
485     return ( \@reports );
486 }
487
488 sub get_saved_report {
489     my ($id)  = @_;
490     my $dbh   = C4::Context->dbh();
491     my $query = " SELECT * FROM saved_sql WHERE id = ?";
492     my $sth   = $dbh->prepare($query);
493     $sth->execute($id);
494     my $data = $sth->fetchrow_hashref();
495     $sth->finish();
496     return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
497 }
498
499 =item create_compound($masterID,$subreportID)
500
501 This will take 2 reports and create a compound report using both of them
502
503 =cut
504
505 sub create_compound {
506         my ($masterID,$subreportID) = @_;
507         my $dbh = C4::Context->dbh();
508         # get the reports
509         my ($mastersql,$mastertype) = get_saved_report($masterID);
510         my ($subsql,$subtype) = get_saved_report($subreportID);
511         
512         # now we have to do some checking to see how these two will fit together
513         # or if they will
514         my ($mastertables,$subtables);
515         if ($mastersql =~ / from (.*) where /i){ 
516                 $mastertables = $1;
517         }
518         if ($subsql =~ / from (.*) where /i){
519                 $subtables = $1;
520         }
521         return ($mastertables,$subtables);
522 }
523
524 =item get_column_type($column)
525
526 This takes a column name of the format table.column and will return what type it is
527 (free text, set values, date)
528
529 =cut
530
531 sub get_column_type {
532         my ($tablecolumn) = @_;
533         my ($table,$column) = split(/\./,$tablecolumn);
534         my $dbh = C4::Context->dbh();
535         my $catalog;
536         my $schema;
537
538         # mysql doesnt support a column selection, set column to %
539         my $tempcolumn='%';
540         my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
541         while (my $info = $sth->fetchrow_hashref()){
542                 if ($info->{'COLUMN_NAME'} eq $column){
543                         #column we want
544                         if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
545                                 $info->{'TYPE_NAME'} = 'distinct';
546                         }
547                         return $info->{'TYPE_NAME'};            
548                 }
549         }
550         $sth->finish();
551 }
552
553 =item get_distinct_values($column)
554
555 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop 
556 with the distinct values of the column
557
558 =cut
559
560 sub get_distinct_values {
561         my ($tablecolumn) = @_;
562         my ($table,$column) = split(/\./,$tablecolumn);
563         my $dbh = C4::Context->dbh();
564         my $query =
565           "SELECT distinct($column) as availablevalues FROM $table";
566         my $sth = $dbh->prepare($query);
567         $sth->execute();
568         my @values;
569         while ( my $row = $sth->fetchrow_hashref() ) {
570                 push @values, $row;
571         }
572         $sth->finish();
573         return \@values;
574 }       
575
576 sub save_dictionary {
577         my ($name,$description,$sql,$area) = @_;
578         my $dbh = C4::Context->dbh();
579         my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
580   VALUES (?,?,?,?,now(),now())";
581     my $sth = $dbh->prepare($query);
582     $sth->execute($name,$description,$sql,$area) || return 0;
583     $sth->finish();
584     return 1;
585 }
586
587 sub get_from_dictionary {
588         my ($area,$id) = @_;
589         my $dbh = C4::Context->dbh();
590         my $query = "SELECT * FROM reports_dictionary";
591         if ($area){
592                 $query.= " WHERE area = ?";
593         }
594         elsif ($id){
595                 $query.= " WHERE id = ?"
596         }
597         my $sth = $dbh->prepare($query);
598         if ($id){
599                 $sth->execute($id);
600         }
601         elsif ($area) {
602                 $sth->execute($area);
603         }
604         else {
605                 $sth->execute();
606         }
607         my @loop;
608         my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
609         while (my $data = $sth->fetchrow_hashref()){
610                 $data->{'areaname'}=$reports[$data->{'area'}-1];
611                 push @loop,$data;
612                 
613         }
614         $sth->finish();
615         return (\@loop);
616 }
617
618 sub delete_definition {
619         my ($id) = @_;
620         my $dbh = C4::Context->dbh();
621         my $query = "DELETE FROM reports_dictionary WHERE id = ?";
622         my $sth = $dbh->prepare($query);
623         $sth->execute($id);
624         $sth->finish();
625 }
626
627 sub get_sql {
628         my ($id) = @_;
629         my $dbh = C4::Context->dbh();
630         my $query = "SELECT * FROM saved_sql WHERE id = ?";
631         my $sth = $dbh->prepare($query);
632         $sth->execute($id);
633         my $data=$sth->fetchrow_hashref();
634         $sth->finish(); 
635         return $data->{'savedsql'};
636 }
637
638 sub _get_column_defs {
639         my ($cgi) = @_;
640         my %columns;
641         my $columns_def_file = "columns.def";
642         my $htdocs = C4::Context->config('intrahtdocs');                       
643         my $section='intranet';
644         my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
645
646         my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";    
647         open (COLUMNS,$full_path_to_columns_def_file);
648         while (my $input = <COLUMNS>){
649                 my @row =split(/\t/,$input);
650                 $columns{$row[0]}=$row[1];
651         }
652
653         close COLUMNS;
654         return \%columns;
655 }
656 1;
657 __END__
658
659 =head1 AUTHOR
660
661 Chris Cormack <crc@liblime.com>
662
663 =cut