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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #use warnings; FIXME - Bug 2505 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
77 # reports on circulation
79 'statistics.type', 'borrowers.categorycode',
81 'biblioitems.publicationyear|date',
82 'items.dateaccessioned|date'
84 # reports on catalogue
86 [ 'items.itemnumber|textrange', 'items.biblionumber|textrange', 'items.barcode|textrange',
87 'biblio.frameworkcode', 'items.holdingbranch', 'items.homebranch',
88 'biblio.datecreated|daterange', 'biblio.timestamp|daterange', 'items.onloan|daterange',
89 'items.ccode', 'items.itemcallnumber|textrange', 'items.itype',
90 'items.itemlost', 'items.location' ];
91 # reports on borrowers
92 $criteria{'3'} = ['borrowers.branchcode', 'borrowers.categorycode'];
93 # reports on acquisition
94 $criteria{'4'} = ['aqorders.datereceived|date'];
96 # reports on accounting
97 $criteria{'5'} = ['borrowers.branchcode', 'borrowers.categorycode'];
99 # Adds itemtypes to criteria, according to the syspref
100 if (C4::Context->preference('item-level_itypes')) {
101 unshift @{ $criteria{'1'} }, 'items.itype';
102 unshift @{ $criteria{'2'} }, 'items.itype';
104 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
105 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
110 C4::Reports::Guided - Module for generating guided reports
114 use C4::Reports::Guided;
125 =item get_report_types()
127 This will return a list of all the available report types
131 sub get_report_types {
132 my $dbh = C4::Context->dbh();
134 # FIXME these should be in the database perhaps
135 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
137 for ( my $i = 0 ; $i < 3 ; $i++ ) {
139 $hashrep{id} = $i + 1;
140 $hashrep{name} = $reports[$i];
141 push @reports2, \%hashrep;
143 return ( \@reports2 );
147 =item get_report_areas()
149 This will return a list of all the available report areas
153 sub get_report_areas {
154 my $dbh = C4::Context->dbh();
156 # FIXME these should be in the database
157 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
159 for ( my $i = 0 ; $i < 5 ; $i++ ) {
161 $hashrep{id} = $i + 1;
162 $hashrep{name} = $reports[$i];
163 push @reports2, \%hashrep;
165 return ( \@reports2 );
169 =item get_all_tables()
171 This will return a list of all tables in the database
176 my $dbh = C4::Context->dbh();
177 my $query = "SHOW TABLES";
178 my $sth = $dbh->prepare($query);
181 while ( my $data = $sth->fetchrow_arrayref() ) {
182 push @tables, $data->[0];
189 =item get_columns($area)
191 This will return a list of all columns for a report area
197 # this calls the internal fucntion _get_columns
198 my ($area,$cgi) = @_;
199 my $tables = $table_areas{$area};
202 foreach my $table (@$tables) {
203 my @columns = _get_columns($table,$cgi, $first);
205 push @allcolumns, @columns;
207 return ( \@allcolumns );
211 my ($tablename,$cgi, $first) = @_;
212 my $dbh = C4::Context->dbh();
213 my $sth = $dbh->prepare("show columns from $tablename");
216 my $column_defs = _get_column_defs($cgi);
218 $tablehash{'table'}=$tablename;
219 $tablehash{'__first__'} = $first;
220 push @columns, \%tablehash;
221 while ( my $data = $sth->fetchrow_arrayref() ) {
223 $temphash{'name'} = "$tablename.$data->[0]";
224 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
225 push @columns, \%temphash;
231 =item build_query($columns,$criteria,$orderby,$area)
233 This will build the sql needed to return the results asked for,
234 $columns is expected to be of the format tablename.columnname.
235 This is what get_columns returns.
240 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
242 my $keys = $keys{$area};
243 my $tables = $table_areas{$area};
246 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
251 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
253 # $keys is an array of joining constraints
254 my $dbh = C4::Context->dbh();
255 my $joinedtables = join( ',', @$tables );
256 my $joinedcolumns = join( ',', @$columns );
258 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
259 for (my $i=1;$i<@$tables;$i++){
260 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
264 $criteria =~ s/AND/WHERE/;
265 $query .= " $criteria";
268 my @definitions = split(',',$definition);
270 foreach my $def (@definitions){
271 my $defin=get_from_dictionary('',$def);
272 $deftext .=" ".$defin->[0]->{'saved_sql'};
274 if ($query =~ /WHERE/i){
278 $deftext =~ s/AND/WHERE/;
284 my @totcolumns = split( ',', $totals );
285 foreach my $total (@totcolumns) {
286 if ( $total =~ /\((.*)\)/ ) {
287 if ( $groupby eq '' ) {
288 $groupby = " GROUP BY $1";
303 =item get_criteria($area,$cgi);
305 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
310 my ($area,$cgi) = @_;
311 my $dbh = C4::Context->dbh();
312 my $crit = $criteria{$area};
313 my $column_defs = _get_column_defs($cgi);
315 foreach my $localcrit (@$crit) {
316 my ( $value, $type ) = split( /\|/, $localcrit );
317 my ( $table, $column ) = split( /\./, $value );
318 if ($type eq 'textrange') {
320 $temp{'name'} = $value;
321 $temp{'from'} = "from_" . $value;
322 $temp{'to'} = "to_" . $value;
323 $temp{'textrange'} = 1;
324 $temp{'description'} = $column_defs->{$value};
325 push @criteria_array, \%temp;
327 elsif ($type eq 'date') {
329 $temp{'name'} = $value;
331 $temp{'description'} = $column_defs->{$value};
332 push @criteria_array, \%temp;
334 elsif ($type eq 'daterange') {
336 $temp{'name'} = $value;
337 $temp{'from'} = "from_" . $value;
338 $temp{'to'} = "to_" . $value;
339 $temp{'daterange'} = 1;
340 $temp{'description'} = $column_defs->{$value};
341 push @criteria_array, \%temp;
345 "SELECT distinct($column) as availablevalues FROM $table";
346 my $sth = $dbh->prepare($query);
349 # push the runtime choosing option
351 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
352 $list='categorycode' if $column eq 'categorycode';
353 $list='itemtype' if $column eq 'itype';
354 $list='ccode' if $column eq 'ccode';
355 # TODO : improve to let the librarian choose the description at runtime
356 push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
357 while ( my $row = $sth->fetchrow_hashref() ) {
359 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
364 $temp{'name'} = $value;
365 $temp{'description'} = $column_defs->{$value};
366 $temp{'values'} = \@values;
368 push @criteria_array, \%temp;
372 return ( \@criteria_array );
379 ($results, $total, $error) = execute_query($sql, $offset, $limit)
383 When passed C<$sql>, this function returns an array ref containing a result set
384 suitably formatted for display in html or for output as a flat file when passed in
385 C<$format> and C<$id>. It also returns the C<$total> records available for the
386 supplied query. If passed any query other than a SELECT, or if there is a db error,
387 C<$errors> an array ref is returned containing the error after this manner:
389 C<$error->{'sqlerr'}> contains the offending SQL keyword.
390 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
392 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
393 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
394 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
395 the user in a user-supplied SQL query WILL apply in any case.
399 # returns $sql, $offset, $limit
400 # $sql returned will be transformed to:
401 # ~ remove any LIMIT clause
402 # ~ repace SELECT clause w/ SELECT count(*)
404 sub select_2_select_count_value ($) {
405 my $sql = shift or return;
406 my $countsql = select_2_select_count($sql);
407 $debug and warn "original query: $sql\ncount query: $countsql\n";
408 my $sth1 = C4::Context->dbh->prepare($countsql);
410 my $total = $sth1->fetchrow();
411 $debug and warn "total records for this query: $total\n";
414 sub select_2_select_count ($) {
415 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
416 my ($sql) = strip_limit(shift) or return;
417 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
420 sub strip_limit ($) {
421 my $sql = shift or return;
422 ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
423 $sql =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
424 return ($sql, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1)); # offset can default to 0, LIMIT cannot!
427 sub execute_query ($;$$$) {
429 my ( $sql, $offset, $limit, $no_count ) = @_;
433 carp "execute_query() called without SQL argument";
436 $offset = 0 unless $offset;
437 $limit = 9999 unless $limit;
438 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
439 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
440 return (undef, { sqlerr => $1} );
441 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
442 return (undef, { queryerr => 'Missing SELECT'} );
445 my ($useroffset, $userlimit);
447 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
448 ($sql, $useroffset, $userlimit) = strip_limit($sql);
449 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
451 (defined($userlimit ) ? $userlimit : 'UNDEF');
452 $offset += $useroffset;
453 if (defined($userlimit)) {
454 if ($offset + $limit > $userlimit ) {
455 $limit = $userlimit - $offset;
456 } elsif ( ! $offset && $limit < $userlimit ) {
460 $sql .= " LIMIT ?, ?";
462 my $sth = C4::Context->dbh->prepare($sql);
463 $sth->execute($offset, $limit);
465 # my @xmlarray = ... ;
466 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
467 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
468 # store_results($id,$xml);
471 =item save_report($sql,$name,$type,$notes)
473 Given some sql and a name this will saved it so that it can resued
478 my ( $borrowernumber, $sql, $name, $type, $notes ) = @_;
479 my $dbh = C4::Context->dbh();
480 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
482 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
483 my $sth = $dbh->prepare($query);
484 $sth->execute( $borrowernumber, $sql, $name, $type, $notes );
488 my $id = shift || croak "No Id given";
490 my $reportname = shift;
492 my $dbh = C4::Context->dbh();
493 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
494 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ? WHERE id = ? ";
495 my $sth = $dbh->prepare($query);
496 $sth->execute( $sql, $reportname, $notes, $id );
502 my $dbh = C4::Context->dbh();
503 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
504 my $sth = $dbh->prepare($query);
506 if (my $data=$sth->fetchrow_hashref()){
507 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
508 my $sth2 = $dbh->prepare($query2);
509 $sth2->execute($xml,$id);
512 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
513 my $sth2 = $dbh->prepare($query2);
514 $sth2->execute($id,$xml);
520 my $dbh = C4::Context->dbh();
521 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
522 my $sth = $dbh->prepare($query);
524 my $data = $sth->fetchrow_hashref();
525 my $dump = new XML::Dumper;
526 my $perl = $dump->xml2pl( $data->{'report'} );
527 foreach my $row (@$perl) {
529 foreach my $key (keys %$row){
530 $htmlrow .= "<td>$row->{$key}</td>";
533 $row->{'row'} = $htmlrow;
536 $query = "SELECT * FROM saved_sql WHERE id = ?";
537 $sth = $dbh->prepare($query);
539 $data = $sth->fetchrow_hashref();
540 return ($perl,$data->{'report_name'},$data->{'notes'});
545 my $dbh = C4::Context->dbh();
546 my $query = "DELETE FROM saved_sql WHERE id = ?";
547 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 my $result = $sth->fetchall_arrayref({});
561 $_->{date_created} = format_date($_->{date_created});
563 my $member = C4::Members::GetMember(borrowernumber=>$_->{borrowernumber});
564 $_->{borrowerfirstname} = $member->{firstname};
565 $_->{borrowersurname} = $member->{surname};
570 sub get_saved_report {
572 my $dbh = C4::Context->dbh();
573 my $query = " SELECT * FROM saved_sql WHERE id = ?";
574 my $sth = $dbh->prepare($query);
576 my $data = $sth->fetchrow_hashref();
577 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
580 =item create_compound($masterID,$subreportID)
582 This will take 2 reports and create a compound report using both of them
586 sub create_compound {
587 my ($masterID,$subreportID) = @_;
588 my $dbh = C4::Context->dbh();
590 my ($mastersql,$mastertype) = get_saved_report($masterID);
591 my ($subsql,$subtype) = get_saved_report($subreportID);
593 # now we have to do some checking to see how these two will fit together
595 my ($mastertables,$subtables);
596 if ($mastersql =~ / from (.*) where /i){
599 if ($subsql =~ / from (.*) where /i){
602 return ($mastertables,$subtables);
605 =item get_column_type($column)
607 This takes a column name of the format table.column and will return what type it is
608 (free text, set values, date)
612 sub get_column_type {
613 my ($tablecolumn) = @_;
614 my ($table,$column) = split(/\./,$tablecolumn);
615 my $dbh = C4::Context->dbh();
619 # mysql doesnt support a column selection, set column to %
621 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
622 while (my $info = $sth->fetchrow_hashref()){
623 if ($info->{'COLUMN_NAME'} eq $column){
625 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
626 $info->{'TYPE_NAME'} = 'distinct';
628 return $info->{'TYPE_NAME'};
633 =item get_distinct_values($column)
635 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
636 with the distinct values of the column
640 sub get_distinct_values {
641 my ($tablecolumn) = @_;
642 my ($table,$column) = split(/\./,$tablecolumn);
643 my $dbh = C4::Context->dbh();
645 "SELECT distinct($column) as availablevalues FROM $table";
646 my $sth = $dbh->prepare($query);
648 return $sth->fetchall_arrayref({});
651 sub save_dictionary {
652 my ($name,$description,$sql,$area) = @_;
653 my $dbh = C4::Context->dbh();
654 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
655 VALUES (?,?,?,?,now(),now())";
656 my $sth = $dbh->prepare($query);
657 $sth->execute($name,$description,$sql,$area) || return 0;
661 sub get_from_dictionary {
663 my $dbh = C4::Context->dbh();
664 my $query = "SELECT * FROM reports_dictionary";
666 $query.= " WHERE area = ?";
669 $query.= " WHERE id = ?"
671 my $sth = $dbh->prepare($query);
676 $sth->execute($area);
682 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
683 while (my $data = $sth->fetchrow_hashref()){
684 $data->{'areaname'}=$reports[$data->{'area'}-1];
691 sub delete_definition {
692 my ($id) = @_ or return;
693 my $dbh = C4::Context->dbh();
694 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
695 my $sth = $dbh->prepare($query);
700 my ($id) = @_ or return;
701 my $dbh = C4::Context->dbh();
702 my $query = "SELECT * FROM saved_sql WHERE id = ?";
703 my $sth = $dbh->prepare($query);
705 my $data=$sth->fetchrow_hashref();
706 return $data->{'savedsql'};
709 sub _get_column_defs {
712 my $columns_def_file = "columns.def";
713 my $htdocs = C4::Context->config('intrahtdocs');
714 my $section='intranet';
715 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
717 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
718 open (COLUMNS,$full_path_to_columns_def_file);
719 while (my $input = <COLUMNS>){
720 my @row =split(/\t/,$input);
721 $columns{$row[0]}=$row[1];
734 Chris Cormack <crc@liblime.com>