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));
545 my $sql = $params->{sql};
546 my $offset = $params->{offset} || 0;
547 my $limit = $params->{limit} || 999999;
548 my $sql_params = defined $params->{sql_params} ? $params->{sql_params} : [];
549 my $report_id = $params->{report_id};
553 carp "execute_query() called without SQL argument";
557 Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
559 my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
560 return (undef, @{$errors}[0]) unless $is_sql_valid;
562 foreach my $sql_param ( @$sql_params ){
563 if ( $sql_param =~ m/\n/ ){
564 my @list = split /\n/, $sql_param;
566 foreach my $item ( @list ){
568 push @quoted_list, C4::Context->dbh->quote($item);
570 $sql_param = "(".join(",",@quoted_list).")";
574 my ($useroffset, $userlimit);
576 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
577 ($sql, $useroffset, $userlimit) = strip_limit($sql);
579 Koha::Logger->get->debug(
580 sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
581 $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
583 $offset += $useroffset;
584 if (defined($userlimit)) {
585 if ($offset + $limit > $userlimit ) {
586 $limit = $userlimit - $offset;
587 } elsif ( ! $offset && $limit < $userlimit ) {
591 $sql .= " LIMIT ?, ?";
593 my $dbh = C4::Context->dbh;
595 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
597 my $sth = $dbh->prepare($sql);
599 $sth->execute(@$sql_params, $offset, $limit);
603 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
607 =head2 save_report($sql,$name,$type,$notes)
609 Given some sql and a name this will saved it so that it can reused
610 Returns id of the newly created report
616 my $borrowernumber = $fields->{borrowernumber};
617 my $sql = $fields->{sql};
618 my $name = $fields->{name};
619 my $type = $fields->{type};
620 my $notes = $fields->{notes};
621 my $area = $fields->{area};
622 my $group = $fields->{group};
623 my $subgroup = $fields->{subgroup};
624 my $cache_expiry = $fields->{cache_expiry};
625 my $public = $fields->{public};
627 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
628 my $now = dt_from_string;
629 my $report = Koha::Report->new(
631 borrowernumber => $borrowernumber,
632 date_created => $now, # Must be moved to Koha::Report->store
633 last_modified => $now, # Must be moved to Koha::Report->store
635 report_name => $name,
636 report_area => $area,
637 report_group => $group,
638 report_subgroup => $subgroup,
641 cache_expiry => $cache_expiry,
650 my $id = shift || croak "No Id given";
652 my $sql = $fields->{sql};
653 my $name = $fields->{name};
654 my $notes = $fields->{notes};
655 my $group = $fields->{group};
656 my $subgroup = $fields->{subgroup};
657 my $cache_expiry = $fields->{cache_expiry};
658 my $public = $fields->{public};
660 $sql =~ s/(\s*\;\s*)$// if defined $sql; # removes trailing whitespace and /;/
661 my $report = Koha::Reports->find($id);
662 $report->last_modified(dt_from_string);
663 $report->savedsql($sql);
664 $report->report_name($name);
665 $report->notes($notes);
666 $report->report_group($group);
667 $report->report_subgroup($subgroup);
668 $report->cache_expiry($cache_expiry) if defined $cache_expiry;
669 $report->public($public);
671 if( $cache_expiry >= 2592000 ){
672 die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
679 my ( $id, $json ) = @_;
680 my $dbh = C4::Context->dbh();
682 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
683 |, undef, $id, $json );
688 my $dbh = C4::Context->dbh();
689 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
690 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
692 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
696 report_name => $report_name,
698 results => from_json( $json ),
699 date_run => $date_run,
706 foreach my $id (@ids) {
707 my $data = Koha::Reports->find($id);
708 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
710 my $dbh = C4::Context->dbh;
711 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
712 my $sth = $dbh->prepare($query);
713 return $sth->execute(@ids);
716 sub get_saved_reports_base_query {
717 my $area_name_sql_snippet = get_area_name_sql_snippet;
719 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
720 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
722 LEFT JOIN saved_reports r ON r.report_id = s.id
723 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
724 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)
725 LEFT OUTER JOIN borrowers b USING (borrowernumber)
729 sub get_saved_reports {
730 # $filter is either { date => $d, author => $a, keyword => $kw, }
731 # or $keyword. Optional.
733 $filter = { keyword => $filter } if $filter && !ref( $filter );
734 my ($group, $subgroup) = @_;
736 my $dbh = C4::Context->dbh();
737 my $query = get_saved_reports_base_query;
740 if (my $date = $filter->{date}) {
741 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
742 push @cond, "DATE(last_modified) = ? OR
744 push @args, $date, $date;
746 if (my $author = $filter->{author}) {
747 $author = "%$author%";
748 push @cond, "surname LIKE ? OR
750 push @args, $author, $author;
752 if (my $keyword = $filter->{keyword}) {
755 OR report_name LIKE ?
760 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
762 if ($filter->{group}) {
763 push @cond, "report_group = ?";
764 push @args, $filter->{group};
766 if ($filter->{subgroup}) {
767 push @cond, "report_subgroup = ?";
768 push @args, $filter->{subgroup};
771 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
772 $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";
773 $query .= " ORDER by date_created";
775 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
780 =head2 get_column_type($column)
782 This takes a column name of the format table.column and will return what type it is
783 (free text, set values, date)
787 sub get_column_type {
788 my ($tablecolumn) = @_;
789 my ($table,$column) = split(/\./,$tablecolumn);
790 my $dbh = C4::Context->dbh();
794 # mysql doesn't support a column selection, set column to %
796 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
797 while (my $info = $sth->fetchrow_hashref()){
798 if ($info->{'COLUMN_NAME'} eq $column){
800 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
801 $info->{'TYPE_NAME'} = 'distinct';
803 return $info->{'TYPE_NAME'};
808 =head2 get_distinct_values($column)
810 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
811 with the distinct values of the column
815 sub get_distinct_values {
816 my ($tablecolumn) = @_;
817 my ($table,$column) = split(/\./,$tablecolumn);
818 my $dbh = C4::Context->dbh();
820 "SELECT distinct($column) as availablevalues FROM $table";
821 my $sth = $dbh->prepare($query);
823 return $sth->fetchall_arrayref({});
826 sub save_dictionary {
827 my ( $name, $description, $sql, $area ) = @_;
828 my $dbh = C4::Context->dbh();
829 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
830 VALUES (?,?,?,?,now(),now())";
831 my $sth = $dbh->prepare($query);
832 $sth->execute($name,$description,$sql,$area) || return 0;
836 sub get_from_dictionary {
837 my ( $area, $id ) = @_;
838 my $dbh = C4::Context->dbh();
839 my $area_name_sql_snippet = get_area_name_sql_snippet;
841 SELECT d.*, $area_name_sql_snippet
842 FROM reports_dictionary d
846 $query .= " WHERE report_area = ?";
848 $query .= " WHERE id = ?";
850 my $sth = $dbh->prepare($query);
854 $sth->execute($area);
859 while ( my $data = $sth->fetchrow_hashref() ) {
865 sub delete_definition {
866 my ($id) = @_ or return;
867 my $dbh = C4::Context->dbh();
868 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
869 my $sth = $dbh->prepare($query);
873 =head2 get_sql($report_id)
875 Given a report id, return the SQL statement for that report.
876 Otherwise, it just returns.
881 my ($id) = @_ or return;
882 my $dbh = C4::Context->dbh();
883 my $query = "SELECT * FROM saved_sql WHERE id = ?";
884 my $sth = $dbh->prepare($query);
886 my $data=$sth->fetchrow_hashref();
887 return $data->{'savedsql'};
891 my ( $report_id ) = @_;
892 my $dbh = C4::Context->dbh;
893 return $dbh->selectall_arrayref(q|
894 SELECT id, report, date_run
897 |, { Slice => {} }, $report_id);
900 sub _get_column_defs {
903 my $columns_def_file = "columns.def";
904 my $htdocs = C4::Context->config('intrahtdocs');
905 my $section = 'intranet';
907 # We need the theme and the lang
908 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
909 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
911 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
912 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
913 while ( my $input = <$fh> ){
915 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
916 my ( $field, $translation ) = ( $1, $2 );
917 $columns{$field} = $translation;
924 =head2 GetReservedAuthorisedValues
926 my %reserved_authorised_values = GetReservedAuthorisedValues();
928 Returns a hash containig all reserved words
932 sub GetReservedAuthorisedValues {
933 my %reserved_authorised_values =
934 map { $_ => 1 } ( 'date',
945 return \%reserved_authorised_values;
949 =head2 IsAuthorisedValueValid
951 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
953 Returns 1 if $authorised_value is on the reserved authorised values list or
954 in the authorised value categories defined in
958 sub IsAuthorisedValueValid {
960 my $authorised_value = shift;
961 my $reserved_authorised_values = GetReservedAuthorisedValues();
963 if ( exists $reserved_authorised_values->{$authorised_value} ||
964 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
971 =head2 GetParametersFromSQL
973 my @sql_parameters = GetParametersFromSQL($sql)
975 Returns an arrayref of hashes containing the keys name and authval
979 sub GetParametersFromSQL {
982 my @split = split(/<<|>>/,$sql);
983 my @sql_parameters = ();
985 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
986 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
987 $authval =~ s/\:all$// if $authval;
988 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
991 return \@sql_parameters;
994 =head2 ValidateSQLParameters
996 my @problematic_parameters = ValidateSQLParameters($sql)
998 Returns an arrayref of hashes containing the keys name and authval of
999 those SQL parameters that do not correspond to valid authorised names
1003 sub ValidateSQLParameters {
1006 my @problematic_parameters = ();
1007 my $sql_parameters = GetParametersFromSQL($sql);
1009 foreach my $sql_parameter (@$sql_parameters) {
1010 if ( defined $sql_parameter->{'authval'} ) {
1011 push @problematic_parameters, $sql_parameter unless
1012 IsAuthorisedValueValid($sql_parameter->{'authval'});
1016 return \@problematic_parameters;
1021 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1023 Take a report and use it to process a Template Toolkit formatted notice
1024 Returns arrayrefs containing prepared letters and errors respectively
1031 my $report_id = $params->{report_id};
1032 my $from = $params->{from};
1033 my $email_col = $params->{email} || 'email';
1034 my $module = $params->{module};
1035 my $code = $params->{code};
1036 my $branch = $params->{branch} || "";
1041 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1043 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1044 my $letter = Koha::Notice::Templates->find({
1047 branchcode => $branch,
1048 message_transport_type => 'email',
1050 $letter = $letter->unblessed;
1051 $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'};
1053 my $report = Koha::Reports->find( $report_id );
1054 my $sql = $report->savedsql;
1055 return ( { FATAL => "NO_REPORT" } ) unless $sql;
1057 #don't pass offset or limit, hardcoded limit of 999,999 will be used
1058 my ( $sth, $errors ) = execute_query( { sql => $sql, report_id => $report_id } );
1059 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1062 my $template = $letter->{content};
1064 while ( my $row = $sth->fetchrow_hashref() ) {
1066 my $err_count = scalar @errors;
1067 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1068 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1069 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1070 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1072 my $from_address = $from || $row->{from};
1073 my $to_address = $row->{$email_col};
1074 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1076 next if scalar @errors > $err_count; #If any problems, try next
1078 $letter->{content} = $content;
1079 $email->{borrowernumber} = $row->{borrowernumber};
1080 $email->{letter} = { %$letter };
1081 $email->{from_address} = $from_address;
1082 $email->{to_address} = $to_address;
1084 push ( @emails, $email );
1087 return ( \@emails, \@errors );
1095 my $content = ProcessRowTT($row_hashref, $template);
1097 Accepts a hashref containing values and processes them against Template Toolkit
1102 sub _process_row_TT {
1104 my ($row, $template) = @_;
1106 return 0 unless ($row && $template);
1108 my $processor = Template->new();
1109 $processor->process( \$template, $row, \$content);
1114 sub _get_display_value {
1115 my ( $original_value, $column ) = @_;
1116 if ( $column eq 'periodicity' ) {
1117 my $dbh = C4::Context->dbh();
1118 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1119 my $sth = $dbh->prepare($query);
1120 $sth->execute($original_value);
1121 return $sth->fetchrow;
1123 return $original_value;
1129 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1131 Convert a sql query using biblioitems.marcxml to use the new
1132 biblio_metadata.metadata field instead
1138 my $updated_sql = $sql;
1139 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1140 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1141 $updated_sql =~ s|marcxml|metadata|g;
1143 return $updated_sql;
1151 Chris Cormack <crc@liblime.com>