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>.
23 use JSON qw( from_json );
25 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27 use C4::Templates qw/themelanguage/;
34 use Koha::Notice::Templates;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Categories;
40 use Koha::SharedContent;
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
51 GetReservedAuthorisedValues
53 IsAuthorisedValueValid
61 C4::Reports::Guided - Module for generating guided reports
65 use C4::Reports::Guided;
73 =head2 get_report_areas
75 This will return a list of all the available report areas
79 sub get_area_name_sql_snippet {
81 [CIRC => "Circulation"],
84 [ACQ => "Acquisition"],
89 return "CASE report_area " .
90 join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) .
94 sub get_report_areas {
96 my $report_areas = [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ];
101 sub get_table_areas {
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
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' );
124 for ( my $i = 0 ; $i < 3 ; $i++ ) {
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
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} => {
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)} ),
155 my $g_sg = $groups_with_subgroups{$g}
156 or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ),
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
170 my $dbh = C4::Context->dbh();
171 my $query = "SHOW TABLES";
172 my $sth = $dbh->prepare($query);
175 while ( my $data = $sth->fetchrow_arrayref() ) {
176 push @tables, $data->[0];
183 =head2 get_columns($area)
185 This will return a list of all columns for a report area
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"};
199 foreach my $table (@$tables) {
200 my @columns = _get_columns($table,$cgi, $first);
202 push @allcolumns, @columns;
204 return ( \@allcolumns );
208 my ($tablename,$cgi, $first) = @_;
209 my $dbh = C4::Context->dbh();
210 my $sth = $dbh->prepare("show columns from $tablename");
213 my $column_defs = _get_column_defs($cgi);
215 $tablehash{'table'}=$tablename;
216 $tablehash{'__first__'} = $first;
217 push @columns, \%tablehash;
218 while ( my $data = $sth->fetchrow_arrayref() ) {
220 $temphash{'name'} = "$tablename.$data->[0]";
221 $temphash{'description'} = $column_defs->{"$tablename.$data->[0]"};
222 push @columns, \%temphash;
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.
237 my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_;
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' ],
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'],
254 my $keys = $keys{$area};
255 my %table_areas = get_table_areas;
256 my $tables = $table_areas{$area};
259 _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition );
264 my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_;
266 # $keys is an array of joining constraints
267 my $dbh = C4::Context->dbh();
268 my $joinedtables = join( ',', @$tables );
269 my $joinedcolumns = join( ',', @$columns );
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]) ";
277 $criteria =~ s/AND/WHERE/;
278 $query .= " $criteria";
281 my @definitions = split(',',$definition);
283 foreach my $def (@definitions){
284 my $defin=get_from_dictionary('',$def);
285 $deftext .=" ".$defin->[0]->{'saved_sql'};
287 if ($query =~ /WHERE/i){
291 $deftext =~ s/AND/WHERE/;
297 my @totcolumns = split( ',', $totals );
298 foreach my $total (@totcolumns) {
299 if ( $total =~ /\((.*)\)/ ) {
300 if ( $groupby eq '' ) {
301 $groupby = " GROUP BY $1";
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.
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
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',
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';
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);
356 foreach my $localcrit (@$crit) {
357 my ( $value, $type ) = split( /\|/, $localcrit );
358 my ( $table, $column ) = split( /\./, $value );
359 if ($type eq 'textrange') {
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') {
370 $temp{'name'} = $value;
372 $temp{'description'} = $column_defs->{$value};
373 push @criteria_array, \%temp;
375 elsif ($type eq 'daterange') {
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;
386 "SELECT distinct($column) as availablevalues FROM $table";
387 my $sth = $dbh->prepare($query);
390 # push the runtime choosing option
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
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 ); }
409 $temp{'name'} = $value;
410 $temp{'description'} = $column_defs->{$value};
411 $temp{'values'} = \@values;
413 push @criteria_array, \%temp;
416 return ( \@criteria_array );
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';
429 my $dbh = C4::Context->dbh;
433 my $RaiseError = $dbh->{RaiseError};
434 my $PrintError = $dbh->{PrintError};
435 $dbh->{RaiseError} = 1;
436 $dbh->{PrintError} = 0;
438 $sth = $dbh->prepare(qq{
440 ( $sql ) $derived_name
445 $dbh->{RaiseError} = $RaiseError;
446 $dbh->{PrintError} = $PrintError;
447 if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error
449 $sth = $dbh->prepare($sql);
453 # Loop through the complete results, fetching 1,000 rows at a time. This
454 # lowers memory requirements but increases execution time.
455 while (my $rows = $sth->fetchall_arrayref(undef, 1000)) {
461 my $results = $sth->fetch;
462 return $results ? $results->[0] : 0;
467 ($sth, $error) = execute_query($sql, $offset, $limit[, \@sql_params])
470 This function returns a DBI statement handler from which the caller can
471 fetch the results of the SQL passed via C<$sql>.
473 If passed any query other than a SELECT, or if there is a DB error,
474 C<$errors> is returned, and is a hashref containing the error after this
477 C<$error->{'sqlerr'}> contains the offending SQL keyword.
478 C<$error->{'queryerr'}> contains the native db engine error returned
481 C<$offset>, and C<$limit> are required parameters.
483 C<\@sql_params> is an optional list of parameter values to paste in.
484 The caller is responsible for making sure that C<$sql> has placeholders
485 and that the number placeholders matches the number of parameters.
489 # returns $sql, $offset, $limit
490 # $sql returned will be transformed to:
491 # ~ remove any LIMIT clause
492 # ~ repace SELECT clause w/ SELECT count(*)
494 sub select_2_select_count {
495 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
496 my ($sql) = strip_limit(shift) or return;
497 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
501 # This removes the LIMIT from the query so that a custom one can be specified.
503 # ($new_sql, $offset, $limit) = strip_limit($sql);
506 # $sql is the query to modify
507 # $new_sql is the resulting query
508 # $offset is the offset value, if the LIMIT was the two-argument form,
509 # 0 if it wasn't otherwise given.
510 # $limit is the limit value
513 # * This makes an effort to not break subqueries that have their own
514 # LIMIT specified. It does that by only removing a LIMIT if it comes after
515 # a WHERE clause (which isn't perfect, but at least should make more cases
516 # work - subqueries with a limit in the WHERE will still break.)
517 # * If your query doesn't have a WHERE clause then all LIMITs will be
518 # removed. This may break some subqueries, but is hopefully rare enough
519 # to not be a big issue.
524 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
526 # Two options: if there's no WHERE clause in the SQL, we simply capture
527 # any LIMIT that's there. If there is a WHERE, we make sure that we only
528 # capture a LIMIT after the last one. This prevents stomping on subqueries.
529 if ($sql !~ /\bWHERE\b/i) {
530 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
531 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
534 $res =~ m/.*\bWHERE\b/gsi;
535 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
536 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
542 my ( $sql, $offset, $limit, $sql_params, $report_id ) = @_;
544 $sql_params = [] unless defined $sql_params;
548 carp "execute_query() called without SQL argument";
551 $offset = 0 unless $offset;
552 $limit = 999999 unless $limit;
554 Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
556 my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
557 return (undef, @{$errors}[0]) unless $is_sql_valid;
559 foreach my $sql_param ( @$sql_params ){
560 if ( $sql_param =~ m/\n/ ){
561 my @list = split /\n/, $sql_param;
563 foreach my $item ( @list ){
565 push @quoted_list, C4::Context->dbh->quote($item);
567 $sql_param = "(".join(",",@quoted_list).")";
571 my ($useroffset, $userlimit);
573 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
574 ($sql, $useroffset, $userlimit) = strip_limit($sql);
576 Koha::Logger->get->debug(
577 sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
578 $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
580 $offset += $useroffset;
581 if (defined($userlimit)) {
582 if ($offset + $limit > $userlimit ) {
583 $limit = $userlimit - $offset;
584 } elsif ( ! $offset && $limit < $userlimit ) {
588 $sql .= " LIMIT ?, ?";
590 my $dbh = C4::Context->dbh;
592 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
594 my $sth = $dbh->prepare($sql);
596 $sth->execute(@$sql_params, $offset, $limit);
600 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
604 =head2 save_report($sql,$name,$type,$notes)
606 Given some sql and a name this will saved it so that it can reused
607 Returns id of the newly created report
613 my $borrowernumber = $fields->{borrowernumber};
614 my $sql = $fields->{sql};
615 my $name = $fields->{name};
616 my $type = $fields->{type};
617 my $notes = $fields->{notes};
618 my $area = $fields->{area};
619 my $group = $fields->{group};
620 my $subgroup = $fields->{subgroup};
621 my $cache_expiry = $fields->{cache_expiry};
622 my $public = $fields->{public};
624 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
625 my $now = dt_from_string;
626 my $report = Koha::Report->new(
628 borrowernumber => $borrowernumber,
629 date_created => $now, # Must be moved to Koha::Report->store
630 last_modified => $now, # Must be moved to Koha::Report->store
632 report_name => $name,
633 report_area => $area,
634 report_group => $group,
635 report_subgroup => $subgroup,
638 cache_expiry => $cache_expiry,
647 my $id = shift || croak "No Id given";
649 my $sql = $fields->{sql};
650 my $name = $fields->{name};
651 my $notes = $fields->{notes};
652 my $group = $fields->{group};
653 my $subgroup = $fields->{subgroup};
654 my $cache_expiry = $fields->{cache_expiry};
655 my $public = $fields->{public};
657 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
658 my $report = Koha::Reports->find($id);
659 $report->last_modified(dt_from_string);
660 $report->savedsql($sql);
661 $report->report_name($name);
662 $report->notes($notes);
663 $report->report_group($group);
664 $report->report_subgroup($subgroup);
665 $report->cache_expiry($cache_expiry) if defined $cache_expiry;
666 $report->public($public);
668 if( $cache_expiry >= 2592000 ){
669 die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
676 my ( $id, $json ) = @_;
677 my $dbh = C4::Context->dbh();
679 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
680 |, undef, $id, $json );
685 my $dbh = C4::Context->dbh();
686 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
687 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
689 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
693 report_name => $report_name,
695 results => from_json( $json ),
696 date_run => $date_run,
703 foreach my $id (@ids) {
704 my $data = Koha::Reports->find($id);
705 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
707 my $dbh = C4::Context->dbh;
708 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
709 my $sth = $dbh->prepare($query);
710 return $sth->execute(@ids);
713 sub get_saved_reports_base_query {
714 my $area_name_sql_snippet = get_area_name_sql_snippet;
716 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
717 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
719 LEFT JOIN saved_reports r ON r.report_id = s.id
720 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
721 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)
722 LEFT OUTER JOIN borrowers b USING (borrowernumber)
726 sub get_saved_reports {
727 # $filter is either { date => $d, author => $a, keyword => $kw, }
728 # or $keyword. Optional.
730 $filter = { keyword => $filter } if $filter && !ref( $filter );
731 my ($group, $subgroup) = @_;
733 my $dbh = C4::Context->dbh();
734 my $query = get_saved_reports_base_query;
737 if (my $date = $filter->{date}) {
738 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
739 push @cond, "DATE(last_modified) = ? OR
741 push @args, $date, $date, $date;
743 if (my $author = $filter->{author}) {
744 $author = "%$author%";
745 push @cond, "surname LIKE ? OR
747 push @args, $author, $author;
749 if (my $keyword = $filter->{keyword}) {
752 OR report_name LIKE ?
757 push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword;
759 if ($filter->{group}) {
760 push @cond, "report_group = ?";
761 push @args, $filter->{group};
763 if ($filter->{subgroup}) {
764 push @cond, "report_subgroup = ?";
765 push @args, $filter->{subgroup};
768 $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond;
769 $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";
770 $query .= " ORDER by date_created";
772 my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args);
777 =head2 get_column_type($column)
779 This takes a column name of the format table.column and will return what type it is
780 (free text, set values, date)
784 sub get_column_type {
785 my ($tablecolumn) = @_;
786 my ($table,$column) = split(/\./,$tablecolumn);
787 my $dbh = C4::Context->dbh();
791 # mysql doesn't support a column selection, set column to %
793 my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr;
794 while (my $info = $sth->fetchrow_hashref()){
795 if ($info->{'COLUMN_NAME'} eq $column){
797 if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){
798 $info->{'TYPE_NAME'} = 'distinct';
800 return $info->{'TYPE_NAME'};
805 =head2 get_distinct_values($column)
807 Given a column name, return an arrary ref of hashrefs suitable for use as a tmpl_loop
808 with the distinct values of the column
812 sub get_distinct_values {
813 my ($tablecolumn) = @_;
814 my ($table,$column) = split(/\./,$tablecolumn);
815 my $dbh = C4::Context->dbh();
817 "SELECT distinct($column) as availablevalues FROM $table";
818 my $sth = $dbh->prepare($query);
820 return $sth->fetchall_arrayref({});
823 sub save_dictionary {
824 my ( $name, $description, $sql, $area ) = @_;
825 my $dbh = C4::Context->dbh();
826 my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified)
827 VALUES (?,?,?,?,now(),now())";
828 my $sth = $dbh->prepare($query);
829 $sth->execute($name,$description,$sql,$area) || return 0;
833 sub get_from_dictionary {
834 my ( $area, $id ) = @_;
835 my $dbh = C4::Context->dbh();
836 my $area_name_sql_snippet = get_area_name_sql_snippet;
838 SELECT d.*, $area_name_sql_snippet
839 FROM reports_dictionary d
843 $query .= " WHERE report_area = ?";
845 $query .= " WHERE id = ?";
847 my $sth = $dbh->prepare($query);
851 $sth->execute($area);
856 while ( my $data = $sth->fetchrow_hashref() ) {
862 sub delete_definition {
863 my ($id) = @_ or return;
864 my $dbh = C4::Context->dbh();
865 my $query = "DELETE FROM reports_dictionary WHERE id = ?";
866 my $sth = $dbh->prepare($query);
870 =head2 get_sql($report_id)
872 Given a report id, return the SQL statement for that report.
873 Otherwise, it just returns.
878 my ($id) = @_ or return;
879 my $dbh = C4::Context->dbh();
880 my $query = "SELECT * FROM saved_sql WHERE id = ?";
881 my $sth = $dbh->prepare($query);
883 my $data=$sth->fetchrow_hashref();
884 return $data->{'savedsql'};
888 my ( $report_id ) = @_;
889 my $dbh = C4::Context->dbh;
890 return $dbh->selectall_arrayref(q|
891 SELECT id, report, date_run
894 |, { Slice => {} }, $report_id);
897 sub _get_column_defs {
900 my $columns_def_file = "columns.def";
901 my $htdocs = C4::Context->config('intrahtdocs');
902 my $section = 'intranet';
904 # We need the theme and the lang
905 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
906 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
908 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
909 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
910 while ( my $input = <$fh> ){
912 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
913 my ( $field, $translation ) = ( $1, $2 );
914 $columns{$field} = $translation;
921 =head2 GetReservedAuthorisedValues
923 my %reserved_authorised_values = GetReservedAuthorisedValues();
925 Returns a hash containig all reserved words
929 sub GetReservedAuthorisedValues {
930 my %reserved_authorised_values =
931 map { $_ => 1 } ( 'date',
937 'biblio_framework' );
939 return \%reserved_authorised_values;
943 =head2 IsAuthorisedValueValid
945 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
947 Returns 1 if $authorised_value is on the reserved authorised values list or
948 in the authorised value categories defined in
952 sub IsAuthorisedValueValid {
954 my $authorised_value = shift;
955 my $reserved_authorised_values = GetReservedAuthorisedValues();
957 if ( exists $reserved_authorised_values->{$authorised_value} ||
958 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
965 =head2 GetParametersFromSQL
967 my @sql_parameters = GetParametersFromSQL($sql)
969 Returns an arrayref of hashes containing the keys name and authval
973 sub GetParametersFromSQL {
976 my @split = split(/<<|>>/,$sql);
977 my @sql_parameters = ();
979 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
980 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
981 $authval =~ s/\:all$// if $authval;
982 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
985 return \@sql_parameters;
988 =head2 ValidateSQLParameters
990 my @problematic_parameters = ValidateSQLParameters($sql)
992 Returns an arrayref of hashes containing the keys name and authval of
993 those SQL parameters that do not correspond to valid authorised names
997 sub ValidateSQLParameters {
1000 my @problematic_parameters = ();
1001 my $sql_parameters = GetParametersFromSQL($sql);
1003 foreach my $sql_parameter (@$sql_parameters) {
1004 if ( defined $sql_parameter->{'authval'} ) {
1005 push @problematic_parameters, $sql_parameter unless
1006 IsAuthorisedValueValid($sql_parameter->{'authval'});
1010 return \@problematic_parameters;
1015 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1017 Take a report and use it to process a Template Toolkit formatted notice
1018 Returns arrayrefs containing prepared letters and errors respectively
1025 my $report_id = $params->{report_id};
1026 my $from = $params->{from};
1027 my $email_col = $params->{email} || 'email';
1028 my $module = $params->{module};
1029 my $code = $params->{code};
1030 my $branch = $params->{branch} || "";
1035 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1037 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1038 my $letter = Koha::Notice::Templates->find({
1041 branchcode => $branch,
1042 message_transport_type => 'email',
1044 $letter = $letter->unblessed;
1046 my $report = Koha::Reports->find( $report_id );
1047 my $sql = $report->savedsql;
1048 return ( { FATAL => "NO_REPORT" } ) unless $sql;
1050 my ( $sth, $errors ) = execute_query( $sql ); #don't pass offset or limit, hardcoded limit of 999,999 will be used
1051 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1054 my $template = $letter->{content};
1056 while ( my $row = $sth->fetchrow_hashref() ) {
1058 my $err_count = scalar @errors;
1059 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1060 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1061 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1062 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1064 my $from_address = $from || $row->{from};
1065 my $to_address = $row->{$email_col};
1066 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1068 next if scalar @errors > $err_count; #If any problems, try next
1070 $letter->{content} = $content;
1071 $email->{borrowernumber} = $row->{borrowernumber};
1072 $email->{letter} = { %$letter };
1073 $email->{from_address} = $from_address;
1074 $email->{to_address} = $to_address;
1076 push ( @emails, $email );
1079 return ( \@emails, \@errors );
1087 my $content = ProcessRowTT($row_hashref, $template);
1089 Accepts a hashref containing values and processes them against Template Toolkit
1094 sub _process_row_TT {
1096 my ($row, $template) = @_;
1098 return 0 unless ($row && $template);
1100 my $processor = Template->new();
1101 $processor->process( \$template, $row, \$content);
1106 sub _get_display_value {
1107 my ( $original_value, $column ) = @_;
1108 if ( $column eq 'periodicity' ) {
1109 my $dbh = C4::Context->dbh();
1110 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1111 my $sth = $dbh->prepare($query);
1112 $sth->execute($original_value);
1113 return $sth->fetchrow;
1115 return $original_value;
1121 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1123 Convert a sql query using biblioitems.marcxml to use the new
1124 biblio_metadata.metadata field instead
1130 my $updated_sql = $sql;
1131 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1132 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1133 $updated_sql =~ s|marcxml|metadata|g;
1135 return $updated_sql;
1143 Chris Cormack <crc@liblime.com>