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;
455 my $dbh = C4::Context->dbh();
456 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
457 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ? WHERE id = ? ";
458 my $sth = $dbh->prepare($query);
459 $sth->execute( $sql, $reportname, $notes, $id );
465 my $dbh = C4::Context->dbh();
466 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
467 my $sth = $dbh->prepare($query);
469 if (my $data=$sth->fetchrow_hashref()){
470 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
471 my $sth2 = $dbh->prepare($query2);
472 $sth2->execute($xml,$id);
475 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
476 my $sth2 = $dbh->prepare($query2);
477 $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();
503 return ($perl,$data->{'report_name'},$data->{'notes'});
508 my $dbh = C4::Context->dbh();
509 my $query = "DELETE FROM saved_sql WHERE id = ?";
510 my $sth = $dbh->prepare($query);
514 sub get_saved_reports {
515 my $dbh = C4::Context->dbh();
516 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
517 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
518 ORDER by date_created";
519 my $sth = $dbh->prepare($query);
522 my $result = $sth->fetchall_arrayref({});
524 $_->{date_created} = format_date($_->{date_created});
526 my $member = C4::Members::GetMember($_->{borrowernumber});
527 $_->{borrowerfirstname} = $member->{firstname};
528 $_->{borrowersurname} = $member->{surname};
533 sub get_saved_report {
535 my $dbh = C4::Context->dbh();
536 my $query = " SELECT * FROM saved_sql WHERE id = ?";
537 my $sth = $dbh->prepare($query);
539 my $data = $sth->fetchrow_hashref();
540 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
543 =item create_compound($masterID,$subreportID)
545 This will take 2 reports and create a compound report using both of them
549 sub create_compound {
550 my ($masterID,$subreportID) = @_;
551 my $dbh = C4::Context->dbh();
553 my ($mastersql,$mastertype) = get_saved_report($masterID);
554 my ($subsql,$subtype) = get_saved_report($subreportID);
556 # now we have to do some checking to see how these two will fit together
558 my ($mastertables,$subtables);
559 if ($mastersql =~ / from (.*) where /i){
562 if ($subsql =~ / from (.*) where /i){
565 return ($mastertables,$subtables);
568 =item get_column_type($column)
570 This takes a column name of the format table.column and will return what type it is
571 (free text, set values, date)
575 sub get_column_type {
576 my ($tablecolumn) = @_;
577 my ($table,$column) = split(/\./,$tablecolumn);
578 my $dbh = C4::Context->dbh();
582 # mysql doesnt support a column selection, set column to %
584 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
585 while (my $info = $sth->fetchrow_hashref()){
586 if ($info->{'COLUMN_NAME'} eq $column){
588 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
589 $info->{'TYPE_NAME'} = 'distinct';
591 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);
611 return $sth->fetchall_arrayref({});
614 sub save_dictionary {
615 my ($name,$description,$sql,$area) = @_;
616 my $dbh = C4::Context->dbh();
617 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
618 VALUES (?,?,?,?,now(),now())";
619 my $sth = $dbh->prepare($query);
620 $sth->execute($name,$description,$sql,$area) || return 0;
624 sub get_from_dictionary {
626 my $dbh = C4::Context->dbh();
627 my $query = "SELECT * FROM reports_dictionary";
629 $query.= " WHERE area = ?";
632 $query.= " WHERE id = ?"
634 my $sth = $dbh->prepare($query);
639 $sth->execute($area);
645 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
646 while (my $data = $sth->fetchrow_hashref()){
647 $data->{'areaname'}=$reports[$data->{'area'}-1];
654 sub delete_definition {
655 my ($id) = @_ or return;
656 my $dbh = C4::Context->dbh();
657 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
658 my $sth = $dbh->prepare($query);
663 my ($id) = @_ or return;
664 my $dbh = C4::Context->dbh();
665 my $query = "SELECT * FROM saved_sql WHERE id = ?";
666 my $sth = $dbh->prepare($query);
668 my $data=$sth->fetchrow_hashref();
669 return $data->{'savedsql'};
672 sub _get_column_defs {
675 my $columns_def_file = "columns.def";
676 my $htdocs = C4::Context->config('intrahtdocs');
677 my $section='intranet';
678 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
680 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
681 open (COLUMNS,$full_path_to_columns_def_file);
682 while (my $input = <COLUMNS>){
683 my @row =split(/\t/,$input);
684 $columns{$row[0]}=$row[1];
697 Chris Cormack <crc@liblime.com>