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
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::Guided - Module for generating guided reports
98 use C4::Reports::Guided;
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 );
336 ($results, $total) = execute_query($sql, $type, $offset, $limit, $format, $id)
340 When passed C<$sql>, this function returns an array ref containing a result set
341 suitably formatted for display in html or for output as a flat file when passed in
342 C<$format> and C<$id>. It also returns the C<$total> records available for the
343 supplied query. If passed any query other than a SELECT, or if there is a db error,
344 C<$errors> an array ref is returned containing the error after this manner:
346 C<$error->{'sqlerr'}> contains the offending SQL keyword.
347 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
349 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
350 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
351 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
352 the user in a user-supplied SQL query WILL apply in any case.
356 # FIXME: This needs to be generalized to reports in general
358 sub execute_query ($$$$;$$) {
359 my ( $sql, $type, $offset, $limit, $format, $id ) = @_;
362 my ($useroffset, $userlimit);
366 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
368 $error->{'sqlerr'} = $1;
369 push @errors, $error;
370 } elsif ($sql !~ /^(SELECT)/i) {
372 $error->{'queryerr'} = 'Missing SELECT';
373 push @errors, $error;
376 my $dbh = C4::Context->dbh();
377 unless ($format eq 'text' || $format eq 'tab' || $format eq 'csv' || $format eq 'url'){
378 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
379 if ($sql =~ /LIMIT/i) {
380 $sql =~ s/LIMIT\W?(\d+)?\,?\W+?(\d+)//ig;
381 $debug and warn "User has supplied LIMIT\n";
384 $debug and warn "User supplied offset = $useroffset, limit = $userlimit\n";
385 $offset += $useroffset if $useroffset;
386 # keep track of where we are if there is a user supplied LIMIT
387 if ( $offset + $limit > $userlimit ) {
388 $limit = $userlimit - $offset;
392 $sql .= " LIMIT ?, ?";
393 $debug and warn "Passing query with params offset = $offset, limit = $limit\n";
394 @params = ($offset, $limit);
395 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
396 $countsql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
397 $debug and warn "original query: $sql\n";
398 $debug and warn "count query: $countsql\n";
399 my $sth1 = $dbh->prepare($countsql);
401 $total = $sth1->fetchrow();
402 $debug and warn "total records for this query: $total\n";
403 $total = $userlimit if defined($userlimit) and $userlimit < $total; # we will never exceed a user defined LIMIT and...
404 $userlimit = $total if defined($userlimit) and $userlimit > $total; # we will never exceed the total number of records available to satisfy the query
406 my $sth = $dbh->prepare($sql);
407 $sth->execute(@params);
408 my $colnames=$sth->{'NAME'};
412 $row = join ('</th><th>',@$colnames);
413 $row = "<tr><th>$row</th></tr>";
414 $temphash{'row'} = $row;
415 push @results, \%temphash;
417 if ($format eq 'tab') {
418 $string = join("\t",@$colnames);
420 if ($format eq 'csv') {
421 $string = join(",",@$colnames);
424 while ( my @data = $sth->fetchrow_array() ) {
425 # if the field is a date field, it needs formatting
426 foreach my $data (@data) {
427 next unless $data =~ C4::Dates->regexp("iso");
428 my $date = C4::Dates->new($data, "iso");
429 $data = $date->output();
433 my $row = join( '</td><td>', @data );
434 $row = "<tr><td>$row</td></tr>";
435 $temphash{'row'} = $row;
436 if ( $format eq 'text' ) {
437 $string .= "\n" . $row;
439 if ($format eq 'tab' ){
440 $row = join("\t",@data);
441 $string .="\n" . $row;
443 if ($format eq 'csv' ){
444 $row = join(",",@data);
445 $string .="\n" . $row;
447 if ($format eq 'url'){
449 @$temphash{@$colnames}=@data;
450 push @xmlarray,$temphash;
452 push @results, \%temphash;
454 if (defined($sth->errstr)) {
455 $error->{'queryerr'} = $sth->errstr;
456 push @errors, $error;
457 warn "Database returned: $sth->errstr";
459 if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
460 return $string, $total, \@errors;
462 elsif ($format eq 'url') {
463 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
464 my $dump = new XML::Dumper;
465 my $xml = $dump->pl2xml( \@xmlarray );
466 store_results($id,$xml);
467 return $url, $total, \@errors;
470 return \@results, $total, \@errors;
473 return undef, undef, \@errors;
477 =item save_report($sql,$name,$type,$notes)
479 Given some sql and a name this will saved it so that it can resued
484 my ( $sql, $name, $type, $notes ) = @_;
485 my $dbh = C4::Context->dbh();
486 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
488 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
489 my $sth = $dbh->prepare($query);
490 $sth->execute( 0, $sql, $name, $type, $notes );
497 my $dbh = C4::Context->dbh();
498 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
499 my $sth = $dbh->prepare($query);
501 if (my $data=$sth->fetchrow_hashref()){
502 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
503 my $sth2 = $dbh->prepare($query2);
504 $sth2->execute($xml,$id);
508 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
509 my $sth2 = $dbh->prepare($query2);
510 $sth2->execute($id,$xml);
518 my $dbh = C4::Context->dbh();
519 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
520 my $sth = $dbh->prepare($query);
522 my $data = $sth->fetchrow_hashref();
523 my $dump = new XML::Dumper;
524 my $perl = $dump->xml2pl( $data->{'report'} );
525 foreach my $row (@$perl) {
527 foreach my $key (keys %$row){
528 $htmlrow .= "<td>$row->{$key}</td>";
531 $row->{'row'} = $htmlrow;
534 $query = "SELECT * FROM saved_sql WHERE id = ?";
535 $sth = $dbh->prepare($query);
537 $data = $sth->fetchrow_hashref();
539 return ($perl,$data->{'report_name'},$data->{'notes'});
544 my $dbh = C4::Context->dbh();
545 my $query = "DELETE FROM saved_sql WHERE id = ?";
546 my $sth = $dbh->prepare($query);
551 sub get_saved_reports {
552 my $dbh = C4::Context->dbh();
553 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
554 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
555 ORDER by date_created";
556 my $sth = $dbh->prepare($query);
559 while ( my $data = $sth->fetchrow_hashref() ) {
560 push @reports, $data;
563 return ( \@reports );
566 sub get_saved_report {
568 my $dbh = C4::Context->dbh();
569 my $query = " SELECT * FROM saved_sql WHERE id = ?";
570 my $sth = $dbh->prepare($query);
572 my $data = $sth->fetchrow_hashref();
574 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
577 =item create_compound($masterID,$subreportID)
579 This will take 2 reports and create a compound report using both of them
583 sub create_compound {
584 my ($masterID,$subreportID) = @_;
585 my $dbh = C4::Context->dbh();
587 my ($mastersql,$mastertype) = get_saved_report($masterID);
588 my ($subsql,$subtype) = get_saved_report($subreportID);
590 # now we have to do some checking to see how these two will fit together
592 my ($mastertables,$subtables);
593 if ($mastersql =~ / from (.*) where /i){
596 if ($subsql =~ / from (.*) where /i){
599 return ($mastertables,$subtables);
602 =item get_column_type($column)
604 This takes a column name of the format table.column and will return what type it is
605 (free text, set values, date)
609 sub get_column_type {
610 my ($tablecolumn) = @_;
611 my ($table,$column) = split(/\./,$tablecolumn);
612 my $dbh = C4::Context->dbh();
616 # mysql doesnt support a column selection, set column to %
618 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
619 while (my $info = $sth->fetchrow_hashref()){
620 if ($info->{'COLUMN_NAME'} eq $column){
622 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
623 $info->{'TYPE_NAME'} = 'distinct';
625 return $info->{'TYPE_NAME'};
631 =item get_distinct_values($column)
633 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
634 with the distinct values of the column
638 sub get_distinct_values {
639 my ($tablecolumn) = @_;
640 my ($table,$column) = split(/\./,$tablecolumn);
641 my $dbh = C4::Context->dbh();
643 "SELECT distinct($column) as availablevalues FROM $table";
644 my $sth = $dbh->prepare($query);
647 while ( my $row = $sth->fetchrow_hashref() ) {
654 sub save_dictionary {
655 my ($name,$description,$sql,$area) = @_;
656 my $dbh = C4::Context->dbh();
657 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
658 VALUES (?,?,?,?,now(),now())";
659 my $sth = $dbh->prepare($query);
660 $sth->execute($name,$description,$sql,$area) || return 0;
665 sub get_from_dictionary {
667 my $dbh = C4::Context->dbh();
668 my $query = "SELECT * FROM reports_dictionary";
670 $query.= " WHERE area = ?";
673 $query.= " WHERE id = ?"
675 my $sth = $dbh->prepare($query);
680 $sth->execute($area);
686 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
687 while (my $data = $sth->fetchrow_hashref()){
688 $data->{'areaname'}=$reports[$data->{'area'}-1];
696 sub delete_definition {
698 my $dbh = C4::Context->dbh();
699 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
700 my $sth = $dbh->prepare($query);
707 my $dbh = C4::Context->dbh();
708 my $query = "SELECT * FROM saved_sql WHERE id = ?";
709 my $sth = $dbh->prepare($query);
711 my $data=$sth->fetchrow_hashref();
713 return $data->{'savedsql'};
716 sub _get_column_defs {
719 my $columns_def_file = "columns.def";
720 my $htdocs = C4::Context->config('intrahtdocs');
721 my $section='intranet';
722 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
724 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
725 open (COLUMNS,$full_path_to_columns_def_file);
726 while (my $input = <COLUMNS>){
727 my @row =split(/\t/,$input);
728 $columns{$row[0]}=$row[1];
741 Chris Cormack <crc@liblime.com>