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/;
33 # use Smart::Comments;
37 # set the version for version checking
42 get_report_types get_report_areas get_columns build_query get_criteria
43 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
44 get_column_type get_distinct_values save_dictionary get_from_dictionary
45 delete_definition delete_report format_results get_sql
46 select_2_select_count_value update_sql
52 [ 'borrowers', 'statistics','items', 'biblioitems' ]; # circulation
53 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ]; # catalogue
54 $table_areas{'3'} = [ 'borrowers' ]; # patrons
55 $table_areas{'4'} = ['aqorders', 'biblio', 'items']; # acquisitions
56 $table_areas{'5'} = [ 'borrowers', 'accountlines' ]; # accounts
59 'statistics.borrowernumber=borrowers.borrowernumber',
60 'items.itemnumber = statistics.itemnumber',
61 'biblioitems.biblioitemnumber = items.biblioitemnumber'
64 'items.biblioitemnumber=biblioitems.biblioitemnumber',
65 'biblioitems.biblionumber=biblio.biblionumber'
69 'aqorders.biblionumber=biblio.biblionumber',
70 'biblio.biblionumber=items.biblionumber'
72 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
74 # have to do someting here to know if its dropdown, free text, date etc
78 'statistics.type', 'borrowers.categorycode',
80 'biblioitems.publicationyear|date',
81 'items.dateaccessioned|date'
84 [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
85 $criteria{'3'} = ['borrowers.branchcode'];
86 $criteria{'4'} = ['aqorders.datereceived|date'];
87 $criteria{'5'} = ['borrowers.branchcode'];
89 if (C4::Context->preference('item-level_itypes')) {
90 unshift @{ $criteria{'1'} }, 'items.itype';
91 unshift @{ $criteria{'2'} }, 'items.itype';
93 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
94 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
99 C4::Reports::Guided - Module for generating guided reports
103 use C4::Reports::Guided;
114 =item get_report_types()
116 This will return a list of all the available report types
120 sub get_report_types {
121 my $dbh = C4::Context->dbh();
123 # FIXME these should be in the database perhaps
124 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
126 for ( my $i = 0 ; $i < 3 ; $i++ ) {
128 $hashrep{id} = $i + 1;
129 $hashrep{name} = $reports[$i];
130 push @reports2, \%hashrep;
132 return ( \@reports2 );
136 =item get_report_areas()
138 This will return a list of all the available report areas
142 sub get_report_areas {
143 my $dbh = C4::Context->dbh();
145 # FIXME these should be in the database
146 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
148 for ( my $i = 0 ; $i < 5 ; $i++ ) {
150 $hashrep{id} = $i + 1;
151 $hashrep{name} = $reports[$i];
152 push @reports2, \%hashrep;
154 return ( \@reports2 );
158 =item get_all_tables()
160 This will return a list of all tables in the database
165 my $dbh = C4::Context->dbh();
166 my $query = "SHOW TABLES";
167 my $sth = $dbh->prepare($query);
170 while ( my $data = $sth->fetchrow_arrayref() ) {
171 push @tables, $data->[0];
178 =item get_columns($area)
180 This will return a list of all columns for a report area
186 # this calls the internal fucntion _get_columns
187 my ($area,$cgi) = @_;
188 my $tables = $table_areas{$area};
191 foreach my $table (@$tables) {
192 my @columns = _get_columns($table,$cgi, $first);
194 push @allcolumns, @columns;
196 return ( \@allcolumns );
200 my ($tablename,$cgi, $first) = @_;
201 my $dbh = C4::Context->dbh();
202 my $sth = $dbh->prepare("show columns from $tablename");
205 my $column_defs = _get_column_defs($cgi);
207 $tablehash{'table'}=$tablename;
208 $tablehash{'__first__'} = $first;
209 push @columns, \%tablehash;
210 while ( my $data = $sth->fetchrow_arrayref() ) {
212 $temphash{'name'} = "$tablename.$data->[0]";
213 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
214 push @columns, \%temphash;
220 =item build_query($columns,$criteria,$orderby,$area)
222 This will build the sql needed to return the results asked for,
223 $columns is expected to be of the format tablename.columnname.
224 This is what get_columns returns.
229 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
231 my $keys = $keys{$area};
232 my $tables = $table_areas{$area};
235 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
240 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
242 # $keys is an array of joining constraints
243 my $dbh = C4::Context->dbh();
244 my $joinedtables = join( ',', @$tables );
245 my $joinedcolumns = join( ',', @$columns );
246 my $joinedkeys = join( ' AND ', @$keys );
248 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
249 for (my $i=1;$i<@$tables;$i++){
250 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
254 $criteria =~ s/AND/WHERE/;
255 $query .= " $criteria";
258 my @definitions = split(',',$definition);
260 foreach my $def (@definitions){
261 my $defin=get_from_dictionary('',$def);
262 $deftext .=" ".$defin->[0]->{'saved_sql'};
264 if ($query =~ /WHERE/i){
268 $deftext =~ s/AND/WHERE/;
274 my @totcolumns = split( ',', $totals );
275 foreach my $total (@totcolumns) {
276 if ( $total =~ /\((.*)\)/ ) {
277 if ( $groupby eq '' ) {
278 $groupby = " GROUP BY $1";
293 =item get_criteria($area,$cgi);
295 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
300 my ($area,$cgi) = @_;
301 my $dbh = C4::Context->dbh();
302 my $crit = $criteria{$area};
303 my $column_defs = _get_column_defs($cgi);
305 foreach my $localcrit (@$crit) {
306 my ( $value, $type ) = split( /\|/, $localcrit );
307 my ( $table, $column ) = split( /\./, $value );
308 if ( $type eq 'date' ) {
310 $temp{'name'} = $value;
312 $temp{'description'} = $column_defs->{$value};
313 push @criteria_array, \%temp;
318 "SELECT distinct($column) as availablevalues FROM $table";
319 my $sth = $dbh->prepare($query);
322 while ( my $row = $sth->fetchrow_hashref() ) {
328 $temp{'name'} = $value;
329 $temp{'description'} = $column_defs->{$value};
330 $temp{'values'} = \@values;
331 push @criteria_array, \%temp;
334 return ( \@criteria_array );
341 ($results, $total, $error) = execute_query($sql, $offset, $limit)
345 When passed C<$sql>, this function returns an array ref containing a result set
346 suitably formatted for display in html or for output as a flat file when passed in
347 C<$format> and C<$id>. It also returns the C<$total> records available for the
348 supplied query. If passed any query other than a SELECT, or if there is a db error,
349 C<$errors> an array ref is returned containing the error after this manner:
351 C<$error->{'sqlerr'}> contains the offending SQL keyword.
352 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
354 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
355 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
356 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
357 the user in a user-supplied SQL query WILL apply in any case.
361 # returns $sql, $offset, $limit
362 # $sql returned will be transformed to:
363 # ~ remove any LIMIT clause
364 # ~ repace SELECT clause w/ SELECT count(*)
366 sub select_2_select_count_value ($) {
367 my $sql = shift or return;
368 my $countsql = select_2_select_count($sql);
369 $debug and warn "original query: $sql\ncount query: $countsql\n";
370 my $sth1 = C4::Context->dbh->prepare($countsql);
372 my $total = $sth1->fetchrow();
373 $debug and warn "total records for this query: $total\n";
376 sub select_2_select_count ($) {
377 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
378 my ($sql) = strip_limit(shift) or return;
379 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
382 sub strip_limit ($) {
383 my $sql = shift or return;
384 ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
385 $sql =~ s/\bLIMIT\b\s*\d+(\,\s*\d+)?\s*/ /ig;
386 return ($sql, (defined $1 ? $1 : 0), $2); # offset can default to 0, LIMIT cannot!
389 sub execute_query ($;$$$) {
391 my ( $sql, $offset, $limit, $no_count ) = @_;
395 carp "execute_query() called without SQL argument";
398 $offset = 0 unless $offset;
399 $limit = 9999 unless $limit;
400 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
401 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
402 return (undef, { sqlerr => $1} );
403 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
404 return (undef, { queryerr => 'Missing SELECT'} );
407 my ($useroffset, $userlimit);
409 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
410 ($sql, $useroffset, $userlimit) = strip_limit($sql);
411 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
413 (defined($userlimit ) ? $userlimit : 'UNDEF');
414 $offset += $useroffset;
416 if (defined($userlimit)) {
417 if ($offset + $limit > $userlimit ) {
418 $limit = $userlimit - $offset;
420 $total = $userlimit if $userlimit < $total; # we will never exceed a user defined LIMIT and...
421 $userlimit = $total if $userlimit > $total; # we will never exceed the total number of records available to satisfy the query
423 $sql .= " LIMIT ?, ?";
425 my $sth = C4::Context->dbh->prepare($sql);
426 $sth->execute($offset, $limit);
428 # my @xmlarray = ... ;
429 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
430 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
431 # store_results($id,$xml);
434 =item save_report($sql,$name,$type,$notes)
436 Given some sql and a name this will saved it so that it can resued
441 my ( $borrowernumber, $sql, $name, $type, $notes ) = @_;
442 my $dbh = C4::Context->dbh();
443 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
445 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
446 my $sth = $dbh->prepare($query);
447 $sth->execute( $borrowernumber, $sql, $name, $type, $notes );
451 my $id = shift || croak "No Id given";
453 my $reportname = shift;
454 my $dbh = C4::Context->dbh();
455 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
456 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ? WHERE id = ? ";
457 my $sth = $dbh->prepare($query);
458 $sth->execute( $sql, $reportname, $id );
464 my $dbh = C4::Context->dbh();
465 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
466 my $sth = $dbh->prepare($query);
468 if (my $data=$sth->fetchrow_hashref()){
469 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
470 my $sth2 = $dbh->prepare($query2);
471 $sth2->execute($xml,$id);
474 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
475 my $sth2 = $dbh->prepare($query2);
476 $sth2->execute($id,$xml);
482 my $dbh = C4::Context->dbh();
483 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
484 my $sth = $dbh->prepare($query);
486 my $data = $sth->fetchrow_hashref();
487 my $dump = new XML::Dumper;
488 my $perl = $dump->xml2pl( $data->{'report'} );
489 foreach my $row (@$perl) {
491 foreach my $key (keys %$row){
492 $htmlrow .= "<td>$row->{$key}</td>";
495 $row->{'row'} = $htmlrow;
498 $query = "SELECT * FROM saved_sql WHERE id = ?";
499 $sth = $dbh->prepare($query);
501 $data = $sth->fetchrow_hashref();
502 return ($perl,$data->{'report_name'},$data->{'notes'});
507 my $dbh = C4::Context->dbh();
508 my $query = "DELETE FROM saved_sql WHERE id = ?";
509 my $sth = $dbh->prepare($query);
513 sub get_saved_reports {
514 my $dbh = C4::Context->dbh();
515 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
516 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
517 ORDER by date_created";
518 my $sth = $dbh->prepare($query);
521 my $result = $sth->fetchall_arrayref({});
523 $_->{date_created} = format_date($_->{date_created});
528 sub get_saved_report {
530 my $dbh = C4::Context->dbh();
531 my $query = " SELECT * FROM saved_sql WHERE id = ?";
532 my $sth = $dbh->prepare($query);
534 my $data = $sth->fetchrow_hashref();
535 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
538 =item create_compound($masterID,$subreportID)
540 This will take 2 reports and create a compound report using both of them
544 sub create_compound {
545 my ($masterID,$subreportID) = @_;
546 my $dbh = C4::Context->dbh();
548 my ($mastersql,$mastertype) = get_saved_report($masterID);
549 my ($subsql,$subtype) = get_saved_report($subreportID);
551 # now we have to do some checking to see how these two will fit together
553 my ($mastertables,$subtables);
554 if ($mastersql =~ / from (.*) where /i){
557 if ($subsql =~ / from (.*) where /i){
560 return ($mastertables,$subtables);
563 =item get_column_type($column)
565 This takes a column name of the format table.column and will return what type it is
566 (free text, set values, date)
570 sub get_column_type {
571 my ($tablecolumn) = @_;
572 my ($table,$column) = split(/\./,$tablecolumn);
573 my $dbh = C4::Context->dbh();
577 # mysql doesnt support a column selection, set column to %
579 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
580 while (my $info = $sth->fetchrow_hashref()){
581 if ($info->{'COLUMN_NAME'} eq $column){
583 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
584 $info->{'TYPE_NAME'} = 'distinct';
586 return $info->{'TYPE_NAME'};
591 =item get_distinct_values($column)
593 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
594 with the distinct values of the column
598 sub get_distinct_values {
599 my ($tablecolumn) = @_;
600 my ($table,$column) = split(/\./,$tablecolumn);
601 my $dbh = C4::Context->dbh();
603 "SELECT distinct($column) as availablevalues FROM $table";
604 my $sth = $dbh->prepare($query);
606 return $sth->fetchall_arrayref({});
609 sub save_dictionary {
610 my ($name,$description,$sql,$area) = @_;
611 my $dbh = C4::Context->dbh();
612 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
613 VALUES (?,?,?,?,now(),now())";
614 my $sth = $dbh->prepare($query);
615 $sth->execute($name,$description,$sql,$area) || return 0;
619 sub get_from_dictionary {
621 my $dbh = C4::Context->dbh();
622 my $query = "SELECT * FROM reports_dictionary";
624 $query.= " WHERE area = ?";
627 $query.= " WHERE id = ?"
629 my $sth = $dbh->prepare($query);
634 $sth->execute($area);
640 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
641 while (my $data = $sth->fetchrow_hashref()){
642 $data->{'areaname'}=$reports[$data->{'area'}-1];
649 sub delete_definition {
650 my ($id) = @_ or return;
651 my $dbh = C4::Context->dbh();
652 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
653 my $sth = $dbh->prepare($query);
658 my ($id) = @_ or return;
659 my $dbh = C4::Context->dbh();
660 my $query = "SELECT * FROM saved_sql WHERE id = ?";
661 my $sth = $dbh->prepare($query);
663 my $data=$sth->fetchrow_hashref();
664 return $data->{'savedsql'};
667 sub _get_column_defs {
670 my $columns_def_file = "columns.def";
671 my $htdocs = C4::Context->config('intrahtdocs');
672 my $section='intranet';
673 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
675 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
676 open (COLUMNS,$full_path_to_columns_def_file);
677 while (my $input = <COLUMNS>){
678 my @row =split(/\t/,$input);
679 $columns{$row[0]}=$row[1];
692 Chris Cormack <crc@liblime.com>