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);
32 # use Smart::Comments;
36 # set the version for version checking
41 get_report_types get_report_areas get_columns build_query get_criteria
42 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
43 get_column_type get_distinct_values save_dictionary get_from_dictionary
44 delete_definition delete_report format_results get_sql
45 select_2_select_count_value update_sql
51 [ 'borrowers', 'statistics','items', 'biblioitems' ]; # circulation
52 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ]; # catalogue
53 $table_areas{'3'} = [ 'borrowers' ]; # patrons
54 $table_areas{'4'} = ['aqorders', 'biblio', 'items']; # acquisitions
55 $table_areas{'5'} = [ 'borrowers', 'accountlines' ]; # accounts
58 'statistics.borrowernumber=borrowers.borrowernumber',
59 'items.itemnumber = statistics.itemnumber',
60 'biblioitems.biblioitemnumber = items.biblioitemnumber'
63 'items.biblioitemnumber=biblioitems.biblioitemnumber',
64 'biblioitems.biblionumber=biblio.biblionumber'
68 'aqorders.biblionumber=biblio.biblionumber',
69 'biblio.biblionumber=items.biblionumber'
71 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
73 # have to do someting here to know if its dropdown, free text, date etc
77 'statistics.type', 'borrowers.categorycode',
79 'biblioitems.publicationyear|date',
80 'items.dateaccessioned|date'
83 [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
84 $criteria{'3'} = ['borrowers.branchcode'];
85 $criteria{'4'} = ['aqorders.datereceived|date'];
86 $criteria{'5'} = ['borrowers.branchcode'];
88 if (C4::Context->preference('item-level_itypes')) {
89 unshift @{ $criteria{'1'} }, 'items.itype';
90 unshift @{ $criteria{'2'} }, 'items.itype';
92 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
93 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
98 C4::Reports::Guided - Module for generating guided reports
102 use C4::Reports::Guided;
113 =item get_report_types()
115 This will return a list of all the available report types
119 sub get_report_types {
120 my $dbh = C4::Context->dbh();
122 # FIXME these should be in the database perhaps
123 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
125 for ( my $i = 0 ; $i < 3 ; $i++ ) {
127 $hashrep{id} = $i + 1;
128 $hashrep{name} = $reports[$i];
129 push @reports2, \%hashrep;
131 return ( \@reports2 );
135 =item get_report_areas()
137 This will return a list of all the available report areas
141 sub get_report_areas {
142 my $dbh = C4::Context->dbh();
144 # FIXME these should be in the database
145 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
147 for ( my $i = 0 ; $i < 5 ; $i++ ) {
149 $hashrep{id} = $i + 1;
150 $hashrep{name} = $reports[$i];
151 push @reports2, \%hashrep;
153 return ( \@reports2 );
157 =item get_all_tables()
159 This will return a list of all tables in the database
164 my $dbh = C4::Context->dbh();
165 my $query = "SHOW TABLES";
166 my $sth = $dbh->prepare($query);
169 while ( my $data = $sth->fetchrow_arrayref() ) {
170 push @tables, $data->[0];
177 =item get_columns($area)
179 This will return a list of all columns for a report area
185 # this calls the internal fucntion _get_columns
186 my ($area,$cgi) = @_;
187 my $tables = $table_areas{$area};
190 foreach my $table (@$tables) {
191 my @columns = _get_columns($table,$cgi, $first);
193 push @allcolumns, @columns;
195 return ( \@allcolumns );
199 my ($tablename,$cgi, $first) = @_;
200 my $dbh = C4::Context->dbh();
201 my $sth = $dbh->prepare("show columns from $tablename");
204 my $column_defs = _get_column_defs($cgi);
206 $tablehash{'table'}=$tablename;
207 $tablehash{'__first__'} = $first;
208 push @columns, \%tablehash;
209 while ( my $data = $sth->fetchrow_arrayref() ) {
211 $temphash{'name'} = "$tablename.$data->[0]";
212 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
213 push @columns, \%temphash;
219 =item build_query($columns,$criteria,$orderby,$area)
221 This will build the sql needed to return the results asked for,
222 $columns is expected to be of the format tablename.columnname.
223 This is what get_columns returns.
228 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
230 my $keys = $keys{$area};
231 my $tables = $table_areas{$area};
234 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
239 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
241 # $keys is an array of joining constraints
242 my $dbh = C4::Context->dbh();
243 my $joinedtables = join( ',', @$tables );
244 my $joinedcolumns = join( ',', @$columns );
245 my $joinedkeys = join( ' AND ', @$keys );
247 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
248 for (my $i=1;$i<@$tables;$i++){
249 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
253 $criteria =~ s/AND/WHERE/;
254 $query .= " $criteria";
257 my @definitions = split(',',$definition);
259 foreach my $def (@definitions){
260 my $defin=get_from_dictionary('',$def);
261 $deftext .=" ".$defin->[0]->{'saved_sql'};
263 if ($query =~ /WHERE/i){
267 $deftext =~ s/AND/WHERE/;
273 my @totcolumns = split( ',', $totals );
274 foreach my $total (@totcolumns) {
275 if ( $total =~ /\((.*)\)/ ) {
276 if ( $groupby eq '' ) {
277 $groupby = " GROUP BY $1";
292 =item get_criteria($area,$cgi);
294 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
299 my ($area,$cgi) = @_;
300 my $dbh = C4::Context->dbh();
301 my $crit = $criteria{$area};
302 my $column_defs = _get_column_defs($cgi);
304 foreach my $localcrit (@$crit) {
305 my ( $value, $type ) = split( /\|/, $localcrit );
306 my ( $table, $column ) = split( /\./, $value );
307 if ( $type eq 'date' ) {
309 $temp{'name'} = $value;
311 $temp{'description'} = $column_defs->{$value};
312 push @criteria_array, \%temp;
317 "SELECT distinct($column) as availablevalues FROM $table";
318 my $sth = $dbh->prepare($query);
321 while ( my $row = $sth->fetchrow_hashref() ) {
327 $temp{'name'} = $value;
328 $temp{'description'} = $column_defs->{$value};
329 $temp{'values'} = \@values;
330 push @criteria_array, \%temp;
333 return ( \@criteria_array );
340 ($results, $total, $error) = execute_query($sql, $offset, $limit)
344 When passed C<$sql>, this function returns an array ref containing a result set
345 suitably formatted for display in html or for output as a flat file when passed in
346 C<$format> and C<$id>. It also returns the C<$total> records available for the
347 supplied query. If passed any query other than a SELECT, or if there is a db error,
348 C<$errors> an array ref is returned containing the error after this manner:
350 C<$error->{'sqlerr'}> contains the offending SQL keyword.
351 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
353 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
354 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
355 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
356 the user in a user-supplied SQL query WILL apply in any case.
360 # returns $sql, $offset, $limit
361 # $sql returned will be transformed to:
362 # ~ remove any LIMIT clause
363 # ~ repace SELECT clause w/ SELECT count(*)
365 sub select_2_select_count_value ($) {
366 my $sql = shift or return;
367 my $countsql = select_2_select_count($sql);
368 $debug and warn "original query: $sql\ncount query: $countsql\n";
369 my $sth1 = C4::Context->dbh->prepare($countsql);
371 my $total = $sth1->fetchrow();
372 $debug and warn "total records for this query: $total\n";
375 sub select_2_select_count ($) {
376 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
377 my ($sql) = strip_limit(shift) or return;
378 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
381 sub strip_limit ($) {
382 my $sql = shift or return;
383 ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
384 $sql =~ s/\bLIMIT\b\s*\d+(\,\s*\d+)?\s*/ /ig;
385 return ($sql, (defined $1 ? $1 : 0), $2); # offset can default to 0, LIMIT cannot!
388 sub execute_query ($;$$$) {
390 my ( $sql, $offset, $limit, $no_count ) = @_;
394 carp "execute_query() called without SQL argument";
397 $offset = 0 unless $offset;
398 $limit = 9999 unless $limit;
399 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
400 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
401 return (undef, { sqlerr => $1} );
402 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
403 return (undef, { queryerr => 'Missing SELECT'} );
406 my ($useroffset, $userlimit);
408 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
409 ($sql, $useroffset, $userlimit) = strip_limit($sql);
410 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
412 (defined($userlimit ) ? $userlimit : 'UNDEF');
413 $offset += $useroffset;
415 if (defined($userlimit)) {
416 if ($offset + $limit > $userlimit ) {
417 $limit = $userlimit - $offset;
419 $total = $userlimit if $userlimit < $total; # we will never exceed a user defined LIMIT and...
420 $userlimit = $total if $userlimit > $total; # we will never exceed the total number of records available to satisfy the query
422 $sql .= " LIMIT ?, ?";
424 my $sth = C4::Context->dbh->prepare($sql);
425 $sth->execute($offset, $limit);
427 # my @xmlarray = ... ;
428 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
429 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
430 # store_results($id,$xml);
433 =item save_report($sql,$name,$type,$notes)
435 Given some sql and a name this will saved it so that it can resued
440 my ( $sql, $name, $type, $notes ) = @_;
441 my $dbh = C4::Context->dbh();
442 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
444 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
445 my $sth = $dbh->prepare($query);
446 $sth->execute( 0, $sql, $name, $type, $notes );
450 my $id = shift || croak "No Id given";
452 my $reportname = shift;
453 my $dbh = C4::Context->dbh();
454 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
455 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ? WHERE id = ? ";
456 my $sth = $dbh->prepare($query);
457 $sth->execute( $sql, $reportname, $id );
463 my $dbh = C4::Context->dbh();
464 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
465 my $sth = $dbh->prepare($query);
467 if (my $data=$sth->fetchrow_hashref()){
468 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
469 my $sth2 = $dbh->prepare($query2);
470 $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);
481 my $dbh = C4::Context->dbh();
482 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
483 my $sth = $dbh->prepare($query);
485 my $data = $sth->fetchrow_hashref();
486 my $dump = new XML::Dumper;
487 my $perl = $dump->xml2pl( $data->{'report'} );
488 foreach my $row (@$perl) {
490 foreach my $key (keys %$row){
491 $htmlrow .= "<td>$row->{$key}</td>";
494 $row->{'row'} = $htmlrow;
497 $query = "SELECT * FROM saved_sql WHERE id = ?";
498 $sth = $dbh->prepare($query);
500 $data = $sth->fetchrow_hashref();
501 return ($perl,$data->{'report_name'},$data->{'notes'});
506 my $dbh = C4::Context->dbh();
507 my $query = "DELETE FROM saved_sql WHERE id = ?";
508 my $sth = $dbh->prepare($query);
512 sub get_saved_reports {
513 my $dbh = C4::Context->dbh();
514 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
515 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
516 ORDER by date_created";
517 my $sth = $dbh->prepare($query);
519 return $sth->fetchall_arrayref({});
522 sub get_saved_report {
524 my $dbh = C4::Context->dbh();
525 my $query = " SELECT * FROM saved_sql WHERE id = ?";
526 my $sth = $dbh->prepare($query);
528 my $data = $sth->fetchrow_hashref();
529 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
532 =item create_compound($masterID,$subreportID)
534 This will take 2 reports and create a compound report using both of them
538 sub create_compound {
539 my ($masterID,$subreportID) = @_;
540 my $dbh = C4::Context->dbh();
542 my ($mastersql,$mastertype) = get_saved_report($masterID);
543 my ($subsql,$subtype) = get_saved_report($subreportID);
545 # now we have to do some checking to see how these two will fit together
547 my ($mastertables,$subtables);
548 if ($mastersql =~ / from (.*) where /i){
551 if ($subsql =~ / from (.*) where /i){
554 return ($mastertables,$subtables);
557 =item get_column_type($column)
559 This takes a column name of the format table.column and will return what type it is
560 (free text, set values, date)
564 sub get_column_type {
565 my ($tablecolumn) = @_;
566 my ($table,$column) = split(/\./,$tablecolumn);
567 my $dbh = C4::Context->dbh();
571 # mysql doesnt support a column selection, set column to %
573 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
574 while (my $info = $sth->fetchrow_hashref()){
575 if ($info->{'COLUMN_NAME'} eq $column){
577 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
578 $info->{'TYPE_NAME'} = 'distinct';
580 return $info->{'TYPE_NAME'};
585 =item get_distinct_values($column)
587 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
588 with the distinct values of the column
592 sub get_distinct_values {
593 my ($tablecolumn) = @_;
594 my ($table,$column) = split(/\./,$tablecolumn);
595 my $dbh = C4::Context->dbh();
597 "SELECT distinct($column) as availablevalues FROM $table";
598 my $sth = $dbh->prepare($query);
600 return $sth->fetchall_arrayref({});
603 sub save_dictionary {
604 my ($name,$description,$sql,$area) = @_;
605 my $dbh = C4::Context->dbh();
606 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
607 VALUES (?,?,?,?,now(),now())";
608 my $sth = $dbh->prepare($query);
609 $sth->execute($name,$description,$sql,$area) || return 0;
613 sub get_from_dictionary {
615 my $dbh = C4::Context->dbh();
616 my $query = "SELECT * FROM reports_dictionary";
618 $query.= " WHERE area = ?";
621 $query.= " WHERE id = ?"
623 my $sth = $dbh->prepare($query);
628 $sth->execute($area);
634 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
635 while (my $data = $sth->fetchrow_hashref()){
636 $data->{'areaname'}=$reports[$data->{'area'}-1];
643 sub delete_definition {
644 my ($id) = @_ or return;
645 my $dbh = C4::Context->dbh();
646 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
647 my $sth = $dbh->prepare($query);
652 my ($id) = @_ or return;
653 my $dbh = C4::Context->dbh();
654 my $query = "SELECT * FROM saved_sql WHERE id = ?";
655 my $sth = $dbh->prepare($query);
657 my $data=$sth->fetchrow_hashref();
658 return $data->{'savedsql'};
661 sub _get_column_defs {
664 my $columns_def_file = "columns.def";
665 my $htdocs = C4::Context->config('intrahtdocs');
666 my $section='intranet';
667 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
669 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
670 open (COLUMNS,$full_path_to_columns_def_file);
671 while (my $input = <COLUMNS>){
672 my @row =split(/\t/,$input);
673 $columns{$row[0]}=$row[1];
686 Chris Cormack <crc@liblime.com>