Bug 23624: (QA follow-up) Optimize even more
[koha.git] / C4 / Reports / Guided.pm
blob58d78002e0014b0c597c70e1c8d03840c063e8ac
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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Modern::Perl;
21 use CGI qw ( -utf8 );
22 use Carp;
23 use JSON qw( from_json );
25 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
26 use C4::Context;
27 use C4::Templates qw/themelanguage/;
28 use C4::Koha;
29 use Koha::DateUtils;
30 use Koha::Patrons;
31 use Koha::Reports;
32 use C4::Output;
33 use C4::Debug;
34 use C4::Log;
35 use Koha::Notice::Templates;
36 use C4::Letters;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Categories;
40 use Koha::SharedContent;
42 BEGIN {
43 require Exporter;
44 @ISA = qw(Exporter);
45 @EXPORT = qw(
46 get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
47 save_report get_saved_reports execute_query
48 get_column_type get_distinct_values save_dictionary get_from_dictionary
49 delete_definition delete_report format_results get_sql
50 nb_rows update_sql
51 GetReservedAuthorisedValues
52 GetParametersFromSQL
53 IsAuthorisedValueValid
54 ValidateSQLParameters
55 nb_rows update_sql
59 =head1 NAME
61 C4::Reports::Guided - Module for generating guided reports
63 =head1 SYNOPSIS
65 use C4::Reports::Guided;
67 =head1 DESCRIPTION
69 =cut
71 =head1 METHODS
73 =head2 get_report_areas
75 This will return a list of all the available report areas
77 =cut
79 sub get_area_name_sql_snippet {
80 my @REPORT_AREA = (
81 [CIRC => "Circulation"],
82 [CAT => "Catalogue"],
83 [PAT => "Patrons"],
84 [ACQ => "Acquisition"],
85 [ACC => "Accounts"],
86 [SER => "Serials"],
89 return "CASE report_area " .
90 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
91 " END AS areaname";
94 sub get_report_areas {
96 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
98 return $report_areas;
101 sub get_table_areas {
102 return (
103 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
104 CAT => [ 'items', 'biblioitems', 'biblio' ],
105 PAT => ['borrowers'],
106 ACQ => [ 'aqorders', 'biblio', 'items' ],
107 ACC => [ 'borrowers', 'accountlines' ],
108 SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
112 =head2 get_report_types
114 This will return a list of all the available report types
116 =cut
118 sub get_report_types {
119 my $dbh = C4::Context->dbh();
121 # FIXME these should be in the database perhaps
122 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
123 my @reports2;
124 for ( my $i = 0 ; $i < 3 ; $i++ ) {
125 my %hashrep;
126 $hashrep{id} = $i + 1;
127 $hashrep{name} = $reports[$i];
128 push @reports2, \%hashrep;
130 return ( \@reports2 );
134 =head2 get_report_groups
136 This will return a list of all the available report areas with groups
138 =cut
140 sub get_report_groups {
141 my $dbh = C4::Context->dbh();
143 my $groups = GetAuthorisedValues('REPORT_GROUP');
144 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
146 my %groups_with_subgroups = map { $_->{authorised_value} => {
147 name => $_->{lib},
148 groups => {}
149 } } @$groups;
150 foreach (@$subgroups) {
151 my $sg = $_->{authorised_value};
152 my $g = $_->{lib_opac}
153 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
154 next;
155 my $g_sg = $groups_with_subgroups{$g}
156 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
157 next;
158 $g_sg->{subgroups}{$sg} = $_->{lib};
160 return \%groups_with_subgroups
163 =head2 get_all_tables
165 This will return a list of all tables in the database
167 =cut
169 sub get_all_tables {
170 my $dbh = C4::Context->dbh();
171 my $query = "SHOW TABLES";
172 my $sth = $dbh->prepare($query);
173 $sth->execute();
174 my @tables;
175 while ( my $data = $sth->fetchrow_arrayref() ) {
176 push @tables, $data->[0];
178 $sth->finish();
179 return ( \@tables );
183 =head2 get_columns($area)
185 This will return a list of all columns for a report area
187 =cut
189 sub get_columns {
191 # this calls the internal function _get_columns
192 my ( $area, $cgi ) = @_;
193 my %table_areas = get_table_areas;
194 my $tables = $table_areas{$area}
195 or die qq{Unsuported report area "$area"};
197 my @allcolumns;
198 my $first = 1;
199 foreach my $table (@$tables) {
200 my @columns = _get_columns($table,$cgi, $first);
201 $first = 0;
202 push @allcolumns, @columns;
204 return ( \@allcolumns );
207 sub _get_columns {
208 my ($tablename,$cgi, $first) = @_;
209 my $dbh = C4::Context->dbh();
210 my $sth = $dbh->prepare("show columns from $tablename");
211 $sth->execute();
212 my @columns;
213 my $column_defs = _get_column_defs($cgi);
214 my %tablehash;
215 $tablehash{'table'}=$tablename;
216 $tablehash{'__first__'} = $first;
217 push @columns, \%tablehash;
218 while ( my $data = $sth->fetchrow_arrayref() ) {
219 my %temphash;
220 $temphash{'name'} = "$tablename.$data->[0]";
221 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
222 push @columns, \%temphash;
224 $sth->finish();
225 return (@columns);
228 =head2 build_query($columns,$criteria,$orderby,$area)
230 This will build the sql needed to return the results asked for,
231 $columns is expected to be of the format tablename.columnname.
232 This is what get_columns returns.
234 =cut
236 sub build_query {
237 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
239 my %keys = (
240 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
241 'items.itemnumber = statistics.itemnumber',
242 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
243 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
244 'biblioitems.biblionumber=biblio.biblionumber' ],
245 PAT => [],
246 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
247 'biblio.biblionumber=items.biblionumber' ],
248 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
249 SER => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'],
253 ### $orderby
254 my $keys = $keys{$area};
255 my %table_areas = get_table_areas;
256 my $tables = $table_areas{$area};
258 my $sql =
259 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
260 return ($sql);
263 sub _build_query {
264 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
265 ### $orderby
266 # $keys is an array of joining constraints
267 my $dbh = C4::Context->dbh();
268 my $joinedtables = join( ',', @$tables );
269 my $joinedcolumns = join( ',', @$columns );
270 my $query =
271 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
272 for (my $i=1;$i<@$tables;$i++){
273 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
276 if ($criteria) {
277 $criteria =~ s/AND/WHERE/;
278 $query .= " $criteria";
280 if ($definition){
281 my @definitions = split(',',$definition);
282 my $deftext;
283 foreach my $def (@definitions){
284 my $defin=get_from_dictionary('',$def);
285 $deftext .=" ".$defin->[0]->{'saved_sql'};
287 if ($query =~ /WHERE/i){
288 $query .= $deftext;
290 else {
291 $deftext =~ s/AND/WHERE/;
292 $query .= $deftext;
295 if ($totals) {
296 my $groupby;
297 my @totcolumns = split( ',', $totals );
298 foreach my $total (@totcolumns) {
299 if ( $total =~ /\((.*)\)/ ) {
300 if ( $groupby eq '' ) {
301 $groupby = " GROUP BY $1";
303 else {
304 $groupby .= ",$1";
308 $query .= $groupby;
310 if ($orderby) {
311 $query .= $orderby;
313 return ($query);
316 =head2 get_criteria($area,$cgi);
318 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
320 =cut
322 sub get_criteria {
323 my ($area,$cgi) = @_;
324 my $dbh = C4::Context->dbh();
326 # have to do someting here to know if its dropdown, free text, date etc
327 my %criteria = (
328 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
329 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
330 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
331 'items.barcode|textrange', 'biblio.frameworkcode',
332 'items.holdingbranch', 'items.homebranch',
333 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
334 'items.onloan|daterange', 'items.ccode',
335 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
336 'items.location' ],
337 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
338 ACQ => ['aqorders.datereceived|date'],
339 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
340 SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
343 # Adds itemtypes to criteria, according to the syspref
344 if ( C4::Context->preference('item-level_itypes') ) {
345 unshift @{ $criteria{'CIRC'} }, 'items.itype';
346 unshift @{ $criteria{'CAT'} }, 'items.itype';
347 } else {
348 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
349 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
353 my $crit = $criteria{$area};
354 my $column_defs = _get_column_defs($cgi);
355 my @criteria_array;
356 foreach my $localcrit (@$crit) {
357 my ( $value, $type ) = split( /\|/, $localcrit );
358 my ( $table, $column ) = split( /\./, $value );
359 if ($type eq 'textrange') {
360 my %temp;
361 $temp{'name'} = $value;
362 $temp{'from'} = "from_" . $value;
363 $temp{'to'} = "to_" . $value;
364 $temp{'textrange'} = 1;
365 $temp{'description'} = $column_defs->{$value};
366 push @criteria_array, \%temp;
368 elsif ($type eq 'date') {
369 my %temp;
370 $temp{'name'} = $value;
371 $temp{'date'} = 1;
372 $temp{'description'} = $column_defs->{$value};
373 push @criteria_array, \%temp;
375 elsif ($type eq 'daterange') {
376 my %temp;
377 $temp{'name'} = $value;
378 $temp{'from'} = "from_" . $value;
379 $temp{'to'} = "to_" . $value;
380 $temp{'daterange'} = 1;
381 $temp{'description'} = $column_defs->{$value};
382 push @criteria_array, \%temp;
384 else {
385 my $query =
386 "SELECT distinct($column) as availablevalues FROM $table";
387 my $sth = $dbh->prepare($query);
388 $sth->execute();
389 my @values;
390 # push the runtime choosing option
391 my $list;
392 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
393 $list='categorycode' if $column eq 'categorycode';
394 $list='itemtypes' if $column eq 'itype';
395 $list='ccode' if $column eq 'ccode';
396 # TODO : improve to let the librarian choose the description at runtime
397 push @values, {
398 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
399 display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
401 while ( my $row = $sth->fetchrow_hashref() ) {
402 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
403 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
404 push @values, $row;
406 $sth->finish();
408 my %temp;
409 $temp{'name'} = $value;
410 $temp{'description'} = $column_defs->{$value};
411 $temp{'values'} = \@values;
413 push @criteria_array, \%temp;
416 return ( \@criteria_array );
419 sub nb_rows {
420 my $sql = shift or return;
422 my $derived_name = 'xxx';
423 # make sure the derived table name is not already used
424 while ( $sql =~ m/$derived_name/ ) {
425 $derived_name .= 'x';
427 my $sth = C4::Context->dbh->prepare(qq{
428 SELECT COUNT(*) FROM
429 ( $sql ) $derived_name
431 $sth->execute();
432 my $n = $sth->fetch->[0];
434 return $n;
437 =head2 execute_query
439 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
442 This function returns a DBI statement handler from which the caller can
443 fetch the results of the SQL passed via C<$sql>.
445 If passed any query other than a SELECT, or if there is a DB error,
446 C<$errors> is returned, and is a hashref containing the error after this
447 manner:
449 C<$error->{'sqlerr'}> contains the offending SQL keyword.
450 C<$error->{'queryerr'}> contains the native db engine error returned
451 for the query.
453 C<$offset>, and C<$limit> are required parameters.
455 C<\@sql_params> is an optional list of parameter values to paste in.
456 The caller is responsible for making sure that C<$sql> has placeholders
457 and that the number placeholders matches the number of parameters.
459 =cut
461 # returns $sql, $offset, $limit
462 # $sql returned will be transformed to:
463 # ~ remove any LIMIT clause
464 # ~ repace SELECT clause w/ SELECT count(*)
466 sub select_2_select_count {
467 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
468 my ($sql) = strip_limit(shift) or return;
469 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
470 return $sql;
473 # This removes the LIMIT from the query so that a custom one can be specified.
474 # Usage:
475 # ($new_sql, $offset, $limit) = strip_limit($sql);
477 # Where:
478 # $sql is the query to modify
479 # $new_sql is the resulting query
480 # $offset is the offset value, if the LIMIT was the two-argument form,
481 # 0 if it wasn't otherwise given.
482 # $limit is the limit value
484 # Notes:
485 # * This makes an effort to not break subqueries that have their own
486 # LIMIT specified. It does that by only removing a LIMIT if it comes after
487 # a WHERE clause (which isn't perfect, but at least should make more cases
488 # work - subqueries with a limit in the WHERE will still break.)
489 # * If your query doesn't have a WHERE clause then all LIMITs will be
490 # removed. This may break some subqueries, but is hopefully rare enough
491 # to not be a big issue.
492 sub strip_limit {
493 my ($sql) = @_;
495 return unless $sql;
496 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
498 # Two options: if there's no WHERE clause in the SQL, we simply capture
499 # any LIMIT that's there. If there is a WHERE, we make sure that we only
500 # capture a LIMIT after the last one. This prevents stomping on subqueries.
501 if ($sql !~ /\bWHERE\b/i) {
502 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
503 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
504 } else {
505 my $res = $sql;
506 $res =~ m/.*\bWHERE\b/gsi;
507 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
508 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
512 sub execute_query {
514 my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
516 $sql_params = [] unless defined $sql_params;
518 # check parameters
519 unless ($sql) {
520 carp "execute_query() called without SQL argument";
521 return;
523 $offset = 0 unless $offset;
524 $limit = 999999 unless $limit;
525 $debug and print STDERR "execute_query($sql, $offset, $limit)\n";
526 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
527 return (undef, { sqlerr => $1} );
528 } elsif ($sql !~ /^\s*SELECT\b\s*/i) {
529 return (undef, { queryerr => 'Missing SELECT'} );
532 my ($useroffset, $userlimit);
534 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
535 ($sql, $useroffset, $userlimit) = strip_limit($sql);
536 $debug and warn sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
537 $useroffset,
538 (defined($userlimit ) ? $userlimit : 'UNDEF');
539 $offset += $useroffset;
540 if (defined($userlimit)) {
541 if ($offset + $limit > $userlimit ) {
542 $limit = $userlimit - $offset;
543 } elsif ( ! $offset && $limit < $userlimit ) {
544 $limit = $userlimit;
547 $sql .= " LIMIT ?, ?";
549 my $dbh = C4::Context->dbh;
551 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
553 my $sth = $dbh->prepare($sql);
554 $sth->execute(@$sql_params, $offset, $limit);
556 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
557 return ( $sth );
560 =head2 save_report($sql,$name,$type,$notes)
562 Given some sql and a name this will saved it so that it can reused
563 Returns id of the newly created report
565 =cut
567 sub save_report {
568 my ($fields) = @_;
569 my $borrowernumber = $fields->{borrowernumber};
570 my $sql = $fields->{sql};
571 my $name = $fields->{name};
572 my $type = $fields->{type};
573 my $notes = $fields->{notes};
574 my $area = $fields->{area};
575 my $group = $fields->{group};
576 my $subgroup = $fields->{subgroup};
577 my $cache_expiry = $fields->{cache_expiry} || 300;
578 my $public = $fields->{public};
580 my $dbh = C4::Context->dbh();
581 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
582 my $query = "INSERT INTO saved_sql (borrowernumber,date_created,last_modified,savedsql,report_name,report_area,report_group,report_subgroup,type,notes,cache_expiry,public) VALUES (?,now(),now(),?,?,?,?,?,?,?,?,?)";
583 $dbh->do($query, undef, $borrowernumber, $sql, $name, $area, $group, $subgroup, $type, $notes, $cache_expiry, $public);
585 my $id = $dbh->selectrow_array("SELECT max(id) FROM saved_sql WHERE borrowernumber=? AND report_name=?", undef,
586 $borrowernumber, $name);
587 return $id;
590 sub update_sql {
591 my $id = shift || croak "No Id given";
592 my $fields = shift;
593 my $sql = $fields->{sql};
594 my $name = $fields->{name};
595 my $notes = $fields->{notes};
596 my $group = $fields->{group};
597 my $subgroup = $fields->{subgroup};
598 my $cache_expiry = $fields->{cache_expiry};
599 my $public = $fields->{public};
601 if( $cache_expiry >= 2592000 ){
602 die "Please specify a cache expiry less than 30 days\n";
605 my $dbh = C4::Context->dbh();
606 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
607 my $query = "UPDATE saved_sql SET savedsql = ?, last_modified = now(), report_name = ?, report_group = ?, report_subgroup = ?, notes = ?, cache_expiry = ?, public = ? WHERE id = ? ";
608 $dbh->do($query, undef, $sql, $name, $group, $subgroup, $notes, $cache_expiry, $public, $id );
611 sub store_results {
612 my ( $id, $json ) = @_;
613 my $dbh = C4::Context->dbh();
614 $dbh->do(q|
615 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
616 |, undef, $id, $json );
619 sub format_results {
620 my ( $id ) = @_;
621 my $dbh = C4::Context->dbh();
622 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
623 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
624 FROM saved_sql ss
625 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
626 WHERE sr.id = ?
627 |, undef, $id);
628 return {
629 report_name => $report_name,
630 notes => $notes,
631 results => from_json( $json ),
632 date_run => $date_run,
636 sub delete_report {
637 my (@ids) = @_;
638 return unless @ids;
639 foreach my $id (@ids) {
640 my $data = Koha::Reports->find($id);
641 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
643 my $dbh = C4::Context->dbh;
644 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
645 my $sth = $dbh->prepare($query);
646 return $sth->execute(@ids);
649 sub get_saved_reports_base_query {
650 my $area_name_sql_snippet = get_area_name_sql_snippet;
651 return <<EOQ;
652 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
653 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
654 FROM saved_sql s
655 LEFT JOIN saved_reports r ON r.report_id = s.id
656 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
657 LEFT OUTER JOIN authorised_values av_sg ON (av_sg.category = 'REPORT_SUBGROUP' AND av_sg.lib_opac = s.report_group AND av_sg.authorised_value = s.report_subgroup)
658 LEFT OUTER JOIN borrowers b USING (borrowernumber)
662 sub get_saved_reports {
663 # $filter is either { date => $d, author => $a, keyword => $kw, }
664 # or $keyword. Optional.
665 my ($filter) = @_;
666 $filter = { keyword => $filter } if $filter && !ref( $filter );
667 my ($group, $subgroup) = @_;
669 my $dbh = C4::Context->dbh();
670 my $query = get_saved_reports_base_query;
671 my (@cond,@args);
672 if ($filter) {
673 if (my $date = $filter->{date}) {
674 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
675 push @cond, "DATE(last_modified) = ? OR
676 DATE(last_run) = ?";
677 push @args, $date, $date, $date;
679 if (my $author = $filter->{author}) {
680 $author = "%$author%";
681 push @cond, "surname LIKE ? OR
682 firstname LIKE ?";
683 push @args, $author, $author;
685 if (my $keyword = $filter->{keyword}) {
686 push @cond, q|
687 report LIKE ?
688 OR report_name LIKE ?
689 OR notes LIKE ?
690 OR savedsql LIKE ?
691 OR s.id = ?
693 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
695 if ($filter->{group}) {
696 push @cond, "report_group = ?";
697 push @args, $filter->{group};
699 if ($filter->{subgroup}) {
700 push @cond, "report_subgroup = ?";
701 push @args, $filter->{subgroup};
704 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
705 $query .= " GROUP BY s.id, s.borrowernumber, s.date_created, s.last_modified, s.savedsql, s.last_run, s.report_name, s.type, s.notes, s.cache_expiry, s.public, s.report_area, s.report_group, s.report_subgroup, s.mana_id, av_g.lib, av_sg.lib, b.firstname, b.surname";
706 $query .= " ORDER by date_created";
708 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
710 return $result;
713 =head2 get_column_type($column)
715 This takes a column name of the format table.column and will return what type it is
716 (free text, set values, date)
718 =cut
720 sub get_column_type {
721 my ($tablecolumn) = @_;
722 my ($table,$column) = split(/\./,$tablecolumn);
723 my $dbh = C4::Context->dbh();
724 my $catalog;
725 my $schema;
727 # mysql doesn't support a column selection, set column to %
728 my $tempcolumn='%';
729 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
730 while (my $info = $sth->fetchrow_hashref()){
731 if ($info->{'COLUMN_NAME'} eq $column){
732 #column we want
733 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
734 $info->{'TYPE_NAME'} = 'distinct';
736 return $info->{'TYPE_NAME'};
741 =head2 get_distinct_values($column)
743 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
744 with the distinct values of the column
746 =cut
748 sub get_distinct_values {
749 my ($tablecolumn) = @_;
750 my ($table,$column) = split(/\./,$tablecolumn);
751 my $dbh = C4::Context->dbh();
752 my $query =
753 "SELECT distinct($column) as availablevalues FROM $table";
754 my $sth = $dbh->prepare($query);
755 $sth->execute();
756 return $sth->fetchall_arrayref({});
759 sub save_dictionary {
760 my ( $name, $description, $sql, $area ) = @_;
761 my $dbh = C4::Context->dbh();
762 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
763 VALUES (?,?,?,?,now(),now())";
764 my $sth = $dbh->prepare($query);
765 $sth->execute($name,$description,$sql,$area) || return 0;
766 return 1;
769 sub get_from_dictionary {
770 my ( $area, $id ) = @_;
771 my $dbh = C4::Context->dbh();
772 my $area_name_sql_snippet = get_area_name_sql_snippet;
773 my $query = <<EOQ;
774 SELECT d.*, $area_name_sql_snippet
775 FROM reports_dictionary d
778 if ($area) {
779 $query .= " WHERE report_area = ?";
780 } elsif ($id) {
781 $query .= " WHERE id = ?";
783 my $sth = $dbh->prepare($query);
784 if ($id) {
785 $sth->execute($id);
786 } elsif ($area) {
787 $sth->execute($area);
788 } else {
789 $sth->execute();
791 my @loop;
792 while ( my $data = $sth->fetchrow_hashref() ) {
793 push @loop, $data;
795 return ( \@loop );
798 sub delete_definition {
799 my ($id) = @_ or return;
800 my $dbh = C4::Context->dbh();
801 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
802 my $sth = $dbh->prepare($query);
803 $sth->execute($id);
806 =head2 get_sql($report_id)
808 Given a report id, return the SQL statement for that report.
809 Otherwise, it just returns.
811 =cut
813 sub get_sql {
814 my ($id) = @_ or return;
815 my $dbh = C4::Context->dbh();
816 my $query = "SELECT * FROM saved_sql WHERE id = ?";
817 my $sth = $dbh->prepare($query);
818 $sth->execute($id);
819 my $data=$sth->fetchrow_hashref();
820 return $data->{'savedsql'};
823 sub get_results {
824 my ( $report_id ) = @_;
825 my $dbh = C4::Context->dbh;
826 return $dbh->selectall_arrayref(q|
827 SELECT id, report, date_run
828 FROM saved_reports
829 WHERE report_id = ?
830 |, { Slice => {} }, $report_id);
833 sub _get_column_defs {
834 my ($cgi) = @_;
835 my %columns;
836 my $columns_def_file = "columns.def";
837 my $htdocs = C4::Context->config('intrahtdocs');
838 my $section = 'intranet';
840 # We need the theme and the lang
841 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
842 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
844 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
845 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
846 while ( my $input = <$fh> ){
847 chomp $input;
848 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
849 my ( $field, $translation ) = ( $1, $2 );
850 $columns{$field} = $translation;
853 close $fh;
854 return \%columns;
857 =head2 GetReservedAuthorisedValues
859 my %reserved_authorised_values = GetReservedAuthorisedValues();
861 Returns a hash containig all reserved words
863 =cut
865 sub GetReservedAuthorisedValues {
866 my %reserved_authorised_values =
867 map { $_ => 1 } ( 'date',
868 'branches',
869 'itemtypes',
870 'cn_source',
871 'categorycode',
872 'biblio_framework' );
874 return \%reserved_authorised_values;
878 =head2 IsAuthorisedValueValid
880 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
882 Returns 1 if $authorised_value is on the reserved authorised values list or
883 in the authorised value categories defined in
885 =cut
887 sub IsAuthorisedValueValid {
889 my $authorised_value = shift;
890 my $reserved_authorised_values = GetReservedAuthorisedValues();
892 if ( exists $reserved_authorised_values->{$authorised_value} ||
893 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
894 return 1;
897 return 0;
900 =head2 GetParametersFromSQL
902 my @sql_parameters = GetParametersFromSQL($sql)
904 Returns an arrayref of hashes containing the keys name and authval
906 =cut
908 sub GetParametersFromSQL {
910 my $sql = shift ;
911 my @split = split(/<<|>>/,$sql);
912 my @sql_parameters = ();
914 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
915 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
916 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
919 return \@sql_parameters;
922 =head2 ValidateSQLParameters
924 my @problematic_parameters = ValidateSQLParameters($sql)
926 Returns an arrayref of hashes containing the keys name and authval of
927 those SQL parameters that do not correspond to valid authorised names
929 =cut
931 sub ValidateSQLParameters {
933 my $sql = shift;
934 my @problematic_parameters = ();
935 my $sql_parameters = GetParametersFromSQL($sql);
937 foreach my $sql_parameter (@$sql_parameters) {
938 if ( defined $sql_parameter->{'authval'} ) {
939 push @problematic_parameters, $sql_parameter unless
940 IsAuthorisedValueValid($sql_parameter->{'authval'});
944 return \@problematic_parameters;
947 =head2 EmailReport
949 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
951 Take a report and use it to process a Template Toolkit formatted notice
952 Returns arrayrefs containing prepared letters and errors respectively
954 =cut
956 sub EmailReport {
958 my $params = shift;
959 my $report_id = $params->{report_id};
960 my $from = $params->{from};
961 my $email = $params->{email};
962 my $module = $params->{module};
963 my $code = $params->{code};
964 my $branch = $params->{branch} || "";
966 my @errors = ();
967 my @emails = ();
969 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
971 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
972 my $letter = Koha::Notice::Templates->find({
973 module => $module,
974 code => $code,
975 branchcode => $branch,
976 message_transport_type => 'email',
978 $letter = $letter->unblessed;
980 my $report = Koha::Reports->find( $report_id );
981 my $sql = $report->savedsql;
982 return ( { FATAL => "NO_REPORT" } ) unless $sql;
984 my ( $sth, $errors ) = execute_query( $sql ); #don't pass offset or limit, hardcoded limit of 999,999 will be used
985 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
987 my $counter = 1;
988 my $template = $letter->{content};
990 while ( my $row = $sth->fetchrow_hashref() ) {
991 my $email;
992 my $err_count = scalar @errors;
993 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
994 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( (defined $email && defined $row->{$email}) || defined $row->{email} );
995 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
996 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
998 my $from_address = $from || $row->{from};
999 my $to_address = $email ? $row->{$email} : $row->{email};
1000 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1001 $counter++;
1002 next if scalar @errors > $err_count; #If any problems, try next
1004 $letter->{content} = $content;
1005 $email->{borrowernumber} = $row->{borrowernumber};
1006 $email->{letter} = $letter;
1007 $email->{from_address} = $from_address;
1008 $email->{to_address} = $to_address;
1010 push ( @emails, $email );
1013 return ( \@emails, \@errors );
1019 =head2 ProcessRowTT
1021 my $content = ProcessRowTT($row_hashref, $template);
1023 Accepts a hashref containing values and processes them against Template Toolkit
1024 to produce content
1026 =cut
1028 sub _process_row_TT {
1030 my ($row, $template) = @_;
1032 return 0 unless ($row && $template);
1033 my $content;
1034 my $processor = Template->new();
1035 $processor->process( \$template, $row, \$content);
1036 return $content;
1040 sub _get_display_value {
1041 my ( $original_value, $column ) = @_;
1042 if ( $column eq 'periodicity' ) {
1043 my $dbh = C4::Context->dbh();
1044 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1045 my $sth = $dbh->prepare($query);
1046 $sth->execute($original_value);
1047 return $sth->fetchrow;
1049 return $original_value;
1053 =head3 convert_sql
1055 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1057 Convert a sql query using biblioitems.marcxml to use the new
1058 biblio_metadata.metadata field instead
1060 =cut
1062 sub convert_sql {
1063 my ( $sql ) = @_;
1064 my $updated_sql = $sql;
1065 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1066 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1067 $updated_sql =~ s|marcxml|metadata|g;
1069 return $updated_sql;
1073 __END__
1075 =head1 AUTHOR
1077 Chris Cormack <crc@liblime.com>
1079 =cut