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 );
32 use C4::Log qw( logaction );
33 use Koha::Notice::Templates;
35 use Koha::Database::Columns;
37 use Koha::AuthorisedValues;
38 use Koha::Patron::Categories;
39 use Koha::SharedContent;
41 our (@ISA, @EXPORT_OK);
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 store_results format_results get_sql get_results
53 GetReservedAuthorisedValues
55 IsAuthorisedValueValid
64 C4::Reports::Guided - Module for generating guided reports
68 use C4::Reports::Guided;
76 =head2 get_report_areas
78 This will return a list of all the available report areas
82 sub get_area_name_sql_snippet {
84 [CIRC => "Circulation"],
87 [ACQ => "Acquisition"],
92 return "CASE report_area " .
93 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
97 sub get_report_areas {
99 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
101 return $report_areas;
104 sub get_table_areas {
106 CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ],
107 CAT => [ 'items', 'biblioitems', 'biblio' ],
108 PAT => ['borrowers'],
109 ACQ => [ 'aqorders', 'biblio', 'items' ],
110 ACC => [ 'borrowers', 'accountlines' ],
111 SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ],
115 =head2 get_report_types
117 This will return a list of all the available report types
121 sub get_report_types {
122 my $dbh = C4::Context->dbh();
124 # FIXME these should be in the database perhaps
125 my @reports = ( 'Tabular', 'Summary', 'Matrix' );
127 for ( my $i = 0 ; $i < 3 ; $i++ ) {
129 $hashrep{id} = $i + 1;
130 $hashrep{name} = $reports[$i];
131 push @reports2, \%hashrep;
133 return ( \@reports2 );
137 =head2 get_report_groups
139 This will return a list of all the available report areas with groups
143 sub get_report_groups {
144 my $dbh = C4::Context->dbh();
146 my $groups = GetAuthorisedValues('REPORT_GROUP');
147 my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP');
149 my %groups_with_subgroups = map { $_->{authorised_value} => {
153 foreach (@$subgroups) {
154 my $sg = $_->{authorised_value};
155 my $g = $_->{lib_opac}
156 or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ),
158 my $g_sg = $groups_with_subgroups{$g}
159 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
161 $g_sg->{subgroups}{$sg} = $_->{lib};
163 return \%groups_with_subgroups
166 =head2 get_all_tables
168 This will return a list of all tables in the database
173 my $dbh = C4::Context->dbh();
174 my $query = "SHOW TABLES";
175 my $sth = $dbh->prepare($query);
178 while ( my $data = $sth->fetchrow_arrayref() ) {
179 push @tables, $data->[0];
186 =head2 get_columns($area)
188 This will return a list of all columns for a report area
194 # this calls the internal function _get_columns
195 my ( $area, $cgi ) = @_;
196 my %table_areas = get_table_areas;
197 my $tables = $table_areas{$area}
198 or die qq{Unsuported report area "$area"};
202 foreach my $table (@$tables) {
203 my @columns = _get_columns($table,$cgi, $first);
205 push @allcolumns, @columns;
207 return ( \@allcolumns );
211 my ($tablename,$cgi, $first) = @_;
212 my $dbh = C4::Context->dbh();
213 my $sth = $dbh->prepare("show columns from $tablename");
216 my $columns = Koha::Database::Columns->columns;
218 $tablehash{'table'}=$tablename;
219 $tablehash{'__first__'} = $first;
220 push @columns, \%tablehash;
221 while ( my $data = $sth->fetchrow_arrayref() ) {
223 $temphash{'name'} = "$tablename.$data->[0]";
224 $temphash{'description'} = $columns->{$tablename}->{$data->[0]};
225 push @columns, \%temphash;
231 =head2 build_query($columns,$criteria,$orderby,$area)
233 This will build the sql needed to return the results asked for,
234 $columns is expected to be of the format tablename.columnname.
235 This is what get_columns returns.
240 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
243 CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber',
244 'items.itemnumber = statistics.itemnumber',
245 'biblioitems.biblioitemnumber = items.biblioitemnumber' ],
246 CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber',
247 'biblioitems.biblionumber=biblio.biblionumber' ],
249 ACQ => [ 'aqorders.biblionumber=biblio.biblionumber',
250 'biblio.biblionumber=items.biblionumber' ],
251 ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'],
252 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'],
257 my $keys = $keys{$area};
258 my %table_areas = get_table_areas;
259 my $tables = $table_areas{$area};
262 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
267 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
269 # $keys is an array of joining constraints
270 my $dbh = C4::Context->dbh();
271 my $joinedtables = join( ',', @$tables );
272 my $joinedcolumns = join( ',', @$columns );
274 "SELECT $totals $joinedcolumns FROM $tables->[0] ";
275 for (my $i=1;$i<@$tables;$i++){
276 $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) ";
280 $criteria =~ s/AND/WHERE/;
281 $query .= " $criteria";
284 my @definitions = split(',',$definition);
286 foreach my $def (@definitions){
287 my $defin=get_from_dictionary('',$def);
288 $deftext .=" ".$defin->[0]->{'saved_sql'};
290 if ($query =~ /WHERE/i){
294 $deftext =~ s/AND/WHERE/;
300 my @totcolumns = split( ',', $totals );
301 foreach my $total (@totcolumns) {
302 if ( $total =~ /\((.*)\)/ ) {
303 if ( $groupby eq '' ) {
304 $groupby = " GROUP BY $1";
319 =head2 get_criteria($area,$cgi);
321 Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the criteria and available values.
326 my ($area,$cgi) = @_;
327 my $dbh = C4::Context->dbh();
329 # have to do someting here to know if its dropdown, free text, date etc
331 CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch',
332 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ],
333 CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange',
334 'items.barcode|textrange', 'biblio.frameworkcode',
335 'items.holdingbranch', 'items.homebranch',
336 'biblio.datecreated|daterange', 'biblio.timestamp|daterange',
337 'items.onloan|daterange', 'items.ccode',
338 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost',
340 PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
341 ACQ => ['aqorders.datereceived|date'],
342 ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ],
343 SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'],
346 # Adds itemtypes to criteria, according to the syspref
347 if ( C4::Context->preference('item-level_itypes') ) {
348 unshift @{ $criteria{'CIRC'} }, 'items.itype';
349 unshift @{ $criteria{'CAT'} }, 'items.itype';
351 unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype';
352 unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype';
356 my $crit = $criteria{$area};
357 my $columns = Koha::Database::Columns->columns;
359 foreach my $localcrit (@$crit) {
360 my ( $value, $type ) = split( /\|/, $localcrit );
361 my ( $table, $column ) = split( /\./, $value );
362 my $description = $columns->{$table}->{$column};
363 if ($type eq 'textrange') {
365 $temp{'name'} = $value;
366 $temp{'from'} = "from_" . $value;
367 $temp{'to'} = "to_" . $value;
368 $temp{'textrange'} = 1;
369 $temp{'description'} = $description;
370 push @criteria_array, \%temp;
372 elsif ($type eq 'date') {
374 $temp{'name'} = $value;
376 $temp{'description'} = $description;
377 push @criteria_array, \%temp;
379 elsif ($type eq 'daterange') {
381 $temp{'name'} = $value;
382 $temp{'from'} = "from_" . $value;
383 $temp{'to'} = "to_" . $value;
384 $temp{'daterange'} = 1;
385 $temp{'description'} = $description;
386 push @criteria_array, \%temp;
390 "SELECT distinct($column) as availablevalues FROM $table";
391 my $sth = $dbh->prepare($query);
394 # push the runtime choosing option
396 $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch';
397 $list='categorycode' if $column eq 'categorycode';
398 $list='itemtypes' if $column eq 'itype';
399 $list='ccode' if $column eq 'ccode';
400 # TODO : improve to let the librarian choose the description at runtime
402 availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
403 display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>",
405 while ( my $row = $sth->fetchrow_hashref() ) {
406 if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 }
407 else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); }
412 push @criteria_array, {
414 description => $description,
419 return ( \@criteria_array );
423 my $sql = shift or return;
425 my $derived_name = 'xxx';
426 # make sure the derived table name is not already used
427 while ( $sql =~ m/$derived_name/ ) {
428 $derived_name .= 'x';
432 my $dbh = C4::Context->dbh;
436 my $RaiseError = $dbh->{RaiseError};
437 my $PrintError = $dbh->{PrintError};
438 $dbh->{RaiseError} = 1;
439 $dbh->{PrintError} = 0;
441 $sth = $dbh->prepare(qq{
443 ( $sql ) $derived_name
448 $dbh->{RaiseError} = $RaiseError;
449 $dbh->{PrintError} = $PrintError;
450 if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
452 $sth = $dbh->prepare($sql);
456 # Loop through the complete results, fetching 1,000 rows at a time. This
457 # lowers memory requirements but increases execution time.
458 while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
464 my $results = $sth->fetch;
465 return $results ? $results->[0] : 0;
468 =head2 select_2_select_count
470 returns $sql, $offset, $limit
471 $sql returned will be transformed to:
472 ~ remove any LIMIT clause
473 ~ replace SELECT clause w/ SELECT count(*)
477 sub select_2_select_count {
478 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
479 my ($sql) = strip_limit(shift) or return;
480 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
485 This removes the LIMIT from the query so that a custom one can be specified.
487 ($new_sql, $offset, $limit) = strip_limit($sql);
490 $sql is the query to modify
491 $new_sql is the resulting query
492 $offset is the offset value, if the LIMIT was the two-argument form,
493 0 if it wasn't otherwise given.
494 $limit is the limit value
497 * This makes an effort to not break subqueries that have their own
498 LIMIT specified. It does that by only removing a LIMIT if it comes after
499 a WHERE clause (which isn't perfect, but at least should make more cases
500 work - subqueries with a limit in the WHERE will still break.)
501 * If your query doesn't have a WHERE clause then all LIMITs will be
502 removed. This may break some subqueries, but is hopefully rare enough
503 to not be a big issue.
511 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
513 # Two options: if there's no WHERE clause in the SQL, we simply capture
514 # any LIMIT that's there. If there is a WHERE, we make sure that we only
515 # capture a LIMIT after the last one. This prevents stomping on subqueries.
516 if ($sql !~ /\bWHERE\b/i) {
517 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
518 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
521 $res =~ m/.*\bWHERE\b/gsi;
522 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
523 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
529 ($sth, $error) = execute_query({
533 sql_params => \@sql_params],
534 report_id => $report_id
538 This function returns a DBI statement handler from which the caller can
539 fetch the results of the SQL passed via C<$sql>.
541 If passed any query other than a SELECT, or if there is a DB error,
542 C<$errors> is returned, and is a hashref containing the error after this
545 C<$error->{'sqlerr'}> contains the offending SQL keyword.
546 C<$error->{'queryerr'}> contains the native db engine error returned
549 C<$offset>, and C<$limit> are required parameters.
551 C<\@sql_params> is an optional list of parameter values to paste in.
552 The caller is responsible for making sure that C<$sql> has placeholders
553 and that the number placeholders matches the number of parameters.
560 my $sql = $params->{sql};
561 my $offset = $params->{offset} || 0;
562 my $limit = $params->{limit} || C4::Context->config('report_results_limit') || 999999;
563 my $sql_params = defined $params->{sql_params} ? $params->{sql_params} : [];
564 my $report_id = $params->{report_id};
568 carp "execute_query() called without SQL argument";
572 Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
574 my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
575 return (undef, @{$errors}[0]) unless $is_sql_valid;
577 foreach my $sql_param ( @$sql_params ){
578 if ( $sql_param =~ m/\n/ ){
579 my @list = split /\n/, $sql_param;
581 foreach my $item ( @list ){
583 push @quoted_list, C4::Context->dbh->quote($item);
585 $sql_param = "(".join(",",@quoted_list).")";
589 my ($useroffset, $userlimit);
591 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
592 ($sql, $useroffset, $userlimit) = strip_limit($sql);
594 Koha::Logger->get->debug(
595 sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
596 $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
598 $offset += $useroffset;
599 if (defined($userlimit)) {
600 if ($offset + $limit > $userlimit ) {
601 $limit = $userlimit - $offset;
602 } elsif ( ! $offset && $limit < $userlimit ) {
606 $sql .= " LIMIT ?, ?";
608 my $dbh = C4::Context->dbh;
610 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
612 my $sth = $dbh->prepare($sql);
614 $sth->execute(@$sql_params, $offset, $limit);
618 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
622 =head2 save_report($sql,$name,$type,$notes)
624 Given some sql and a name this will saved it so that it can reused
625 Returns id of the newly created report
631 my $borrowernumber = $fields->{borrowernumber};
632 my $sql = $fields->{sql};
633 my $name = $fields->{name};
634 my $type = $fields->{type};
635 my $notes = $fields->{notes};
636 my $area = $fields->{area};
637 my $group = $fields->{group};
638 my $subgroup = $fields->{subgroup};
639 my $cache_expiry = $fields->{cache_expiry};
640 my $public = $fields->{public};
642 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
643 my $now = dt_from_string;
644 my $report = Koha::Report->new(
646 borrowernumber => $borrowernumber,
647 date_created => $now, # Must be moved to Koha::Report->store
648 last_modified => $now, # Must be moved to Koha::Report->store
650 report_name => $name,
651 report_area => $area,
652 report_group => $group,
653 report_subgroup => $subgroup,
656 cache_expiry => $cache_expiry,
665 my $id = shift || croak "No Id given";
667 my $sql = $fields->{sql};
668 my $name = $fields->{name};
669 my $notes = $fields->{notes};
670 my $group = $fields->{group};
671 my $subgroup = $fields->{subgroup};
672 my $cache_expiry = $fields->{cache_expiry};
673 my $public = $fields->{public};
675 $sql =~ s/(\s*\;\s*)$// if defined $sql; # removes trailing whitespace and /;/
676 my $report = Koha::Reports->find($id);
677 $report->last_modified(dt_from_string);
678 $report->savedsql($sql);
679 $report->report_name($name);
680 $report->notes($notes);
681 $report->report_group($group);
682 $report->report_subgroup($subgroup);
683 $report->cache_expiry($cache_expiry) if defined $cache_expiry;
684 $report->public($public);
686 if( $cache_expiry >= 2592000 ){
687 die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
694 my ( $id, $json ) = @_;
695 my $dbh = C4::Context->dbh();
697 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
698 |, undef, $id, $json );
703 my $dbh = C4::Context->dbh();
704 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
705 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
707 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
711 report_name => $report_name,
713 results => from_json( $json ),
714 date_run => $date_run,
721 foreach my $id (@ids) {
722 my $data = Koha::Reports->find($id);
723 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
725 my $dbh = C4::Context->dbh;
726 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
727 my $sth = $dbh->prepare($query);
728 return $sth->execute(@ids);
731 sub get_saved_reports_base_query {
732 my $area_name_sql_snippet = get_area_name_sql_snippet;
734 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
735 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
737 LEFT JOIN saved_reports r ON r.report_id = s.id
738 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
739 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)
740 LEFT OUTER JOIN borrowers b USING (borrowernumber)
744 sub get_saved_reports {
745 # $filter is either { date => $d, author => $a, keyword => $kw, }
746 # or $keyword. Optional.
748 $filter = { keyword => $filter } if $filter && !ref( $filter );
749 my ($group, $subgroup) = @_;
751 my $dbh = C4::Context->dbh();
752 my $query = get_saved_reports_base_query;
755 if (my $date = $filter->{date}) {
756 push @cond, "DATE(last_modified) = ? OR
758 push @args, $date, $date;
760 if (my $author = $filter->{author}) {
761 $author = "%$author%";
762 push @cond, "surname LIKE ? OR
764 push @args, $author, $author;
766 if (my $keyword = $filter->{keyword}) {
769 OR report_name LIKE ?
774 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
776 if ($filter->{group}) {
777 push @cond, "report_group = ?";
778 push @args, $filter->{group};
780 if ($filter->{subgroup}) {
781 push @cond, "report_subgroup = ?";
782 push @args, $filter->{subgroup};
785 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
786 $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";
787 $query .= " ORDER by date_created";
789 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
794 =head2 get_column_type($column)
796 This takes a column name of the format table.column and will return what type it is
797 (free text, set values, date)
801 sub get_column_type {
802 my ($tablecolumn) = @_;
803 my ($table,$column) = split(/\./,$tablecolumn);
804 my $dbh = C4::Context->dbh();
808 # mysql doesn't support a column selection, set column to %
810 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
811 while (my $info = $sth->fetchrow_hashref()){
812 if ($info->{'COLUMN_NAME'} eq $column){
814 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
815 $info->{'TYPE_NAME'} = 'distinct';
817 return $info->{'TYPE_NAME'};
822 =head2 get_distinct_values($column)
824 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
825 with the distinct values of the column
829 sub get_distinct_values {
830 my ($tablecolumn) = @_;
831 my ($table,$column) = split(/\./,$tablecolumn);
832 my $dbh = C4::Context->dbh();
834 "SELECT distinct($column) as availablevalues FROM $table";
835 my $sth = $dbh->prepare($query);
837 return $sth->fetchall_arrayref({});
840 sub save_dictionary {
841 my ( $name, $description, $sql, $area ) = @_;
842 my $dbh = C4::Context->dbh();
843 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
844 VALUES (?,?,?,?,now(),now())";
845 my $sth = $dbh->prepare($query);
846 $sth->execute($name,$description,$sql,$area) || return 0;
850 sub get_from_dictionary {
851 my ( $area, $id ) = @_;
852 my $dbh = C4::Context->dbh();
853 my $area_name_sql_snippet = get_area_name_sql_snippet;
855 SELECT d.*, $area_name_sql_snippet
856 FROM reports_dictionary d
860 $query .= " WHERE report_area = ?";
862 $query .= " WHERE id = ?";
864 my $sth = $dbh->prepare($query);
868 $sth->execute($area);
873 while ( my $data = $sth->fetchrow_hashref() ) {
879 sub delete_definition {
880 my ($id) = @_ or return;
881 my $dbh = C4::Context->dbh();
882 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
883 my $sth = $dbh->prepare($query);
887 =head2 get_sql($report_id)
889 Given a report id, return the SQL statement for that report.
890 Otherwise, it just returns.
895 my ($id) = @_ or return;
896 my $dbh = C4::Context->dbh();
897 my $query = "SELECT * FROM saved_sql WHERE id = ?";
898 my $sth = $dbh->prepare($query);
900 my $data=$sth->fetchrow_hashref();
901 return $data->{'savedsql'};
905 my ( $report_id ) = @_;
906 my $dbh = C4::Context->dbh;
907 return $dbh->selectall_arrayref(q|
908 SELECT id, report, date_run
911 |, { Slice => {} }, $report_id);
914 =head2 GetReservedAuthorisedValues
916 my %reserved_authorised_values = GetReservedAuthorisedValues();
918 Returns a hash containig all reserved words
922 sub GetReservedAuthorisedValues {
923 my %reserved_authorised_values =
924 map { $_ => 1 } ( 'date',
935 return \%reserved_authorised_values;
939 =head2 IsAuthorisedValueValid
941 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
943 Returns 1 if $authorised_value is on the reserved authorised values list or
944 in the authorised value categories defined in
948 sub IsAuthorisedValueValid {
950 my $authorised_value = shift;
951 my $reserved_authorised_values = GetReservedAuthorisedValues();
953 if ( exists $reserved_authorised_values->{$authorised_value} ||
954 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
961 =head2 GetParametersFromSQL
963 my @sql_parameters = GetParametersFromSQL($sql)
965 Returns an arrayref of hashes containing the keys name and authval
969 sub GetParametersFromSQL {
972 my @split = split(/<<|>>/,$sql);
973 my @sql_parameters = ();
975 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
976 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
977 $authval =~ s/\:all$// if $authval;
978 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
981 return \@sql_parameters;
984 =head2 ValidateSQLParameters
986 my @problematic_parameters = ValidateSQLParameters($sql)
988 Returns an arrayref of hashes containing the keys name and authval of
989 those SQL parameters that do not correspond to valid authorised names
993 sub ValidateSQLParameters {
996 my @problematic_parameters = ();
997 my $sql_parameters = GetParametersFromSQL($sql);
999 foreach my $sql_parameter (@$sql_parameters) {
1000 if ( defined $sql_parameter->{'authval'} ) {
1001 push @problematic_parameters, $sql_parameter unless
1002 IsAuthorisedValueValid($sql_parameter->{'authval'});
1006 return \@problematic_parameters;
1011 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1013 Take a report and use it to process a Template Toolkit formatted notice
1014 Returns arrayrefs containing prepared letters and errors respectively
1021 my $report_id = $params->{report_id};
1022 my $from = $params->{from};
1023 my $email_col = $params->{email} || 'email';
1024 my $module = $params->{module};
1025 my $code = $params->{code};
1026 my $branch = $params->{branch} || "";
1031 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1033 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1034 my $letter = Koha::Notice::Templates->find({
1037 branchcode => $branch,
1038 message_transport_type => 'email',
1040 $letter = $letter->unblessed;
1041 $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'};
1043 my $report = Koha::Reports->find( $report_id );
1044 my $sql = $report->savedsql;
1045 return ( { FATAL => "NO_REPORT" } ) unless $sql;
1047 #don't pass offset or limit, hardcoded limit of 999,999 will be used
1048 my ( $sth, $errors ) = execute_query( { sql => $sql, report_id => $report_id } );
1049 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1052 my $template = $letter->{content};
1054 while ( my $row = $sth->fetchrow_hashref() ) {
1056 my $err_count = scalar @errors;
1057 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1058 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1059 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1060 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1062 my $from_address = $from || $row->{from};
1063 my $to_address = $row->{$email_col};
1064 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1066 next if scalar @errors > $err_count; #If any problems, try next
1068 $letter->{content} = $content;
1069 $email->{borrowernumber} = $row->{borrowernumber};
1070 $email->{letter} = { %$letter };
1071 $email->{from_address} = $from_address;
1072 $email->{to_address} = $to_address;
1074 push ( @emails, $email );
1077 return ( \@emails, \@errors );
1085 my $content = ProcessRowTT($row_hashref, $template);
1087 Accepts a hashref containing values and processes them against Template Toolkit
1092 sub _process_row_TT {
1094 my ($row, $template) = @_;
1096 return 0 unless ($row && $template);
1098 my $processor = Template->new();
1099 $processor->process( \$template, $row, \$content);
1104 sub _get_display_value {
1105 my ( $original_value, $column ) = @_;
1106 if ( $column eq 'periodicity' ) {
1107 my $dbh = C4::Context->dbh();
1108 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1109 my $sth = $dbh->prepare($query);
1110 $sth->execute($original_value);
1111 return $sth->fetchrow;
1113 return $original_value;
1119 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1121 Convert a sql query using biblioitems.marcxml to use the new
1122 biblio_metadata.metadata field instead
1128 my $updated_sql = $sql;
1129 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1130 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1131 $updated_sql =~ s|marcxml|metadata|g;
1133 return $updated_sql;
1141 Chris Cormack <crc@liblime.com>