1 package C4::Reports::Guided;
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
21 # use warnings; # FIXME: this module needs a lot of repair to run clean under warnings
25 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27 use C4::Dates qw/format_date/;
34 # use Smart::Comments;
38 # set the version for version checking
43 get_report_types get_report_areas get_columns build_query get_criteria
44 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
45 get_column_type get_distinct_values save_dictionary get_from_dictionary
46 delete_definition delete_report format_results get_sql
47 select_2_select_count_value update_sql
53 [ 'borrowers', 'statistics','items', 'biblioitems' ]; # circulation
54 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ]; # catalogue
55 $table_areas{'3'} = [ 'borrowers' ]; # patrons
56 $table_areas{'4'} = ['aqorders', 'biblio', 'items']; # acquisitions
57 $table_areas{'5'} = [ 'borrowers', 'accountlines' ]; # accounts
60 'statistics.borrowernumber=borrowers.borrowernumber',
61 'items.itemnumber = statistics.itemnumber',
62 'biblioitems.biblioitemnumber = items.biblioitemnumber'
65 'items.biblioitemnumber=biblioitems.biblioitemnumber',
66 'biblioitems.biblionumber=biblio.biblionumber'
70 'aqorders.biblionumber=biblio.biblionumber',
71 'biblio.biblionumber=items.biblionumber'
73 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
75 # have to do someting here to know if its dropdown, free text, date etc
78 # reports on circulation
80 'statistics.type', 'borrowers.categorycode',
82 'biblioitems.publicationyear|date',
83 'items.dateaccessioned|date'
85 # reports on catalogue
87 [ 'items.itemnumber|textrange', 'items.biblionumber|textrange', 'items.barcode|textrange',
88 'biblio.frameworkcode', 'items.holdingbranch', 'items.homebranch',
89 'biblio.datecreated|daterange', 'biblio.timestamp|daterange', 'items.onloan|daterange',
90 'items.ccode', 'items.itemcallnumber|textrange', 'items.itype',
91 'items.itemlost', 'items.location' ];
92 # reports on borrowers
93 $criteria{'3'} = ['borrowers.branchcode', 'borrowers.categorycode'];
94 # reports on acquisition
95 $criteria{'4'} = ['aqorders.datereceived|date'];
97 # reports on accounting
98 $criteria{'5'} = ['borrowers.branchcode', 'borrowers.categorycode'];
100 # Adds itemtypes to criteria, according to the syspref
101 if (C4::Context->preference('item-level_itypes')) {
102 unshift @{ $criteria{'1'} }, 'items.itype';
103 unshift @{ $criteria{'2'} }, 'items.itype';
105 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
106 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
111 C4::Reports::Guided - Module for generating guided reports
115 use C4::Reports::Guided;
126 =item get_report_types()
128 This will return a list of all the available report types
132 sub get_report_types {
133 my $dbh = C4::Context->dbh();
135 # FIXME these should be in the database perhaps
136 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
138 for ( my $i = 0 ; $i < 3 ; $i++ ) {
140 $hashrep{id} = $i + 1;
141 $hashrep{name} = $reports[$i];
142 push @reports2, \%hashrep;
144 return ( \@reports2 );
148 =item get_report_areas()
150 This will return a list of all the available report areas
154 sub get_report_areas {
156 my $dbh = C4::Context->dbh();
158 # FIXME these should be in the database
159 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
161 for ( my $i = 0 ; $i < 5 ; $i++ ) {
163 $hashrep{id} = $i + 1;
164 $hashrep{name} = $reports[$i];
165 $hashrep{selected} = 1 if $hashrep{id} == $area;
166 push @reports2, \%hashrep;
168 return ( \@reports2 );
172 =item get_all_tables()
174 This will return a list of all tables in the database
179 my $dbh = C4::Context->dbh();
180 my $query = "SHOW TABLES";
181 my $sth = $dbh->prepare($query);
184 while ( my $data = $sth->fetchrow_arrayref() ) {
185 push @tables, $data->[0];
192 =item get_columns($area)
194 This will return a list of all columns for a report area
200 # this calls the internal fucntion _get_columns
201 my ($area,$cgi) = @_;
202 my $tables = $table_areas{$area};
205 foreach my $table (@$tables) {
206 my @columns = _get_columns($table,$cgi, $first);
208 push @allcolumns, @columns;
210 return ( \@allcolumns );
214 my ($tablename,$cgi, $first) = @_;
215 my $dbh = C4::Context->dbh();
216 my $sth = $dbh->prepare("show columns from $tablename");
219 my $column_defs = _get_column_defs($cgi);
221 $tablehash{'table'}=$tablename;
222 $tablehash{'__first__'} = $first;
223 push @columns, \%tablehash;
224 while ( my $data = $sth->fetchrow_arrayref() ) {
226 $temphash{'name'} = "$tablename.$data->[0]";
227 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
228 push @columns, \%temphash;
234 =item build_query($columns,$criteria,$orderby,$area)
236 This will build the sql needed to return the results asked for,
237 $columns is expected to be of the format tablename.columnname.
238 This is what get_columns returns.
243 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
245 my $keys = $keys{$area};
246 my $tables = $table_areas{$area};
249 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
254 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
256 # $keys is an array of joining constraints
257 my $dbh = C4::Context->dbh();
258 my $joinedtables = join( ',', @$tables );
259 my $joinedcolumns = join( ',', @$columns );
261 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
262 for (my $i=1;$i<@$tables;$i++){
263 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
267 $criteria =~ s/AND/WHERE/;
268 $query .= " $criteria";
271 my @definitions = split(',',$definition);
273 foreach my $def (@definitions){
274 my $defin=get_from_dictionary('',$def);
275 $deftext .=" ".$defin->[0]->{'saved_sql'};
277 if ($query =~ /WHERE/i){
281 $deftext =~ s/AND/WHERE/;
287 my @totcolumns = split( ',', $totals );
288 foreach my $total (@totcolumns) {
289 if ( $total =~ /\((.*)\)/ ) {
290 if ( $groupby eq '' ) {
291 $groupby = " GROUP BY $1";
306 =item get_criteria($area,$cgi);
308 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
313 my ($area,$cgi) = @_;
314 my $dbh = C4::Context->dbh();
315 my $crit = $criteria{$area};
316 my $column_defs = _get_column_defs($cgi);
318 foreach my $localcrit (@$crit) {
319 my ( $value, $type ) = split( /\|/, $localcrit );
320 my ( $table, $column ) = split( /\./, $value );
324 $temp{'name'} = $value;
325 $temp{'from'} = "from_" . $value;
326 $temp{'to'} = "to_" . $value;
327 $temp{'textrange'} = 1;
328 $temp{'description'} = $column_defs->{$value};
329 push @criteria_array, \%temp;
334 $temp{'name'} = $value;
336 $temp{'description'} = $column_defs->{$value};
337 push @criteria_array, \%temp;
342 $temp{'name'} = $value;
343 $temp{'from'} = "from_" . $value;
344 $temp{'to'} = "to_" . $value;
345 $temp{'daterange'} = 1;
346 $temp{'description'} = $column_defs->{$value};
347 push @criteria_array, \%temp;
352 "SELECT distinct($column) as availablevalues FROM $table";
353 my $sth = $dbh->prepare($query);
356 # push the runtime choosing option
358 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
359 $list='categorycode' if $column eq 'categorycode';
360 $list='itemtype' if $column eq 'itype';
361 $list='ccode' if $column eq 'ccode';
362 # TODO : improve to let the librarian choose the description at runtime
363 push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
364 while ( my $row = $sth->fetchrow_hashref() ) {
366 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
371 $temp{'name'} = $value;
372 $temp{'description'} = $column_defs->{$value};
373 $temp{'values'} = \@values;
375 push @criteria_array, \%temp;
381 return ( \@criteria_array );
388 ($results, $total, $error) = execute_query($sql, $offset, $limit)
392 When passed C<$sql>, this function returns an array ref containing a result set
393 suitably formatted for display in html or for output as a flat file when passed in
394 C<$format> and C<$id>. It also returns the C<$total> records available for the
395 supplied query. If passed any query other than a SELECT, or if there is a db error,
396 C<$errors> an array ref is returned containing the error after this manner:
398 C<$error->{'sqlerr'}> contains the offending SQL keyword.
399 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
401 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
402 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
403 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
404 the user in a user-supplied SQL query WILL apply in any case.
408 # returns $sql, $offset, $limit
409 # $sql returned will be transformed to:
410 # ~ remove any LIMIT clause
411 # ~ repace SELECT clause w/ SELECT count(*)
413 sub select_2_select_count_value ($) {
414 my $sql = shift or return;
415 my $countsql = select_2_select_count($sql);
416 $debug and warn "original query: $sql\ncount query: $countsql\n";
417 my $sth1 = C4::Context->dbh->prepare($countsql);
419 my $total = $sth1->fetchrow();
420 $debug and warn "total records for this query: $total\n";
423 sub select_2_select_count ($) {
424 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
425 my ($sql) = strip_limit(shift) or return;
426 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
429 sub strip_limit ($) {
430 my $sql = shift or return;
431 ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
432 $sql =~ s/\bLIMIT\b\s*\d+(\,\s*\d+)?\s*/ /ig;
433 return ($sql, (defined $1 ? $1 : 0), $2); # offset can default to 0, LIMIT cannot!
436 sub execute_query ($;$$$) {
438 my ( $sql, $offset, $limit, $no_count ) = @_;
442 carp "execute_query() called without SQL argument";
445 $offset = 0 unless $offset;
446 $limit = 9999 unless $limit;
447 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
448 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
449 return (undef, { sqlerr => $1} );
450 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
451 return (undef, { queryerr => 'Missing SELECT'} );
454 my ($useroffset, $userlimit);
456 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
457 ($sql, $useroffset, $userlimit) = strip_limit($sql);
458 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
460 (defined($userlimit ) ? $userlimit : 'UNDEF');
461 $offset += $useroffset;
463 if (defined($userlimit)) {
464 if ($offset + $limit > $userlimit ) {
465 $limit = $userlimit - $offset;
467 $total = $userlimit if $userlimit < $total; # we will never exceed a user defined LIMIT and...
468 $userlimit = $total if $userlimit > $total; # we will never exceed the total number of records available to satisfy the query
470 $sql .= " LIMIT ?, ?";
472 my $sth = C4::Context->dbh->prepare($sql);
473 $sth->execute($offset, $limit);
475 # my @xmlarray = ... ;
476 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
477 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
478 # store_results($id,$xml);
481 =item save_report($sql,$name,$type,$notes)
483 Given some sql and a name this will saved it so that it can resued
488 my ( $borrowernumber, $sql, $name, $type, $notes ) = @_;
489 my $dbh = C4::Context->dbh();
490 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
492 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
493 my $sth = $dbh->prepare($query);
494 $sth->execute( $borrowernumber, $sql, $name, $type, $notes );
498 my $id = shift || croak "No Id given";
500 my $reportname = shift;
502 my $dbh = C4::Context->dbh();
503 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
504 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ? WHERE id = ? ";
505 my $sth = $dbh->prepare($query);
506 $sth->execute( $sql, $reportname, $notes, $id );
512 my $dbh = C4::Context->dbh();
513 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
514 my $sth = $dbh->prepare($query);
516 if (my $data=$sth->fetchrow_hashref()){
517 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
518 my $sth2 = $dbh->prepare($query2);
519 $sth2->execute($xml,$id);
522 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
523 my $sth2 = $dbh->prepare($query2);
524 $sth2->execute($id,$xml);
530 my $dbh = C4::Context->dbh();
531 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
532 my $sth = $dbh->prepare($query);
534 my $data = $sth->fetchrow_hashref();
535 my $dump = new XML::Dumper;
536 my $perl = $dump->xml2pl( $data->{'report'} );
537 foreach my $row (@$perl) {
539 foreach my $key (keys %$row){
540 $htmlrow .= "<td>$row->{$key}</td>";
543 $row->{'row'} = $htmlrow;
546 $query = "SELECT * FROM saved_sql WHERE id = ?";
547 $sth = $dbh->prepare($query);
549 $data = $sth->fetchrow_hashref();
550 return ($perl,$data->{'report_name'},$data->{'notes'});
555 my $dbh = C4::Context->dbh();
556 my $query = "DELETE FROM saved_sql WHERE id = ?";
557 my $sth = $dbh->prepare($query);
561 sub get_saved_reports {
562 my $dbh = C4::Context->dbh();
563 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
564 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
565 ORDER by date_created";
566 my $sth = $dbh->prepare($query);
569 my $result = $sth->fetchall_arrayref({});
571 $_->{date_created} = format_date($_->{date_created});
573 my $member = C4::Members::GetMember(borrowernumber=>$_->{borrowernumber});
574 $_->{borrowerfirstname} = $member->{firstname};
575 $_->{borrowersurname} = $member->{surname};
580 sub get_saved_report {
582 my $dbh = C4::Context->dbh();
583 my $query = " SELECT * FROM saved_sql WHERE id = ?";
584 my $sth = $dbh->prepare($query);
586 my $data = $sth->fetchrow_hashref();
587 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
590 =item create_compound($masterID,$subreportID)
592 This will take 2 reports and create a compound report using both of them
596 sub create_compound {
597 my ($masterID,$subreportID) = @_;
598 my $dbh = C4::Context->dbh();
600 my ($mastersql,$mastertype) = get_saved_report($masterID);
601 my ($subsql,$subtype) = get_saved_report($subreportID);
603 # now we have to do some checking to see how these two will fit together
605 my ($mastertables,$subtables);
606 if ($mastersql =~ / from (.*) where /i){
609 if ($subsql =~ / from (.*) where /i){
612 return ($mastertables,$subtables);
615 =item get_column_type($column)
617 This takes a column name of the format table.column and will return what type it is
618 (free text, set values, date)
622 sub get_column_type {
623 my ($tablecolumn) = @_;
624 my ($table,$column) = split(/\./,$tablecolumn);
625 my $dbh = C4::Context->dbh();
629 # mysql doesnt support a column selection, set column to %
631 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
632 while (my $info = $sth->fetchrow_hashref()){
633 if ($info->{'COLUMN_NAME'} eq $column){
635 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
636 $info->{'TYPE_NAME'} = 'distinct';
638 return $info->{'TYPE_NAME'};
643 =item get_distinct_values($column)
645 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
646 with the distinct values of the column
650 sub get_distinct_values {
651 my ($tablecolumn) = @_;
652 my ($table,$column) = split(/\./,$tablecolumn);
653 my $dbh = C4::Context->dbh();
655 "SELECT distinct($column) as availablevalues FROM $table";
656 my $sth = $dbh->prepare($query);
658 return $sth->fetchall_arrayref({});
661 sub save_dictionary {
662 my ($name,$description,$sql,$area) = @_;
663 my $dbh = C4::Context->dbh();
664 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
665 VALUES (?,?,?,?,now(),now())";
666 my $sth = $dbh->prepare($query);
667 $sth->execute($name,$description,$sql,$area) || return 0;
671 sub get_from_dictionary {
673 my $dbh = C4::Context->dbh();
674 my $query = "SELECT * FROM reports_dictionary";
676 $query.= " WHERE area = ?";
679 $query.= " WHERE id = ?"
681 my $sth = $dbh->prepare($query);
686 $sth->execute($area);
692 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
693 while (my $data = $sth->fetchrow_hashref()){
694 $data->{'areaname'}=$reports[$data->{'area'}-1];
701 sub delete_definition {
702 my ($id) = @_ or return;
703 my $dbh = C4::Context->dbh();
704 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
705 my $sth = $dbh->prepare($query);
710 my ($id) = @_ or return;
711 my $dbh = C4::Context->dbh();
712 my $query = "SELECT * FROM saved_sql WHERE id = ?";
713 my $sth = $dbh->prepare($query);
715 my $data=$sth->fetchrow_hashref();
716 return $data->{'savedsql'};
719 sub _get_column_defs {
722 my $columns_def_file = "columns.def";
723 my $htdocs = C4::Context->config('intrahtdocs');
724 my $section='intranet';
725 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
727 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
728 open (COLUMNS,$full_path_to_columns_def_file);
729 while (my $input = <COLUMNS>){
730 my @row =split(/\t/,$input);
731 $columns{$row[0]}=$row[1];
744 Chris Cormack <crc@liblime.com>