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>.
22 use Carp qw( carp croak );
23 use JSON qw( from_json );
26 use C4::Templates qw/themelanguage/;
27 use C4::Koha qw( GetAuthorisedValues );
28 use Koha::DateUtils qw( dt_from_string output_pref );
32 use C4::Log qw( logaction );
33 use Koha::Notice::Templates;
36 use Koha::AuthorisedValues;
37 use Koha::Patron::Categories;
38 use Koha::SharedContent;
40 our (@ISA, @EXPORT_OK);
45 get_report_types get_report_areas get_report_groups get_columns build_query get_criteria
46 save_report get_saved_reports execute_query
47 get_column_type get_distinct_values save_dictionary get_from_dictionary
48 delete_definition delete_report store_results format_results get_sql get_results
52 GetReservedAuthorisedValues
54 IsAuthorisedValueValid
63 C4::Reports::Guided - Module for generating guided reports
67 use C4::Reports::Guided;
75 =head2 get_report_areas
77 This will return a list of all the available report areas
81 sub get_area_name_sql_snippet {
83 [CIRC => "Circulation"],
86 [ACQ => "Acquisition"],
91 return "CASE report_area " .
92 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
96 sub get_report_areas {
98 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
100 return $report_areas;
103 sub get_table_areas {
105 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
106 CAT => [ 'items', 'biblioitems', 'biblio' ],
107 PAT => ['borrowers'],
108 ACQ => [ 'aqorders', 'biblio', 'items' ],
109 ACC => [ 'borrowers', 'accountlines' ],
110 SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
114 =head2 get_report_types
116 This will return a list of all the available report types
120 sub get_report_types {
121 my $dbh = C4::Context->dbh();
123 # FIXME these should be in the database perhaps
124 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
126 for ( my $i = 0 ; $i < 3 ; $i++ ) {
128 $hashrep{id} = $i + 1;
129 $hashrep{name} = $reports[$i];
130 push @reports2, \%hashrep;
132 return ( \@reports2 );
136 =head2 get_report_groups
138 This will return a list of all the available report areas with groups
142 sub get_report_groups {
143 my $dbh = C4::Context->dbh();
145 my $groups = GetAuthorisedValues('REPORT_GROUP');
146 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
148 my %groups_with_subgroups = map { $_->{authorised_value} => {
152 foreach (@$subgroups) {
153 my $sg = $_->{authorised_value};
154 my $g = $_->{lib_opac}
155 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
157 my $g_sg = $groups_with_subgroups{$g}
158 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
160 $g_sg->{subgroups}{$sg} = $_->{lib};
162 return \%groups_with_subgroups
165 =head2 get_all_tables
167 This will return a list of all tables in the database
172 my $dbh = C4::Context->dbh();
173 my $query = "SHOW TABLES";
174 my $sth = $dbh->prepare($query);
177 while ( my $data = $sth->fetchrow_arrayref() ) {
178 push @tables, $data->[0];
185 =head2 get_columns($area)
187 This will return a list of all columns for a report area
193 # this calls the internal function _get_columns
194 my ( $area, $cgi ) = @_;
195 my %table_areas = get_table_areas;
196 my $tables = $table_areas{$area}
197 or die qq{Unsuported report area "$area"};
201 foreach my $table (@$tables) {
202 my @columns = _get_columns($table,$cgi, $first);
204 push @allcolumns, @columns;
206 return ( \@allcolumns );
210 my ($tablename,$cgi, $first) = @_;
211 my $dbh = C4::Context->dbh();
212 my $sth = $dbh->prepare("show columns from $tablename");
215 my $column_defs = _get_column_defs($cgi);
217 $tablehash{'table'}=$tablename;
218 $tablehash{'__first__'} = $first;
219 push @columns, \%tablehash;
220 while ( my $data = $sth->fetchrow_arrayref() ) {
222 $temphash{'name'} = "$tablename.$data->[0]";
223 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
224 push @columns, \%temphash;
230 =head2 build_query($columns,$criteria,$orderby,$area)
232 This will build the sql needed to return the results asked for,
233 $columns is expected to be of the format tablename.columnname.
234 This is what get_columns returns.
239 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
242 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
243 'items.itemnumber = statistics.itemnumber',
244 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
245 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
246 'biblioitems.biblionumber=biblio.biblionumber' ],
248 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
249 'biblio.biblionumber=items.biblionumber' ],
250 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
251 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'],
256 my $keys = $keys{$area};
257 my %table_areas = get_table_areas;
258 my $tables = $table_areas{$area};
261 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
266 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
268 # $keys is an array of joining constraints
269 my $dbh = C4::Context->dbh();
270 my $joinedtables = join( ',', @$tables );
271 my $joinedcolumns = join( ',', @$columns );
273 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
274 for (my $i=1;$i<@$tables;$i++){
275 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
279 $criteria =~ s/AND/WHERE/;
280 $query .= " $criteria";
283 my @definitions = split(',',$definition);
285 foreach my $def (@definitions){
286 my $defin=get_from_dictionary('',$def);
287 $deftext .=" ".$defin->[0]->{'saved_sql'};
289 if ($query =~ /WHERE/i){
293 $deftext =~ s/AND/WHERE/;
299 my @totcolumns = split( ',', $totals );
300 foreach my $total (@totcolumns) {
301 if ( $total =~ /\((.*)\)/ ) {
302 if ( $groupby eq '' ) {
303 $groupby = " GROUP BY $1";
318 =head2 get_criteria($area,$cgi);
320 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
325 my ($area,$cgi) = @_;
326 my $dbh = C4::Context->dbh();
328 # have to do someting here to know if its dropdown, free text, date etc
330 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
331 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
332 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
333 'items.barcode|textrange', 'biblio.frameworkcode',
334 'items.holdingbranch', 'items.homebranch',
335 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
336 'items.onloan|daterange', 'items.ccode',
337 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
339 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
340 ACQ => ['aqorders.datereceived|date'],
341 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
342 SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
345 # Adds itemtypes to criteria, according to the syspref
346 if ( C4::Context->preference('item-level_itypes') ) {
347 unshift @{ $criteria{'CIRC'} }, 'items.itype';
348 unshift @{ $criteria{'CAT'} }, 'items.itype';
350 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
351 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
355 my $crit = $criteria{$area};
356 my $column_defs = _get_column_defs($cgi);
358 foreach my $localcrit (@$crit) {
359 my ( $value, $type ) = split( /\|/, $localcrit );
360 my ( $table, $column ) = split( /\./, $value );
361 if ($type eq 'textrange') {
363 $temp{'name'} = $value;
364 $temp{'from'} = "from_" . $value;
365 $temp{'to'} = "to_" . $value;
366 $temp{'textrange'} = 1;
367 $temp{'description'} = $column_defs->{$value};
368 push @criteria_array, \%temp;
370 elsif ($type eq 'date') {
372 $temp{'name'} = $value;
374 $temp{'description'} = $column_defs->{$value};
375 push @criteria_array, \%temp;
377 elsif ($type eq 'daterange') {
379 $temp{'name'} = $value;
380 $temp{'from'} = "from_" . $value;
381 $temp{'to'} = "to_" . $value;
382 $temp{'daterange'} = 1;
383 $temp{'description'} = $column_defs->{$value};
384 push @criteria_array, \%temp;
388 "SELECT distinct($column) as availablevalues FROM $table";
389 my $sth = $dbh->prepare($query);
392 # push the runtime choosing option
394 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
395 $list='categorycode' if $column eq 'categorycode';
396 $list='itemtypes' if $column eq 'itype';
397 $list='ccode' if $column eq 'ccode';
398 # TODO : improve to let the librarian choose the description at runtime
400 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
401 display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
403 while ( my $row = $sth->fetchrow_hashref() ) {
404 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
405 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
411 $temp{'name'} = $value;
412 $temp{'description'} = $column_defs->{$value};
413 $temp{'values'} = \@values;
415 push @criteria_array, \%temp;
418 return ( \@criteria_array );
422 my $sql = shift or return;
424 my $derived_name = 'xxx';
425 # make sure the derived table name is not already used
426 while ( $sql =~ m/$derived_name/ ) {
427 $derived_name .= 'x';
431 my $dbh = C4::Context->dbh;
435 my $RaiseError = $dbh->{RaiseError};
436 my $PrintError = $dbh->{PrintError};
437 $dbh->{RaiseError} = 1;
438 $dbh->{PrintError} = 0;
440 $sth = $dbh->prepare(qq{
442 ( $sql ) $derived_name
447 $dbh->{RaiseError} = $RaiseError;
448 $dbh->{PrintError} = $PrintError;
449 if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
451 $sth = $dbh->prepare($sql);
455 # Loop through the complete results, fetching 1,000 rows at a time. This
456 # lowers memory requirements but increases execution time.
457 while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
463 my $results = $sth->fetch;
464 return $results ? $results->[0] : 0;
469 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
472 This function returns a DBI statement handler from which the caller can
473 fetch the results of the SQL passed via C<$sql>.
475 If passed any query other than a SELECT, or if there is a DB error,
476 C<$errors> is returned, and is a hashref containing the error after this
479 C<$error->{'sqlerr'}> contains the offending SQL keyword.
480 C<$error->{'queryerr'}> contains the native db engine error returned
483 C<$offset>, and C<$limit> are required parameters.
485 C<\@sql_params> is an optional list of parameter values to paste in.
486 The caller is responsible for making sure that C<$sql> has placeholders
487 and that the number placeholders matches the number of parameters.
491 # returns $sql, $offset, $limit
492 # $sql returned will be transformed to:
493 # ~ remove any LIMIT clause
494 # ~ repace SELECT clause w/ SELECT count(*)
496 sub select_2_select_count {
497 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
498 my ($sql) = strip_limit(shift) or return;
499 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
503 # This removes the LIMIT from the query so that a custom one can be specified.
505 # ($new_sql, $offset, $limit) = strip_limit($sql);
508 # $sql is the query to modify
509 # $new_sql is the resulting query
510 # $offset is the offset value, if the LIMIT was the two-argument form,
511 # 0 if it wasn't otherwise given.
512 # $limit is the limit value
515 # * This makes an effort to not break subqueries that have their own
516 # LIMIT specified. It does that by only removing a LIMIT if it comes after
517 # a WHERE clause (which isn't perfect, but at least should make more cases
518 # work - subqueries with a limit in the WHERE will still break.)
519 # * If your query doesn't have a WHERE clause then all LIMITs will be
520 # removed. This may break some subqueries, but is hopefully rare enough
521 # to not be a big issue.
526 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
528 # Two options: if there's no WHERE clause in the SQL, we simply capture
529 # any LIMIT that's there. If there is a WHERE, we make sure that we only
530 # capture a LIMIT after the last one. This prevents stomping on subqueries.
531 if ($sql !~ /\bWHERE\b/i) {
532 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
533 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
536 $res =~ m/.*\bWHERE\b/gsi;
537 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
538 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
544 my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
546 $sql_params = [] unless defined $sql_params;
550 carp "execute_query() called without SQL argument";
553 $offset = 0 unless $offset;
554 $limit = 999999 unless $limit;
556 Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
558 my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
559 return (undef, @{$errors}[0]) unless $is_sql_valid;
561 foreach my $sql_param ( @$sql_params ){
562 if ( $sql_param =~ m/\n/ ){
563 my @list = split /\n/, $sql_param;
565 foreach my $item ( @list ){
567 push @quoted_list, C4::Context->dbh->quote($item);
569 $sql_param = "(".join(",",@quoted_list).")";
573 my ($useroffset, $userlimit);
575 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
576 ($sql, $useroffset, $userlimit) = strip_limit($sql);
578 Koha::Logger->get->debug(
579 sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
580 $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
582 $offset += $useroffset;
583 if (defined($userlimit)) {
584 if ($offset + $limit > $userlimit ) {
585 $limit = $userlimit - $offset;
586 } elsif ( ! $offset && $limit < $userlimit ) {
590 $sql .= " LIMIT ?, ?";
592 my $dbh = C4::Context->dbh;
594 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
596 my $sth = $dbh->prepare($sql);
598 $sth->execute(@$sql_params, $offset, $limit);
602 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
606 =head2 save_report($sql,$name,$type,$notes)
608 Given some sql and a name this will saved it so that it can reused
609 Returns id of the newly created report
615 my $borrowernumber = $fields->{borrowernumber};
616 my $sql = $fields->{sql};
617 my $name = $fields->{name};
618 my $type = $fields->{type};
619 my $notes = $fields->{notes};
620 my $area = $fields->{area};
621 my $group = $fields->{group};
622 my $subgroup = $fields->{subgroup};
623 my $cache_expiry = $fields->{cache_expiry};
624 my $public = $fields->{public};
626 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
627 my $now = dt_from_string;
628 my $report = Koha::Report->new(
630 borrowernumber => $borrowernumber,
631 date_created => $now, # Must be moved to Koha::Report->store
632 last_modified => $now, # Must be moved to Koha::Report->store
634 report_name => $name,
635 report_area => $area,
636 report_group => $group,
637 report_subgroup => $subgroup,
640 cache_expiry => $cache_expiry,
649 my $id = shift || croak "No Id given";
651 my $sql = $fields->{sql};
652 my $name = $fields->{name};
653 my $notes = $fields->{notes};
654 my $group = $fields->{group};
655 my $subgroup = $fields->{subgroup};
656 my $cache_expiry = $fields->{cache_expiry};
657 my $public = $fields->{public};
659 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
660 my $report = Koha::Reports->find($id);
661 $report->last_modified(dt_from_string);
662 $report->savedsql($sql);
663 $report->report_name($name);
664 $report->notes($notes);
665 $report->report_group($group);
666 $report->report_subgroup($subgroup);
667 $report->cache_expiry($cache_expiry) if defined $cache_expiry;
668 $report->public($public);
670 if( $cache_expiry >= 2592000 ){
671 die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
678 my ( $id, $json ) = @_;
679 my $dbh = C4::Context->dbh();
681 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
682 |, undef, $id, $json );
687 my $dbh = C4::Context->dbh();
688 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
689 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
691 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
695 report_name => $report_name,
697 results => from_json( $json ),
698 date_run => $date_run,
705 foreach my $id (@ids) {
706 my $data = Koha::Reports->find($id);
707 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
709 my $dbh = C4::Context->dbh;
710 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
711 my $sth = $dbh->prepare($query);
712 return $sth->execute(@ids);
715 sub get_saved_reports_base_query {
716 my $area_name_sql_snippet = get_area_name_sql_snippet;
718 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
719 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
721 LEFT JOIN saved_reports r ON r.report_id = s.id
722 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
723 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)
724 LEFT OUTER JOIN borrowers b USING (borrowernumber)
728 sub get_saved_reports {
729 # $filter is either { date => $d, author => $a, keyword => $kw, }
730 # or $keyword. Optional.
732 $filter = { keyword => $filter } if $filter && !ref( $filter );
733 my ($group, $subgroup) = @_;
735 my $dbh = C4::Context->dbh();
736 my $query = get_saved_reports_base_query;
739 if (my $date = $filter->{date}) {
740 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
741 push @cond, "DATE(last_modified) = ? OR
743 push @args, $date, $date, $date;
745 if (my $author = $filter->{author}) {
746 $author = "%$author%";
747 push @cond, "surname LIKE ? OR
749 push @args, $author, $author;
751 if (my $keyword = $filter->{keyword}) {
754 OR report_name LIKE ?
759 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
761 if ($filter->{group}) {
762 push @cond, "report_group = ?";
763 push @args, $filter->{group};
765 if ($filter->{subgroup}) {
766 push @cond, "report_subgroup = ?";
767 push @args, $filter->{subgroup};
770 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
771 $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";
772 $query .= " ORDER by date_created";
774 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
779 =head2 get_column_type($column)
781 This takes a column name of the format table.column and will return what type it is
782 (free text, set values, date)
786 sub get_column_type {
787 my ($tablecolumn) = @_;
788 my ($table,$column) = split(/\./,$tablecolumn);
789 my $dbh = C4::Context->dbh();
793 # mysql doesn't support a column selection, set column to %
795 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
796 while (my $info = $sth->fetchrow_hashref()){
797 if ($info->{'COLUMN_NAME'} eq $column){
799 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
800 $info->{'TYPE_NAME'} = 'distinct';
802 return $info->{'TYPE_NAME'};
807 =head2 get_distinct_values($column)
809 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
810 with the distinct values of the column
814 sub get_distinct_values {
815 my ($tablecolumn) = @_;
816 my ($table,$column) = split(/\./,$tablecolumn);
817 my $dbh = C4::Context->dbh();
819 "SELECT distinct($column) as availablevalues FROM $table";
820 my $sth = $dbh->prepare($query);
822 return $sth->fetchall_arrayref({});
825 sub save_dictionary {
826 my ( $name, $description, $sql, $area ) = @_;
827 my $dbh = C4::Context->dbh();
828 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
829 VALUES (?,?,?,?,now(),now())";
830 my $sth = $dbh->prepare($query);
831 $sth->execute($name,$description,$sql,$area) || return 0;
835 sub get_from_dictionary {
836 my ( $area, $id ) = @_;
837 my $dbh = C4::Context->dbh();
838 my $area_name_sql_snippet = get_area_name_sql_snippet;
840 SELECT d.*, $area_name_sql_snippet
841 FROM reports_dictionary d
845 $query .= " WHERE report_area = ?";
847 $query .= " WHERE id = ?";
849 my $sth = $dbh->prepare($query);
853 $sth->execute($area);
858 while ( my $data = $sth->fetchrow_hashref() ) {
864 sub delete_definition {
865 my ($id) = @_ or return;
866 my $dbh = C4::Context->dbh();
867 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
868 my $sth = $dbh->prepare($query);
872 =head2 get_sql($report_id)
874 Given a report id, return the SQL statement for that report.
875 Otherwise, it just returns.
880 my ($id) = @_ or return;
881 my $dbh = C4::Context->dbh();
882 my $query = "SELECT * FROM saved_sql WHERE id = ?";
883 my $sth = $dbh->prepare($query);
885 my $data=$sth->fetchrow_hashref();
886 return $data->{'savedsql'};
890 my ( $report_id ) = @_;
891 my $dbh = C4::Context->dbh;
892 return $dbh->selectall_arrayref(q|
893 SELECT id, report, date_run
896 |, { Slice => {} }, $report_id);
899 sub _get_column_defs {
902 my $columns_def_file = "columns.def";
903 my $htdocs = C4::Context->config('intrahtdocs');
904 my $section = 'intranet';
906 # We need the theme and the lang
907 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
908 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
910 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
911 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
912 while ( my $input = <$fh> ){
914 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
915 my ( $field, $translation ) = ( $1, $2 );
916 $columns{$field} = $translation;
923 =head2 GetReservedAuthorisedValues
925 my %reserved_authorised_values = GetReservedAuthorisedValues();
927 Returns a hash containig all reserved words
931 sub GetReservedAuthorisedValues {
932 my %reserved_authorised_values =
933 map { $_ => 1 } ( 'date',
939 'biblio_framework' );
941 return \%reserved_authorised_values;
945 =head2 IsAuthorisedValueValid
947 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
949 Returns 1 if $authorised_value is on the reserved authorised values list or
950 in the authorised value categories defined in
954 sub IsAuthorisedValueValid {
956 my $authorised_value = shift;
957 my $reserved_authorised_values = GetReservedAuthorisedValues();
959 if ( exists $reserved_authorised_values->{$authorised_value} ||
960 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
967 =head2 GetParametersFromSQL
969 my @sql_parameters = GetParametersFromSQL($sql)
971 Returns an arrayref of hashes containing the keys name and authval
975 sub GetParametersFromSQL {
978 my @split = split(/<<|>>/,$sql);
979 my @sql_parameters = ();
981 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
982 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
983 $authval =~ s/\:all$// if $authval;
984 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
987 return \@sql_parameters;
990 =head2 ValidateSQLParameters
992 my @problematic_parameters = ValidateSQLParameters($sql)
994 Returns an arrayref of hashes containing the keys name and authval of
995 those SQL parameters that do not correspond to valid authorised names
999 sub ValidateSQLParameters {
1002 my @problematic_parameters = ();
1003 my $sql_parameters = GetParametersFromSQL($sql);
1005 foreach my $sql_parameter (@$sql_parameters) {
1006 if ( defined $sql_parameter->{'authval'} ) {
1007 push @problematic_parameters, $sql_parameter unless
1008 IsAuthorisedValueValid($sql_parameter->{'authval'});
1012 return \@problematic_parameters;
1017 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1019 Take a report and use it to process a Template Toolkit formatted notice
1020 Returns arrayrefs containing prepared letters and errors respectively
1027 my $report_id = $params->{report_id};
1028 my $from = $params->{from};
1029 my $email_col = $params->{email} || 'email';
1030 my $module = $params->{module};
1031 my $code = $params->{code};
1032 my $branch = $params->{branch} || "";
1037 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1039 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1040 my $letter = Koha::Notice::Templates->find({
1043 branchcode => $branch,
1044 message_transport_type => 'email',
1046 $letter = $letter->unblessed;
1048 my $report = Koha::Reports->find( $report_id );
1049 my $sql = $report->savedsql;
1050 return ( { FATAL => "NO_REPORT" } ) unless $sql;
1052 my ( $sth, $errors ) = execute_query( $sql ); #don't pass offset or limit, hardcoded limit of 999,999 will be used
1053 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1056 my $template = $letter->{content};
1058 while ( my $row = $sth->fetchrow_hashref() ) {
1060 my $err_count = scalar @errors;
1061 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1062 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1063 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1064 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1066 my $from_address = $from || $row->{from};
1067 my $to_address = $row->{$email_col};
1068 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1070 next if scalar @errors > $err_count; #If any problems, try next
1072 $letter->{content} = $content;
1073 $email->{borrowernumber} = $row->{borrowernumber};
1074 $email->{letter} = { %$letter };
1075 $email->{from_address} = $from_address;
1076 $email->{to_address} = $to_address;
1078 push ( @emails, $email );
1081 return ( \@emails, \@errors );
1089 my $content = ProcessRowTT($row_hashref, $template);
1091 Accepts a hashref containing values and processes them against Template Toolkit
1096 sub _process_row_TT {
1098 my ($row, $template) = @_;
1100 return 0 unless ($row && $template);
1102 my $processor = Template->new();
1103 $processor->process( \$template, $row, \$content);
1108 sub _get_display_value {
1109 my ( $original_value, $column ) = @_;
1110 if ( $column eq 'periodicity' ) {
1111 my $dbh = C4::Context->dbh();
1112 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1113 my $sth = $dbh->prepare($query);
1114 $sth->execute($original_value);
1115 return $sth->fetchrow;
1117 return $original_value;
1123 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1125 Convert a sql query using biblioitems.marcxml to use the new
1126 biblio_metadata.metadata field instead
1132 my $updated_sql = $sql;
1133 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1134 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1135 $updated_sql =~ s|marcxml|metadata|g;
1137 return $updated_sql;
1145 Chris Cormack <crc@liblime.com>