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;
467 =head2 select_2_select_count
469 returns $sql, $offset, $limit
470 $sql returned will be transformed to:
471 ~ remove any LIMIT clause
472 ~ replace SELECT clause w/ SELECT count(*)
476 sub select_2_select_count {
477 # Modify the query passed in to create a count query... (I think this covers all cases -crn)
478 my ($sql) = strip_limit(shift) or return;
479 $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig;
484 This removes the LIMIT from the query so that a custom one can be specified.
486 ($new_sql, $offset, $limit) = strip_limit($sql);
489 $sql is the query to modify
490 $new_sql is the resulting query
491 $offset is the offset value, if the LIMIT was the two-argument form,
492 0 if it wasn't otherwise given.
493 $limit is the limit value
496 * This makes an effort to not break subqueries that have their own
497 LIMIT specified. It does that by only removing a LIMIT if it comes after
498 a WHERE clause (which isn't perfect, but at least should make more cases
499 work - subqueries with a limit in the WHERE will still break.)
500 * If your query doesn't have a WHERE clause then all LIMITs will be
501 removed. This may break some subqueries, but is hopefully rare enough
502 to not be a big issue.
510 return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i;
512 # Two options: if there's no WHERE clause in the SQL, we simply capture
513 # any LIMIT that's there. If there is a WHERE, we make sure that we only
514 # capture a LIMIT after the last one. This prevents stomping on subqueries.
515 if ($sql !~ /\bWHERE\b/i) {
516 (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig;
517 return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1));
520 $res =~ m/.*\bWHERE\b/gsi;
521 $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is;
522 return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2));
528 ($sth, $error) = execute_query({
532 sql_params => \@sql_params],
533 report_id => $report_id
537 This function returns a DBI statement handler from which the caller can
538 fetch the results of the SQL passed via C<$sql>.
540 If passed any query other than a SELECT, or if there is a DB error,
541 C<$errors> is returned, and is a hashref containing the error after this
544 C<$error->{'sqlerr'}> contains the offending SQL keyword.
545 C<$error->{'queryerr'}> contains the native db engine error returned
548 C<$offset>, and C<$limit> are required parameters.
550 C<\@sql_params> is an optional list of parameter values to paste in.
551 The caller is responsible for making sure that C<$sql> has placeholders
552 and that the number placeholders matches the number of parameters.
559 my $sql = $params->{sql};
560 my $offset = $params->{offset} || 0;
561 my $limit = $params->{limit} || 999999;
562 my $sql_params = defined $params->{sql_params} ? $params->{sql_params} : [];
563 my $report_id = $params->{report_id};
567 carp "execute_query() called without SQL argument";
571 Koha::Logger->get->debug("Report - execute_query($sql, $offset, $limit)");
573 my ( $is_sql_valid, $errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
574 return (undef, @{$errors}[0]) unless $is_sql_valid;
576 foreach my $sql_param ( @$sql_params ){
577 if ( $sql_param =~ m/\n/ ){
578 my @list = split /\n/, $sql_param;
580 foreach my $item ( @list ){
582 push @quoted_list, C4::Context->dbh->quote($item);
584 $sql_param = "(".join(",",@quoted_list).")";
588 my ($useroffset, $userlimit);
590 # Grab offset/limit from user supplied LIMIT and drop the LIMIT so we can control pagination
591 ($sql, $useroffset, $userlimit) = strip_limit($sql);
593 Koha::Logger->get->debug(
594 sprintf "User has supplied (OFFSET,) LIMIT = %s, %s",
595 $useroffset, ( defined($userlimit) ? $userlimit : 'UNDEF' ) );
597 $offset += $useroffset;
598 if (defined($userlimit)) {
599 if ($offset + $limit > $userlimit ) {
600 $limit = $userlimit - $offset;
601 } elsif ( ! $offset && $limit < $userlimit ) {
605 $sql .= " LIMIT ?, ?";
607 my $dbh = C4::Context->dbh;
609 $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id;
611 my $sth = $dbh->prepare($sql);
613 $sth->execute(@$sql_params, $offset, $limit);
617 return ( $sth, { queryerr => $sth->errstr } ) if ($sth->err);
621 =head2 save_report($sql,$name,$type,$notes)
623 Given some sql and a name this will saved it so that it can reused
624 Returns id of the newly created report
630 my $borrowernumber = $fields->{borrowernumber};
631 my $sql = $fields->{sql};
632 my $name = $fields->{name};
633 my $type = $fields->{type};
634 my $notes = $fields->{notes};
635 my $area = $fields->{area};
636 my $group = $fields->{group};
637 my $subgroup = $fields->{subgroup};
638 my $cache_expiry = $fields->{cache_expiry};
639 my $public = $fields->{public};
641 $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/
642 my $now = dt_from_string;
643 my $report = Koha::Report->new(
645 borrowernumber => $borrowernumber,
646 date_created => $now, # Must be moved to Koha::Report->store
647 last_modified => $now, # Must be moved to Koha::Report->store
649 report_name => $name,
650 report_area => $area,
651 report_group => $group,
652 report_subgroup => $subgroup,
655 cache_expiry => $cache_expiry,
664 my $id = shift || croak "No Id given";
666 my $sql = $fields->{sql};
667 my $name = $fields->{name};
668 my $notes = $fields->{notes};
669 my $group = $fields->{group};
670 my $subgroup = $fields->{subgroup};
671 my $cache_expiry = $fields->{cache_expiry};
672 my $public = $fields->{public};
674 $sql =~ s/(\s*\;\s*)$// if defined $sql; # removes trailing whitespace and /;/
675 my $report = Koha::Reports->find($id);
676 $report->last_modified(dt_from_string);
677 $report->savedsql($sql);
678 $report->report_name($name);
679 $report->notes($notes);
680 $report->report_group($group);
681 $report->report_subgroup($subgroup);
682 $report->cache_expiry($cache_expiry) if defined $cache_expiry;
683 $report->public($public);
685 if( $cache_expiry >= 2592000 ){
686 die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh
693 my ( $id, $json ) = @_;
694 my $dbh = C4::Context->dbh();
696 INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() );
697 |, undef, $id, $json );
702 my $dbh = C4::Context->dbh();
703 my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q|
704 SELECT ss.report_name, ss.notes, sr.report, sr.date_run
706 LEFT JOIN saved_reports sr ON sr.report_id = ss.id
710 report_name => $report_name,
712 results => from_json( $json ),
713 date_run => $date_run,
720 foreach my $id (@ids) {
721 my $data = Koha::Reports->find($id);
722 logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog");
724 my $dbh = C4::Context->dbh;
725 my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')';
726 my $sth = $dbh->prepare($query);
727 return $sth->execute(@ids);
730 sub get_saved_reports_base_query {
731 my $area_name_sql_snippet = get_area_name_sql_snippet;
733 SELECT s.*, $area_name_sql_snippet, av_g.lib AS groupname, av_sg.lib AS subgroupname,
734 b.firstname AS borrowerfirstname, b.surname AS borrowersurname
736 LEFT JOIN saved_reports r ON r.report_id = s.id
737 LEFT OUTER JOIN authorised_values av_g ON (av_g.category = 'REPORT_GROUP' AND av_g.authorised_value = s.report_group)
738 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)
739 LEFT OUTER JOIN borrowers b USING (borrowernumber)
743 sub get_saved_reports {
744 # $filter is either { date => $d, author => $a, keyword => $kw, }
745 # or $keyword. Optional.
747 $filter = { keyword => $filter } if $filter && !ref( $filter );
748 my ($group, $subgroup) = @_;
750 my $dbh = C4::Context->dbh();
751 my $query = get_saved_reports_base_query;
754 if (my $date = $filter->{date}) {
755 $date = eval { output_pref( { dt => dt_from_string( $date ), dateonly => 1, dateformat => 'iso' }); };
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 sub _get_column_defs {
917 my $columns_def_file = "columns.def";
918 my $htdocs = C4::Context->config('intrahtdocs');
919 my $section = 'intranet';
921 # We need the theme and the lang
922 # Since columns.def is not in the modules directory, we cannot sent it for the $tmpl var
923 my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi);
925 my $full_path_to_columns_def_file="$htdocs/$theme/$lang/$columns_def_file";
926 open (my $fh, '<:encoding(utf-8)', $full_path_to_columns_def_file);
927 while ( my $input = <$fh> ){
929 if ( $input =~ m|<field name="(.*)">(.*)</field>| ) {
930 my ( $field, $translation ) = ( $1, $2 );
931 $columns{$field} = $translation;
938 =head2 GetReservedAuthorisedValues
940 my %reserved_authorised_values = GetReservedAuthorisedValues();
942 Returns a hash containig all reserved words
946 sub GetReservedAuthorisedValues {
947 my %reserved_authorised_values =
948 map { $_ => 1 } ( 'date',
959 return \%reserved_authorised_values;
963 =head2 IsAuthorisedValueValid
965 my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value)
967 Returns 1 if $authorised_value is on the reserved authorised values list or
968 in the authorised value categories defined in
972 sub IsAuthorisedValueValid {
974 my $authorised_value = shift;
975 my $reserved_authorised_values = GetReservedAuthorisedValues();
977 if ( exists $reserved_authorised_values->{$authorised_value} ||
978 Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
985 =head2 GetParametersFromSQL
987 my @sql_parameters = GetParametersFromSQL($sql)
989 Returns an arrayref of hashes containing the keys name and authval
993 sub GetParametersFromSQL {
996 my @split = split(/<<|>>/,$sql);
997 my @sql_parameters = ();
999 for ( my $i = 0; $i < ($#split/2) ; $i++ ) {
1000 my ($name,$authval) = split(/\|/,$split[$i*2+1]);
1001 $authval =~ s/\:all$// if $authval;
1002 push @sql_parameters, { 'name' => $name, 'authval' => $authval };
1005 return \@sql_parameters;
1008 =head2 ValidateSQLParameters
1010 my @problematic_parameters = ValidateSQLParameters($sql)
1012 Returns an arrayref of hashes containing the keys name and authval of
1013 those SQL parameters that do not correspond to valid authorised names
1017 sub ValidateSQLParameters {
1020 my @problematic_parameters = ();
1021 my $sql_parameters = GetParametersFromSQL($sql);
1023 foreach my $sql_parameter (@$sql_parameters) {
1024 if ( defined $sql_parameter->{'authval'} ) {
1025 push @problematic_parameters, $sql_parameter unless
1026 IsAuthorisedValueValid($sql_parameter->{'authval'});
1030 return \@problematic_parameters;
1035 my ( $emails, $arrayrefs ) = EmailReport($report_id, $letter_code, $module, $branch, $email)
1037 Take a report and use it to process a Template Toolkit formatted notice
1038 Returns arrayrefs containing prepared letters and errors respectively
1045 my $report_id = $params->{report_id};
1046 my $from = $params->{from};
1047 my $email_col = $params->{email} || 'email';
1048 my $module = $params->{module};
1049 my $code = $params->{code};
1050 my $branch = $params->{branch} || "";
1055 return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code);
1057 return ( undef, [{ FATAL => "NO_LETTER" }] ) unless
1058 my $letter = Koha::Notice::Templates->find({
1061 branchcode => $branch,
1062 message_transport_type => 'email',
1064 $letter = $letter->unblessed;
1065 $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'};
1067 my $report = Koha::Reports->find( $report_id );
1068 my $sql = $report->savedsql;
1069 return ( { FATAL => "NO_REPORT" } ) unless $sql;
1071 #don't pass offset or limit, hardcoded limit of 999,999 will be used
1072 my ( $sth, $errors ) = execute_query( { sql => $sql, report_id => $report_id } );
1073 return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors;
1076 my $template = $letter->{content};
1078 while ( my $row = $sth->fetchrow_hashref() ) {
1080 my $err_count = scalar @errors;
1081 push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber};
1082 push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} );
1083 push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} );
1084 push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}});
1086 my $from_address = $from || $row->{from};
1087 my $to_address = $row->{$email_col};
1088 push ( @errors, { NOT_PARSE => $counter } ) unless my $content = _process_row_TT( $row, $template );
1090 next if scalar @errors > $err_count; #If any problems, try next
1092 $letter->{content} = $content;
1093 $email->{borrowernumber} = $row->{borrowernumber};
1094 $email->{letter} = { %$letter };
1095 $email->{from_address} = $from_address;
1096 $email->{to_address} = $to_address;
1098 push ( @emails, $email );
1101 return ( \@emails, \@errors );
1109 my $content = ProcessRowTT($row_hashref, $template);
1111 Accepts a hashref containing values and processes them against Template Toolkit
1116 sub _process_row_TT {
1118 my ($row, $template) = @_;
1120 return 0 unless ($row && $template);
1122 my $processor = Template->new();
1123 $processor->process( \$template, $row, \$content);
1128 sub _get_display_value {
1129 my ( $original_value, $column ) = @_;
1130 if ( $column eq 'periodicity' ) {
1131 my $dbh = C4::Context->dbh();
1132 my $query = "SELECT description FROM subscription_frequencies WHERE id = ?";
1133 my $sth = $dbh->prepare($query);
1134 $sth->execute($original_value);
1135 return $sth->fetchrow;
1137 return $original_value;
1143 my $updated_sql = C4::Reports::Guided::convert_sql( $sql );
1145 Convert a sql query using biblioitems.marcxml to use the new
1146 biblio_metadata.metadata field instead
1152 my $updated_sql = $sql;
1153 if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) {
1154 $updated_sql =~ s|biblioitems|biblio_metadata|g;
1155 $updated_sql =~ s|marcxml|metadata|g;
1157 return $updated_sql;
1165 Chris Cormack <crc@liblime.com>