3 # Copyright 2007 Liblime Ltd
5 # This file is part of Koha.
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
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.
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
23 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
29 # use Smart::Comments;
33 # set the version for version checking
38 get_report_types get_report_areas get_columns build_query get_criteria
39 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
40 get_column_type get_distinct_values save_dictionary get_from_dictionary
41 delete_definition delete_report format_results get_sql
47 [ 'borrowers', 'statistics','items', 'biblioitems' ]; # circulation
48 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ]; # catalogue
49 $table_areas{'3'} = [ 'borrowers' ]; # patrons
50 $table_areas{'4'} = ['aqorders', 'biblio', 'items']; # acquisitions
51 $table_areas{'5'} = [ 'borrowers', 'accountlines' ]; # accounts
54 'statistics.borrowernumber=borrowers.borrowernumber',
55 'items.itemnumber = statistics.itemnumber',
56 'biblioitems.biblioitemnumber = items.biblioitemnumber'
59 'items.biblioitemnumber=biblioitems.biblioitemnumber',
60 'biblioitems.biblionumber=biblio.biblionumber'
64 'aqorders.biblionumber=biblio.biblionumber',
65 'biblio.biblionumber=items.biblionumber'
67 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
69 # have to do someting here to know if its dropdown, free text, date etc
73 'statistics.type', 'borrowers.categorycode',
75 'biblioitems.publicationyear|date',
76 'items.dateaccessioned|date'
79 [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
80 $criteria{'3'} = ['borrowers.branchcode'];
81 $criteria{'4'} = ['aqorders.datereceived|date'];
82 $criteria{'5'} = ['borrowers.branchcode'];
84 if (C4::Context->preference('item-level_itypes')) {
85 unshift @{ $criteria{'1'} }, 'items.itype';
86 unshift @{ $criteria{'2'} }, 'items.itype';
88 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
89 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
94 C4::Reports - Module for generating reports
109 =item get_report_types()
111 This will return a list of all the available report types
115 sub get_report_types {
116 my $dbh = C4::Context->dbh();
118 # FIXME these should be in the database perhaps
119 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
121 for ( my $i = 0 ; $i < 3 ; $i++ ) {
123 $hashrep{id} = $i + 1;
124 $hashrep{name} = $reports[$i];
125 push @reports2, \%hashrep;
127 return ( \@reports2 );
131 =item get_report_areas()
133 This will return a list of all the available report areas
137 sub get_report_areas {
138 my $dbh = C4::Context->dbh();
140 # FIXME these should be in the database
141 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
143 for ( my $i = 0 ; $i < 5 ; $i++ ) {
145 $hashrep{id} = $i + 1;
146 $hashrep{name} = $reports[$i];
147 push @reports2, \%hashrep;
149 return ( \@reports2 );
153 =item get_all_tables()
155 This will return a list of all tables in the database
160 my $dbh = C4::Context->dbh();
161 my $query = "SHOW TABLES";
162 my $sth = $dbh->prepare($query);
165 while ( my $data = $sth->fetchrow_arrayref() ) {
166 push @tables, $data->[0];
173 =item get_columns($area)
175 This will return a list of all columns for a report area
181 # this calls the internal fucntion _get_columns
182 my ($area,$cgi) = @_;
183 my $tables = $table_areas{$area};
186 foreach my $table (@$tables) {
187 my @columns = _get_columns($table,$cgi, $first);
189 push @allcolumns, @columns;
191 return ( \@allcolumns );
195 my ($tablename,$cgi, $first) = @_;
196 my $dbh = C4::Context->dbh();
197 my $sth = $dbh->prepare("show columns from $tablename");
200 my $column_defs = _get_column_defs($cgi);
202 $tablehash{'table'}=$tablename;
203 $tablehash{'__first__'} = $first;
204 push @columns, \%tablehash;
205 while ( my $data = $sth->fetchrow_arrayref() ) {
207 $temphash{'name'} = "$tablename.$data->[0]";
208 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
209 push @columns, \%temphash;
215 =item build_query($columns,$criteria,$orderby,$area)
217 This will build the sql needed to return the results asked for,
218 $columns is expected to be of the format tablename.columnname.
219 This is what get_columns returns.
224 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
226 my $keys = $keys{$area};
227 my $tables = $table_areas{$area};
230 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
235 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
237 # $keys is an array of joining constraints
238 my $dbh = C4::Context->dbh();
239 my $joinedtables = join( ',', @$tables );
240 my $joinedcolumns = join( ',', @$columns );
241 my $joinedkeys = join( ' AND ', @$keys );
243 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
244 for (my $i=1;$i<@$tables;$i++){
245 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
249 $criteria =~ s/AND/WHERE/;
250 $query .= " $criteria";
253 my @definitions = split(',',$definition);
255 foreach my $def (@definitions){
256 my $defin=get_from_dictionary('',$def);
257 $deftext .=" ".$defin->[0]->{'saved_sql'};
259 if ($query =~ /WHERE/i){
263 $deftext =~ s/AND/WHERE/;
269 my @totcolumns = split( ',', $totals );
270 foreach my $total (@totcolumns) {
271 if ( $total =~ /\((.*)\)/ ) {
272 if ( $groupby eq '' ) {
273 $groupby = " GROUP BY $1";
288 =item get_criteria($area,$cgi);
290 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
295 my ($area,$cgi) = @_;
296 my $dbh = C4::Context->dbh();
297 my $crit = $criteria{$area};
298 my $column_defs = _get_column_defs($cgi);
300 foreach my $localcrit (@$crit) {
301 my ( $value, $type ) = split( /\|/, $localcrit );
302 my ( $table, $column ) = split( /\./, $value );
303 if ( $type eq 'date' ) {
305 $temp{'name'} = $value;
307 $temp{'description'} = $column_defs->{$value};
308 push @criteria_array, \%temp;
313 "SELECT distinct($column) as availablevalues FROM $table";
314 my $sth = $dbh->prepare($query);
317 while ( my $row = $sth->fetchrow_hashref() ) {
323 $temp{'name'} = $value;
324 $temp{'description'} = $column_defs->{$value};
325 $temp{'values'} = \@values;
326 push @criteria_array, \%temp;
329 return ( \@criteria_array );
334 =head2 ($results, $total) = execute_query($sql, $type, $offset, $limit, $format, $id)
336 When passed C<$sql>, this function returns an array ref containing a result set
337 suitably formatted for display in html or for output as a flat file when passed in
338 C<$format> and C<$id>. Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url.
339 C<$sql>, C<$type>, C<$offset>, and C<$limit> are required parameters. If a valid
340 C<$format> is passed in, C<$offset> and C<$limit> are ignored for obvious reasons.
341 A LIMIT specified by the user in a user-supplied SQL query WILL apply in any case.
345 sub execute_query ($$$$;$$) {
346 my ( $sql, $type, $offset, $limit, $format, $id ) = @_;
349 my ($useroffset, $userlimit);
350 my $dbh = C4::Context->dbh();
351 unless ($format eq 'text' || $format eq 'tab' || $format eq 'csv' || $format eq 'url'){
352 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
353 if ($sql =~ /LIMIT/i) {
354 $sql =~ s/LIMIT\W?(\d+)?\,?\W+?(\d+)//ig;
355 $debug and warn "User has supplied LIMIT\n";
358 $debug and warn "User supplied offset = $useroffset, limit = $userlimit\n";
359 $offset += $useroffset if $useroffset;
360 # keep track of where we are if there is a user supplied LIMIT
361 if ( $offset + $limit > $userlimit ) {
362 $limit = $userlimit - $offset;
366 $sql .= " LIMIT ?, ?";
367 $debug and warn "Passing query with params offset = $offset, limit = $limit\n";
368 @params = ($offset, $limit);
369 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
370 $countsql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
371 $debug and warn "original query: $sql\n";
372 $debug and warn "count query: $countsql\n";
373 my $sth1 = $dbh->prepare($countsql);
375 $total = $sth1->fetchrow();
376 $debug and warn "total records for this query: $total\n";
377 $total = $userlimit if defined($userlimit) and $userlimit < $total; # we will never exceed a user defined LIMIT and...
378 $userlimit = $total if defined($userlimit) and $userlimit > $total; # we will never exceed the total number of records available to satisfy the query
380 my $sth = $dbh->prepare($sql);
381 $sth->execute(@params);
382 my $colnames=$sth->{'NAME'};
386 $row = join ('</th><th>',@$colnames);
387 $row = "<tr><th>$row</th></tr>";
388 $temphash{'row'} = $row;
389 push @results, \%temphash;
391 if ($format eq 'tab') {
392 $string = join("\t",@$colnames);
394 if ($format eq 'csv') {
395 $string = join(",",@$colnames);
398 while ( my @data = $sth->fetchrow_array() ) {
399 # if the field is a date field, it needs formatting
400 foreach my $data (@data) {
401 next unless $data =~ C4::Dates->regexp("iso");
402 my $date = C4::Dates->new($data, "iso");
403 $data = $date->output();
407 my $row = join( '</td><td>', @data );
408 $row = "<tr><td>$row</td></tr>";
409 $temphash{'row'} = $row;
410 if ( $format eq 'text' ) {
411 $string .= "\n" . $row;
413 if ($format eq 'tab' ){
414 $row = join("\t",@data);
415 $string .="\n" . $row;
417 if ($format eq 'csv' ){
418 $row = join(",",@data);
419 $string .="\n" . $row;
421 if ($format eq 'url'){
423 @$temphash{@$colnames}=@data;
424 push @xmlarray,$temphash;
426 push @results, \%temphash;
428 if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
431 elsif ($format eq 'url') {
432 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
433 my $dump = new XML::Dumper;
434 my $xml = $dump->pl2xml( \@xmlarray );
435 store_results($id,$xml);
439 return ( \@results, $total );
443 =item save_report($sql,$name,$type,$notes)
445 Given some sql and a name this will saved it so that it can resued
450 my ( $sql, $name, $type, $notes ) = @_;
451 my $dbh = C4::Context->dbh();
453 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
454 my $sth = $dbh->prepare($query);
455 $sth->execute( 0, $sql, $name, $type, $notes );
462 my $dbh = C4::Context->dbh();
463 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
464 my $sth = $dbh->prepare($query);
466 if (my $data=$sth->fetchrow_hashref()){
467 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
468 my $sth2 = $dbh->prepare($query2);
469 $sth2->execute($xml,$id);
473 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
474 my $sth2 = $dbh->prepare($query2);
475 $sth2->execute($id,$xml);
483 my $dbh = C4::Context->dbh();
484 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
485 my $sth = $dbh->prepare($query);
487 my $data = $sth->fetchrow_hashref();
488 my $dump = new XML::Dumper;
489 my $perl = $dump->xml2pl( $data->{'report'} );
490 foreach my $row (@$perl) {
492 foreach my $key (keys %$row){
493 $htmlrow .= "<td>$row->{$key}</td>";
496 $row->{'row'} = $htmlrow;
499 $query = "SELECT * FROM saved_sql WHERE id = ?";
500 $sth = $dbh->prepare($query);
502 $data = $sth->fetchrow_hashref();
504 return ($perl,$data->{'report_name'},$data->{'notes'});
509 my $dbh = C4::Context->dbh();
510 my $query = "DELETE FROM saved_sql WHERE id = ?";
511 my $sth = $dbh->prepare($query);
516 sub get_saved_reports {
517 my $dbh = C4::Context->dbh();
518 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
519 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
520 ORDER by date_created";
521 my $sth = $dbh->prepare($query);
524 while ( my $data = $sth->fetchrow_hashref() ) {
525 push @reports, $data;
528 return ( \@reports );
531 sub get_saved_report {
533 my $dbh = C4::Context->dbh();
534 my $query = " SELECT * FROM saved_sql WHERE id = ?";
535 my $sth = $dbh->prepare($query);
537 my $data = $sth->fetchrow_hashref();
539 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
542 =item create_compound($masterID,$subreportID)
544 This will take 2 reports and create a compound report using both of them
548 sub create_compound {
549 my ($masterID,$subreportID) = @_;
550 my $dbh = C4::Context->dbh();
552 my ($mastersql,$mastertype) = get_saved_report($masterID);
553 my ($subsql,$subtype) = get_saved_report($subreportID);
555 # now we have to do some checking to see how these two will fit together
557 my ($mastertables,$subtables);
558 if ($mastersql =~ / from (.*) where /i){
561 if ($subsql =~ / from (.*) where /i){
564 return ($mastertables,$subtables);
567 =item get_column_type($column)
569 This takes a column name of the format table.column and will return what type it is
570 (free text, set values, date)
574 sub get_column_type {
575 my ($tablecolumn) = @_;
576 my ($table,$column) = split(/\./,$tablecolumn);
577 my $dbh = C4::Context->dbh();
581 # mysql doesnt support a column selection, set column to %
583 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
584 while (my $info = $sth->fetchrow_hashref()){
585 if ($info->{'COLUMN_NAME'} eq $column){
587 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
588 $info->{'TYPE_NAME'} = 'distinct';
590 return $info->{'TYPE_NAME'};
596 =item get_distinct_values($column)
598 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
599 with the distinct values of the column
603 sub get_distinct_values {
604 my ($tablecolumn) = @_;
605 my ($table,$column) = split(/\./,$tablecolumn);
606 my $dbh = C4::Context->dbh();
608 "SELECT distinct($column) as availablevalues FROM $table";
609 my $sth = $dbh->prepare($query);
612 while ( my $row = $sth->fetchrow_hashref() ) {
619 sub save_dictionary {
620 my ($name,$description,$sql,$area) = @_;
621 my $dbh = C4::Context->dbh();
622 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
623 VALUES (?,?,?,?,now(),now())";
624 my $sth = $dbh->prepare($query);
625 $sth->execute($name,$description,$sql,$area) || return 0;
630 sub get_from_dictionary {
632 my $dbh = C4::Context->dbh();
633 my $query = "SELECT * FROM reports_dictionary";
635 $query.= " WHERE area = ?";
638 $query.= " WHERE id = ?"
640 my $sth = $dbh->prepare($query);
645 $sth->execute($area);
651 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
652 while (my $data = $sth->fetchrow_hashref()){
653 $data->{'areaname'}=$reports[$data->{'area'}-1];
661 sub delete_definition {
663 my $dbh = C4::Context->dbh();
664 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
665 my $sth = $dbh->prepare($query);
672 my $dbh = C4::Context->dbh();
673 my $query = "SELECT * FROM saved_sql WHERE id = ?";
674 my $sth = $dbh->prepare($query);
676 my $data=$sth->fetchrow_hashref();
678 return $data->{'savedsql'};
681 sub _get_column_defs {
684 my $columns_def_file = "columns.def";
685 my $htdocs = C4::Context->config('intrahtdocs');
686 my $section='intranet';
687 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
689 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
690 open (COLUMNS,$full_path_to_columns_def_file);
691 while (my $input = <COLUMNS>){
692 my @row =split(/\t/,$input);
693 $columns{$row[0]}=$row[1];
704 Chris Cormack <crc@liblime.com>