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
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;
126 =item get_report_types()
128 This will return a list of all the available report types
132 sub get_report_types {
133 my $dbh = C4::Context->dbh();
135 # FIXME these should be in the database perhaps
136 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
138 for ( my $i = 0 ; $i < 3 ; $i++ ) {
140 $hashrep{id} = $i + 1;
141 $hashrep{name} = $reports[$i];
142 push @reports2, \%hashrep;
144 return ( \@reports2 );
148 =item get_report_areas()
150 This will return a list of all the available report areas
154 sub get_report_areas {
155 my $dbh = C4::Context->dbh();
157 # FIXME these should be in the database
158 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
160 for ( my $i = 0 ; $i < 5 ; $i++ ) {
162 $hashrep{id} = $i + 1;
163 $hashrep{name} = $reports[$i];
164 push @reports2, \%hashrep;
166 return ( \@reports2 );
170 =item get_all_tables()
172 This will return a list of all tables in the database
177 my $dbh = C4::Context->dbh();
178 my $query = "SHOW TABLES";
179 my $sth = $dbh->prepare($query);
182 while ( my $data = $sth->fetchrow_arrayref() ) {
183 push @tables, $data->[0];
190 =item get_columns($area)
192 This will return a list of all columns for a report area
198 # this calls the internal fucntion _get_columns
199 my ($area,$cgi) = @_;
200 my $tables = $table_areas{$area};
203 foreach my $table (@$tables) {
204 my @columns = _get_columns($table,$cgi, $first);
206 push @allcolumns, @columns;
208 return ( \@allcolumns );
212 my ($tablename,$cgi, $first) = @_;
213 my $dbh = C4::Context->dbh();
214 my $sth = $dbh->prepare("show columns from $tablename");
217 my $column_defs = _get_column_defs($cgi);
219 $tablehash{'table'}=$tablename;
220 $tablehash{'__first__'} = $first;
221 push @columns, \%tablehash;
222 while ( my $data = $sth->fetchrow_arrayref() ) {
224 $temphash{'name'} = "$tablename.$data->[0]";
225 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
226 push @columns, \%temphash;
232 =item build_query($columns,$criteria,$orderby,$area)
234 This will build the sql needed to return the results asked for,
235 $columns is expected to be of the format tablename.columnname.
236 This is what get_columns returns.
241 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
243 my $keys = $keys{$area};
244 my $tables = $table_areas{$area};
247 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
252 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
254 # $keys is an array of joining constraints
255 my $dbh = C4::Context->dbh();
256 my $joinedtables = join( ',', @$tables );
257 my $joinedcolumns = join( ',', @$columns );
259 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
260 for (my $i=1;$i<@$tables;$i++){
261 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
265 $criteria =~ s/AND/WHERE/;
266 $query .= " $criteria";
269 my @definitions = split(',',$definition);
271 foreach my $def (@definitions){
272 my $defin=get_from_dictionary('',$def);
273 $deftext .=" ".$defin->[0]->{'saved_sql'};
275 if ($query =~ /WHERE/i){
279 $deftext =~ s/AND/WHERE/;
285 my @totcolumns = split( ',', $totals );
286 foreach my $total (@totcolumns) {
287 if ( $total =~ /\((.*)\)/ ) {
288 if ( $groupby eq '' ) {
289 $groupby = " GROUP BY $1";
304 =item get_criteria($area,$cgi);
306 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
311 my ($area,$cgi) = @_;
312 my $dbh = C4::Context->dbh();
313 my $crit = $criteria{$area};
314 my $column_defs = _get_column_defs($cgi);
316 foreach my $localcrit (@$crit) {
317 my ( $value, $type ) = split( /\|/, $localcrit );
318 my ( $table, $column ) = split( /\./, $value );
319 if ($type eq 'textrange') {
321 $temp{'name'} = $value;
322 $temp{'from'} = "from_" . $value;
323 $temp{'to'} = "to_" . $value;
324 $temp{'textrange'} = 1;
325 $temp{'description'} = $column_defs->{$value};
326 push @criteria_array, \%temp;
328 elsif ($type eq 'date') {
330 $temp{'name'} = $value;
332 $temp{'description'} = $column_defs->{$value};
333 push @criteria_array, \%temp;
335 elsif ($type eq 'daterange') {
337 $temp{'name'} = $value;
338 $temp{'from'} = "from_" . $value;
339 $temp{'to'} = "to_" . $value;
340 $temp{'daterange'} = 1;
341 $temp{'description'} = $column_defs->{$value};
342 push @criteria_array, \%temp;
346 "SELECT distinct($column) as availablevalues FROM $table";
347 my $sth = $dbh->prepare($query);
350 # push the runtime choosing option
352 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
353 $list='categorycode' if $column eq 'categorycode';
354 $list='itemtype' if $column eq 'itype';
355 $list='ccode' if $column eq 'ccode';
356 # TODO : improve to let the librarian choose the description at runtime
357 push @values, { availablevalues => "<<$column".($list?"|$list":'').">>" };
358 while ( my $row = $sth->fetchrow_hashref() ) {
360 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 };
365 $temp{'name'} = $value;
366 $temp{'description'} = $column_defs->{$value};
367 $temp{'values'} = \@values;
369 push @criteria_array, \%temp;
373 return ( \@criteria_array );
377 my $sql = shift or return;
378 my $sth = C4::Context->dbh->prepare($sql);
380 my $rows = $sth->fetchall_arrayref();
381 return scalar (@$rows);
386 ($results, $total, $error) = execute_query($sql, $offset, $limit)
389 When passed C<$sql>, this function returns an array ref containing a result set
390 suitably formatted for display in html or for output as a flat file when passed in
391 C<$format> and C<$id>. It also returns the C<$total> records available for the
392 supplied query. If passed any query other than a SELECT, or if there is a db error,
393 C<$errors> an array ref is returned containing the error after this manner:
395 C<$error->{'sqlerr'}> contains the offending SQL keyword.
396 C<$error->{'queryerr'}> contains the native db engine error returned for the query.
398 Valid values for C<$format> are 'text,' 'tab,' 'csv,' or 'url. C<$sql>, C<$type>,
399 C<$offset>, and C<$limit> are required parameters. If a valid C<$format> is passed
400 in, C<$offset> and C<$limit> are ignored for obvious reasons. A LIMIT specified by
401 the user in a user-supplied SQL query WILL apply in any case.
405 # returns $sql, $offset, $limit
406 # $sql returned will be transformed to:
407 # ~ remove any LIMIT clause
408 # ~ repace SELECT clause w/ SELECT count(*)
410 sub select_2_select_count ($) {
411 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
412 my ($sql) = strip_limit(shift) or return;
413 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
416 sub strip_limit ($) {
417 my $sql = shift or return;
418 ($sql =~ /\bLIMIT\b/i) or return ($sql, 0, undef);
419 $sql =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
420 return ($sql, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1)); # offset can default to 0, LIMIT cannot!
423 sub execute_query ($;$$$) {
425 my ( $sql, $offset, $limit, $no_count ) = @_;
429 carp "execute_query() called without SQL argument";
432 $offset = 0 unless $offset;
433 $limit = 999999 unless $limit;
434 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
435 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
436 return (undef, { sqlerr => $1} );
437 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
438 return (undef, { queryerr => 'Missing SELECT'} );
441 my ($useroffset, $userlimit);
443 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
444 ($sql, $useroffset, $userlimit) = strip_limit($sql);
445 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
447 (defined($userlimit ) ? $userlimit : 'UNDEF');
448 $offset += $useroffset;
449 if (defined($userlimit)) {
450 if ($offset + $limit > $userlimit ) {
451 $limit = $userlimit - $offset;
452 } elsif ( ! $offset && $limit < $userlimit ) {
456 $sql .= " LIMIT ?, ?";
458 my $sth = C4::Context->dbh->prepare($sql);
459 $sth->execute($offset, $limit);
461 # my @xmlarray = ... ;
462 # my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
463 # my $xml = XML::Dumper->new()->pl2xml( \@xmlarray );
464 # store_results($id,$xml);
467 =item save_report($sql,$name,$type,$notes)
469 Given some sql and a name this will saved it so that it can reused
470 Returns id of the newly created report
475 my ( $borrowernumber, $sql, $name, $type, $notes ) = @_;
476 my $dbh = C4::Context->dbh();
477 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
479 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
480 $dbh->do( $query, undef, $borrowernumber, $sql, $name, $type, $notes );
481 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
482 $borrowernumber, $name);
487 my $id = shift || croak "No Id given";
489 my $reportname = shift;
491 my $dbh = C4::Context->dbh();
492 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
493 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, notes = ? WHERE id = ? ";
494 my $sth = $dbh->prepare($query);
495 $sth->execute( $sql, $reportname, $notes, $id );
501 my $dbh = C4::Context->dbh();
502 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
503 my $sth = $dbh->prepare($query);
505 if (my $data=$sth->fetchrow_hashref()){
506 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
507 my $sth2 = $dbh->prepare($query2);
508 $sth2->execute($xml,$id);
511 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
512 my $sth2 = $dbh->prepare($query2);
513 $sth2->execute($id,$xml);
519 my $dbh = C4::Context->dbh();
520 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
521 my $sth = $dbh->prepare($query);
523 my $data = $sth->fetchrow_hashref();
524 my $dump = new XML::Dumper;
525 my $perl = $dump->xml2pl( $data->{'report'} );
526 foreach my $row (@$perl) {
528 foreach my $key (keys %$row){
529 $htmlrow .= "<td>$row->{$key}</td>";
532 $row->{'row'} = $htmlrow;
535 $query = "SELECT * FROM saved_sql WHERE id = ?";
536 $sth = $dbh->prepare($query);
538 $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);
550 sub get_saved_reports {
551 my $dbh = C4::Context->dbh();
552 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
553 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
554 ORDER by date_created";
555 my $sth = $dbh->prepare($query);
558 my $result = $sth->fetchall_arrayref({});
560 $_->{date_created} = format_date($_->{date_created});
562 my $member = C4::Members::GetMember(borrowernumber=>$_->{borrowernumber});
563 $_->{borrowerfirstname} = $member->{firstname};
564 $_->{borrowersurname} = $member->{surname};
569 sub get_saved_report {
571 my $dbh = C4::Context->dbh();
572 my $query = " SELECT * FROM saved_sql WHERE id = ?";
573 my $sth = $dbh->prepare($query);
575 my $data = $sth->fetchrow_hashref();
576 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
579 =item create_compound($masterID,$subreportID)
581 This will take 2 reports and create a compound report using both of them
585 sub create_compound {
586 my ($masterID,$subreportID) = @_;
587 my $dbh = C4::Context->dbh();
589 my ($mastersql,$mastertype) = get_saved_report($masterID);
590 my ($subsql,$subtype) = get_saved_report($subreportID);
592 # now we have to do some checking to see how these two will fit together
594 my ($mastertables,$subtables);
595 if ($mastersql =~ / from (.*) where /i){
598 if ($subsql =~ / from (.*) where /i){
601 return ($mastertables,$subtables);
604 =item get_column_type($column)
606 This takes a column name of the format table.column and will return what type it is
607 (free text, set values, date)
611 sub get_column_type {
612 my ($tablecolumn) = @_;
613 my ($table,$column) = split(/\./,$tablecolumn);
614 my $dbh = C4::Context->dbh();
618 # mysql doesnt support a column selection, set column to %
620 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
621 while (my $info = $sth->fetchrow_hashref()){
622 if ($info->{'COLUMN_NAME'} eq $column){
624 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
625 $info->{'TYPE_NAME'} = 'distinct';
627 return $info->{'TYPE_NAME'};
632 =item get_distinct_values($column)
634 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
635 with the distinct values of the column
639 sub get_distinct_values {
640 my ($tablecolumn) = @_;
641 my ($table,$column) = split(/\./,$tablecolumn);
642 my $dbh = C4::Context->dbh();
644 "SELECT distinct($column) as availablevalues FROM $table";
645 my $sth = $dbh->prepare($query);
647 return $sth->fetchall_arrayref({});
650 sub save_dictionary {
651 my ($name,$description,$sql,$area) = @_;
652 my $dbh = C4::Context->dbh();
653 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
654 VALUES (?,?,?,?,now(),now())";
655 my $sth = $dbh->prepare($query);
656 $sth->execute($name,$description,$sql,$area) || return 0;
660 sub get_from_dictionary {
662 my $dbh = C4::Context->dbh();
663 my $query = "SELECT * FROM reports_dictionary";
665 $query.= " WHERE area = ?";
668 $query.= " WHERE id = ?"
670 my $sth = $dbh->prepare($query);
675 $sth->execute($area);
681 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
682 while (my $data = $sth->fetchrow_hashref()){
683 $data->{'areaname'}=$reports[$data->{'area'}-1];
690 sub delete_definition {
691 my ($id) = @_ or return;
692 my $dbh = C4::Context->dbh();
693 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
694 my $sth = $dbh->prepare($query);
699 my ($id) = @_ or return;
700 my $dbh = C4::Context->dbh();
701 my $query = "SELECT * FROM saved_sql WHERE id = ?";
702 my $sth = $dbh->prepare($query);
704 my $data=$sth->fetchrow_hashref();
705 return $data->{'savedsql'};
708 sub _get_column_defs {
711 my $columns_def_file = "columns.def";
712 my $htdocs = C4::Context->config('intrahtdocs');
713 my $section='intranet';
714 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
716 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
717 open (COLUMNS,$full_path_to_columns_def_file);
718 while (my $input = <COLUMNS>){
720 my @row =split(/\t/,$input);
721 $columns{$row[0]}= $row[1];
734 Chris Cormack <crc@liblime.com>