bug-2149, added new block to C4::Letters::SendAlerts() to email 'account creation...
[koha.git] / C4 / Reports.pm
blob376196aac63b8da2c4b18d69db99d64b162849b2
1 package C4::Reports;
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
10 # version.
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
20 use strict;
21 use CGI;
23 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
24 use C4::Context;
25 use C4::Output;
26 use XML::Simple;
27 use XML::Dumper;
28 # use Smart::Comments;
29 # use Data::Dumper;
31 BEGIN {
32 # set the version for version checking
33 $VERSION = 0.12;
34 require Exporter;
35 @ISA = qw(Exporter);
36 @EXPORT = qw(
37 get_report_types get_report_areas get_columns build_query get_criteria
38 save_report get_saved_reports execute_query get_saved_report create_compound run_compound
39 get_column_type get_distinct_values save_dictionary get_from_dictionary
40 delete_definition delete_report format_results get_sql
44 our %table_areas;
45 $table_areas{'1'} =
46 [ 'borrowers', 'statistics','items', 'biblioitems' ]; # circulation
47 $table_areas{'2'} = [ 'items', 'biblioitems', 'biblio' ]; # catalogue
48 $table_areas{'3'} = [ 'borrowers' ]; # patrons
49 $table_areas{'4'} = ['aqorders', 'biblio', 'items']; # acquisitions
50 $table_areas{'5'} = [ 'borrowers', 'accountlines' ]; # accounts
51 our %keys;
52 $keys{'1'} = [
53 'statistics.borrowernumber=borrowers.borrowernumber',
54 'items.itemnumber = statistics.itemnumber',
55 'biblioitems.biblioitemnumber = items.biblioitemnumber'
57 $keys{'2'} = [
58 'items.biblioitemnumber=biblioitems.biblioitemnumber',
59 'biblioitems.biblionumber=biblio.biblionumber'
61 $keys{'3'} = [ ];
62 $keys{'4'} = [
63 'aqorders.biblionumber=biblio.biblionumber',
64 'biblio.biblionumber=items.biblionumber'
66 $keys{'5'} = ['borrowers.borrowernumber=accountlines.borrowernumber'];
68 # have to do someting here to know if its dropdown, free text, date etc
70 our %criteria;
71 $criteria{'1'} = [
72 'statistics.type', 'borrowers.categorycode',
73 'statistics.branch',
74 'biblioitems.publicationyear|date',
75 'items.dateaccessioned|date'
77 $criteria{'2'} =
78 [ 'items.holdingbranch', 'items.homebranch' ,'items.itemlost', 'items.location', 'items.ccode'];
79 $criteria{'3'} = ['borrowers.branchcode'];
80 $criteria{'4'} = ['aqorders.datereceived|date'];
81 $criteria{'5'} = ['borrowers.branchcode'];
83 if (C4::Context->preference('item-level_itypes')) {
84 unshift @{ $criteria{'1'} }, 'items.itype';
85 unshift @{ $criteria{'2'} }, 'items.itype';
86 } else {
87 unshift @{ $criteria{'1'} }, 'biblioitems.itemtype';
88 unshift @{ $criteria{'2'} }, 'biblioitems.itemtype';
91 =head1 NAME
93 C4::Reports - Module for generating reports
95 =head1 SYNOPSIS
97 use C4::Reports;
99 =head1 DESCRIPTION
102 =head1 METHODS
104 =over 2
106 =cut
108 =item get_report_types()
110 This will return a list of all the available report types
112 =cut
114 sub get_report_types {
115 my $dbh = C4::Context->dbh();
117 # FIXME these should be in the database perhaps
118 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
119 my @reports2;
120 for ( my $i = 0 ; $i < 3 ; $i++ ) {
121 my %hashrep;
122 $hashrep{id} = $i + 1;
123 $hashrep{name} = $reports[$i];
124 push @reports2, \%hashrep;
126 return ( \@reports2 );
130 =item get_report_areas()
132 This will return a list of all the available report areas
134 =cut
136 sub get_report_areas {
137 my $dbh = C4::Context->dbh();
139 # FIXME these should be in the database
140 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
141 my @reports2;
142 for ( my $i = 0 ; $i < 5 ; $i++ ) {
143 my %hashrep;
144 $hashrep{id} = $i + 1;
145 $hashrep{name} = $reports[$i];
146 push @reports2, \%hashrep;
148 return ( \@reports2 );
152 =item get_all_tables()
154 This will return a list of all tables in the database
156 =cut
158 sub get_all_tables {
159 my $dbh = C4::Context->dbh();
160 my $query = "SHOW TABLES";
161 my $sth = $dbh->prepare($query);
162 $sth->execute();
163 my @tables;
164 while ( my $data = $sth->fetchrow_arrayref() ) {
165 push @tables, $data->[0];
167 $sth->finish();
168 return ( \@tables );
172 =item get_columns($area)
174 This will return a list of all columns for a report area
176 =cut
178 sub get_columns {
180 # this calls the internal fucntion _get_columns
181 my ($area,$cgi) = @_;
182 my $tables = $table_areas{$area};
183 my @allcolumns;
184 my $first = 1;
185 foreach my $table (@$tables) {
186 my @columns = _get_columns($table,$cgi, $first);
187 $first = 0;
188 push @allcolumns, @columns;
190 return ( \@allcolumns );
193 sub _get_columns {
194 my ($tablename,$cgi, $first) = @_;
195 my $dbh = C4::Context->dbh();
196 my $sth = $dbh->prepare("show columns from $tablename");
197 $sth->execute();
198 my @columns;
199 my $column_defs = _get_column_defs($cgi);
200 my %tablehash;
201 $tablehash{'table'}=$tablename;
202 $tablehash{'__first__'} = $first;
203 push @columns, \%tablehash;
204 while ( my $data = $sth->fetchrow_arrayref() ) {
205 my %temphash;
206 $temphash{'name'} = "$tablename.$data->[0]";
207 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
208 push @columns, \%temphash;
210 $sth->finish();
211 return (@columns);
214 =item build_query($columns,$criteria,$orderby,$area)
216 This will build the sql needed to return the results asked for,
217 $columns is expected to be of the format tablename.columnname.
218 This is what get_columns returns.
220 =cut
222 sub build_query {
223 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
224 ### $orderby
225 my $keys = $keys{$area};
226 my $tables = $table_areas{$area};
228 my $sql =
229 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
230 return ($sql);
233 sub _build_query {
234 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
235 ### $orderby
236 # $keys is an array of joining constraints
237 my $dbh = C4::Context->dbh();
238 my $joinedtables = join( ',', @$tables );
239 my $joinedcolumns = join( ',', @$columns );
240 my $joinedkeys = join( ' AND ', @$keys );
241 my $query =
242 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
243 for (my $i=1;$i<@$tables;$i++){
244 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
247 if ($criteria) {
248 $criteria =~ s/AND/WHERE/;
249 $query .= " $criteria";
251 if ($definition){
252 my @definitions = split(',',$definition);
253 my $deftext;
254 foreach my $def (@definitions){
255 my $defin=get_from_dictionary('',$def);
256 $deftext .=" ".$defin->[0]->{'saved_sql'};
258 if ($query =~ /WHERE/i){
259 $query .= $deftext;
261 else {
262 $deftext =~ s/AND/WHERE/;
263 $query .= $deftext;
266 if ($totals) {
267 my $groupby;
268 my @totcolumns = split( ',', $totals );
269 foreach my $total (@totcolumns) {
270 if ( $total =~ /\((.*)\)/ ) {
271 if ( $groupby eq '' ) {
272 $groupby = " GROUP BY $1";
274 else {
275 $groupby .= ",$1";
279 $query .= $groupby;
281 if ($orderby) {
282 $query .= $orderby;
284 return ($query);
287 =item get_criteria($area,$cgi);
289 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
291 =cut
293 sub get_criteria {
294 my ($area,$cgi) = @_;
295 my $dbh = C4::Context->dbh();
296 my $crit = $criteria{$area};
297 my $column_defs = _get_column_defs($cgi);
298 my @criteria_array;
299 foreach my $localcrit (@$crit) {
300 my ( $value, $type ) = split( /\|/, $localcrit );
301 my ( $table, $column ) = split( /\./, $value );
302 if ( $type eq 'date' ) {
303 my %temp;
304 $temp{'name'} = $value;
305 $temp{'date'} = 1;
306 $temp{'description'} = $column_defs->{$value};
307 push @criteria_array, \%temp;
309 else {
311 my $query =
312 "SELECT distinct($column) as availablevalues FROM $table";
313 my $sth = $dbh->prepare($query);
314 $sth->execute();
315 my @values;
316 while ( my $row = $sth->fetchrow_hashref() ) {
317 push @values, $row;
318 ### $row;
320 $sth->finish();
321 my %temp;
322 $temp{'name'} = $value;
323 $temp{'description'} = $column_defs->{$value};
324 $temp{'values'} = \@values;
325 push @criteria_array, \%temp;
328 return ( \@criteria_array );
331 sub execute_query {
332 my ( $sql, $type, $format, $id ) = @_;
333 my $dbh = C4::Context->dbh();
335 # take this line out when in production
336 if ($format eq 'csv' or $format eq 'tab'){
338 else {
339 $sql .= " LIMIT 20";
341 my $sth = $dbh->prepare($sql);
342 $sth->execute();
343 my $colnames=$sth->{'NAME'};
344 my @results;
345 my $row;
346 my %temphash;
347 $row = join ('</th><th>',@$colnames);
348 $row = "<tr><th>$row</th></tr>";
349 $temphash{'row'} = $row;
350 push @results, \%temphash;
351 my $string;
352 my @xmlarray;
353 while ( my @data = $sth->fetchrow_array() ) {
355 # tabular
356 my %temphash;
357 my $row = join( '</td><td>', @data );
358 $row = "<tr><td>$row</td></tr>";
359 $temphash{'row'} = $row;
360 if ( $format eq 'text' ) {
361 $string .= "\n" . $row;
363 if ($format eq 'tab' ){
364 $row = join("\t",@data);
365 $string .="\n" . $row;
367 if ($format eq 'csv' ){
368 $row = join(",",@data);
369 $string .="\n" . $row;
371 if ($format eq 'url'){
372 my $temphash;
373 @$temphash{@$colnames}=@data;
374 push @xmlarray,$temphash;
376 push @results, \%temphash;
379 $sth->finish();
380 if ( $format eq 'text' || $format eq 'tab' || $format eq 'csv' ) {
381 return $string;
383 elsif ($format eq 'url') {
384 my $url = "/cgi-bin/koha/reports/guided_reports.pl?phase=retrieve%20results&id=$id";
385 my $dump = new XML::Dumper;
386 my $xml = $dump->pl2xml( \@xmlarray );
387 store_results($id,$xml);
388 return $url;
390 else {
391 return ( \@results );
395 =item save_report($sql,$name,$type,$notes)
397 Given some sql and a name this will saved it so that it can resued
399 =cut
401 sub save_report {
402 my ( $sql, $name, $type, $notes ) = @_;
403 my $dbh = C4::Context->dbh();
404 my $query =
405 "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,type,notes) VALUES (?,now(),now(),?,?,?,?)";
406 my $sth = $dbh->prepare($query);
407 $sth->execute( 0, $sql, $name, $type, $notes );
408 $sth->finish();
412 sub store_results {
413 my ($id,$xml)=@_;
414 my $dbh = C4::Context->dbh();
415 my $query = "SELECT * FROM saved_reports WHERE report_id=?";
416 my $sth = $dbh->prepare($query);
417 $sth->execute($id);
418 if (my $data=$sth->fetchrow_hashref()){
419 my $query2 = "UPDATE saved_reports SET report=?,date_run=now() WHERE report_id=?";
420 my $sth2 = $dbh->prepare($query2);
421 $sth2->execute($xml,$id);
422 $sth2->finish();
424 else {
425 my $query2 = "INSERT INTO saved_reports (report_id,report,date_run) VALUES (?,?,now())";
426 my $sth2 = $dbh->prepare($query2);
427 $sth2->execute($id,$xml);
428 $sth2->finish();
430 $sth->finish();
433 sub format_results {
434 my ($id) = @_;
435 my $dbh = C4::Context->dbh();
436 my $query = "SELECT * FROM saved_reports WHERE report_id = ?";
437 my $sth = $dbh->prepare($query);
438 $sth->execute($id);
439 my $data = $sth->fetchrow_hashref();
440 my $dump = new XML::Dumper;
441 my $perl = $dump->xml2pl( $data->{'report'} );
442 foreach my $row (@$perl) {
443 my $htmlrow="<tr>";
444 foreach my $key (keys %$row){
445 $htmlrow .= "<td>$row->{$key}</td>";
447 $htmlrow .= "</tr>";
448 $row->{'row'} = $htmlrow;
450 $sth->finish;
451 $query = "SELECT * FROM saved_sql WHERE id = ?";
452 $sth = $dbh->prepare($query);
453 $sth->execute($id);
454 $data = $sth->fetchrow_hashref();
455 $sth->finish();
456 return ($perl,$data->{'report_name'},$data->{'notes'});
459 sub delete_report {
460 my ( $id ) = @_;
461 my $dbh = C4::Context->dbh();
462 my $query = "DELETE FROM saved_sql WHERE id = ?";
463 my $sth = $dbh->prepare($query);
464 $sth->execute($id);
465 $sth->finish();
468 sub get_saved_reports {
469 my $dbh = C4::Context->dbh();
470 my $query = "SELECT *,saved_sql.id AS id FROM saved_sql
471 LEFT JOIN saved_reports ON saved_reports.report_id = saved_sql.id
472 ORDER by date_created";
473 my $sth = $dbh->prepare($query);
474 $sth->execute();
475 my @reports;
476 while ( my $data = $sth->fetchrow_hashref() ) {
477 push @reports, $data;
479 $sth->finish();
480 return ( \@reports );
483 sub get_saved_report {
484 my ($id) = @_;
485 my $dbh = C4::Context->dbh();
486 my $query = " SELECT * FROM saved_sql WHERE id = ?";
487 my $sth = $dbh->prepare($query);
488 $sth->execute($id);
489 my $data = $sth->fetchrow_hashref();
490 $sth->finish();
491 return ( $data->{'savedsql'}, $data->{'type'}, $data->{'report_name'}, $data->{'notes'} );
494 =item create_compound($masterID,$subreportID)
496 This will take 2 reports and create a compound report using both of them
498 =cut
500 sub create_compound {
501 my ($masterID,$subreportID) = @_;
502 my $dbh = C4::Context->dbh();
503 # get the reports
504 my ($mastersql,$mastertype) = get_saved_report($masterID);
505 my ($subsql,$subtype) = get_saved_report($subreportID);
507 # now we have to do some checking to see how these two will fit together
508 # or if they will
509 my ($mastertables,$subtables);
510 if ($mastersql =~ / from (.*) where /i){
511 $mastertables = $1;
513 if ($subsql =~ / from (.*) where /i){
514 $subtables = $1;
516 return ($mastertables,$subtables);
519 =item get_column_type($column)
521 This takes a column name of the format table.column and will return what type it is
522 (free text, set values, date)
524 =cut
526 sub get_column_type {
527 my ($tablecolumn) = @_;
528 my ($table,$column) = split(/\./,$tablecolumn);
529 my $dbh = C4::Context->dbh();
530 my $catalog;
531 my $schema;
533 # mysql doesnt support a column selection, set column to %
534 my $tempcolumn='%';
535 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
536 while (my $info = $sth->fetchrow_hashref()){
537 if ($info->{'COLUMN_NAME'} eq $column){
538 #column we want
539 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
540 $info->{'TYPE_NAME'} = 'distinct';
542 return $info->{'TYPE_NAME'};
545 $sth->finish();
548 =item get_distinct_values($column)
550 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
551 with the distinct values of the column
553 =cut
555 sub get_distinct_values {
556 my ($tablecolumn) = @_;
557 my ($table,$column) = split(/\./,$tablecolumn);
558 my $dbh = C4::Context->dbh();
559 my $query =
560 "SELECT distinct($column) as availablevalues FROM $table";
561 my $sth = $dbh->prepare($query);
562 $sth->execute();
563 my @values;
564 while ( my $row = $sth->fetchrow_hashref() ) {
565 push @values, $row;
567 $sth->finish();
568 return \@values;
571 sub save_dictionary {
572 my ($name,$description,$sql,$area) = @_;
573 my $dbh = C4::Context->dbh();
574 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,area,date_created,date_modified)
575 VALUES (?,?,?,?,now(),now())";
576 my $sth = $dbh->prepare($query);
577 $sth->execute($name,$description,$sql,$area) || return 0;
578 $sth->finish();
579 return 1;
582 sub get_from_dictionary {
583 my ($area,$id) = @_;
584 my $dbh = C4::Context->dbh();
585 my $query = "SELECT * FROM reports_dictionary";
586 if ($area){
587 $query.= " WHERE area = ?";
589 elsif ($id){
590 $query.= " WHERE id = ?"
592 my $sth = $dbh->prepare($query);
593 if ($id){
594 $sth->execute($id);
596 elsif ($area) {
597 $sth->execute($area);
599 else {
600 $sth->execute();
602 my @loop;
603 my @reports = ( 'Circulation', 'Catalog', 'Patrons', 'Acquisitions', 'Accounts');
604 while (my $data = $sth->fetchrow_hashref()){
605 $data->{'areaname'}=$reports[$data->{'area'}-1];
606 push @loop,$data;
609 $sth->finish();
610 return (\@loop);
613 sub delete_definition {
614 my ($id) = @_;
615 my $dbh = C4::Context->dbh();
616 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
617 my $sth = $dbh->prepare($query);
618 $sth->execute($id);
619 $sth->finish();
622 sub get_sql {
623 my ($id) = @_;
624 my $dbh = C4::Context->dbh();
625 my $query = "SELECT * FROM saved_sql WHERE id = ?";
626 my $sth = $dbh->prepare($query);
627 $sth->execute($id);
628 my $data=$sth->fetchrow_hashref();
629 $sth->finish();
630 return $data->{'savedsql'};
633 sub _get_column_defs {
634 my ($cgi) = @_;
635 my %columns;
636 my $columns_def_file = "columns.def";
637 my $htdocs = C4::Context->config('intrahtdocs');
638 my $section='intranet';
639 my ($theme, $lang) = themelanguage($htdocs, $columns_def_file, $section,$cgi);
641 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
642 open (COLUMNS,$full_path_to_columns_def_file);
643 while (my $input = <COLUMNS>){
644 my @row =split(/\t/,$input);
645 $columns{$row[0]}=$row[1];
648 close COLUMNS;
649 return \%columns;
652 __END__
654 =head1 AUTHOR
656 Chris Cormack <crc@liblime.com>
658 =cut