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 Text::CSV::Encoded;
23 use Encode qw( decode );
26 use C4::Reports::Guided qw( delete_report get_report_areas convert_sql update_sql get_saved_reports get_results ValidateSQLParameters format_results get_report_types get_columns get_from_dictionary get_criteria build_query save_report execute_query nb_rows get_report_groups );
28 use C4::Auth qw( get_template_and_user get_session );
29 use C4::Output qw( pagination_bar output_html_with_http_headers );
32 use C4::Log qw( logaction );
33 use Koha::DateUtils qw( dt_from_string output_pref );
34 use Koha::AuthorisedValue;
35 use Koha::AuthorisedValues;
36 use Koha::BiblioFrameworks;
38 use Koha::Patron::Categories;
39 use Koha::SharedContent;
40 use Koha::Util::OpenDocument qw( generate_ods );
41 use C4::ClassSource qw( GetClassSources );
49 Script to control the guided report creation
54 my $usecache = Koha::Caches->get_instance->memcached_cache;
56 my $phase = $input->param('phase') // '';
58 if ( ( $phase eq 'Build new' ) || ( $phase eq 'Create report from SQL' ) || ( $phase eq 'Edit SQL' )
59 || ( $phase eq 'Build new from existing' ) ) {
60 $flagsrequired = 'create_reports';
62 elsif ( $phase eq 'Use saved' ) {
63 $flagsrequired = 'execute_reports';
65 elsif ( $phase eq 'Delete Saved' ) {
66 $flagsrequired = 'delete_reports';
72 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
74 template_name => "reports/guided_reports_start.tt",
77 flagsrequired => { reports => $flagsrequired },
80 my $session = $cookie ? get_session($cookie->value) : undef;
83 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
85 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
86 $session->param('report_filter', $filter) if $session;
87 $template->param( 'filter_set' => 1 );
89 elsif ($session and not $input->param('clear_filters')) {
90 $filter = $session->param('report_filter');
93 my $op = $input->param('op') || q||;
97 $template->param( 'start' => 1 );
100 elsif ( $phase eq 'Build new' ) {
102 $template->param( 'build1' => 1 );
104 'areas' => get_report_areas(),
105 'usecache' => $usecache,
106 'cache_expiry' => 300,
109 } elsif ( $phase eq 'Use saved' ) {
111 if ( $op eq 'convert' ) {
112 my $report_id = $input->param('report_id');
113 my $report = Koha::Reports->find($report_id);
115 my $updated_sql = C4::Reports::Guided::convert_sql( $report->savedsql );
116 C4::Reports::Guided::update_sql(
120 name => $report->report_name,
121 group => $report->report_group,
122 subgroup => $report->report_subgroup,
123 notes => $report->notes,
124 public => $report->public,
125 cache_expiry => $report->cache_expiry,
128 $template->param( report_converted => $report->report_name );
133 # get list of reports and display them
134 my $group = $input->param('group');
135 my $subgroup = $input->param('subgroup');
136 $filter->{group} = $group;
137 $filter->{subgroup} = $subgroup;
138 my $reports = get_saved_reports($filter);
139 my $has_obsolete_reports;
140 for my $report ( @$reports ) {
141 $report->{results} = C4::Reports::Guided::get_results( $report->{id} );
142 if ( $report->{savedsql} =~ m|biblioitems| and $report->{savedsql} =~ m|marcxml| ) {
143 $report->{seems_obsolete} = 1;
144 $has_obsolete_reports++;
148 'manamsg' => $input->param('manamsg') || '',
150 'savedreports' => $reports,
151 'usecache' => $usecache,
152 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ),
154 has_obsolete_reports => $has_obsolete_reports,
158 elsif ( $phase eq 'Delete Multiple') {
159 my @ids = $input->multi_param('ids');
160 delete_report( @ids );
161 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
165 elsif ( $phase eq 'Delete Saved') {
167 # delete a report from the saved reports list
168 my $ids = $input->param('reports');
170 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
174 elsif ( $phase eq 'Show SQL'){
176 my $id = $input->param('reports');
177 my $report = Koha::Reports->find($id);
180 'reportname' => $report->report_name,
181 'notes' => $report->notes,
182 'sql' => $report->savedsql,
184 'mana_success' => $input->param('mana_success'),
185 'mana_success' => scalar $input->param('mana_success'),
186 'mana_id' => $report->{mana_id},
187 'mana_comments' => $report->{comments}
191 elsif ( $phase eq 'Edit SQL'){
192 my $id = $input->param('reports');
193 my $report = Koha::Reports->find($id);
194 my $group = $report->report_group;
195 my $subgroup = $report->report_subgroup;
197 'sql' => $report->savedsql,
198 'reportname' => $report->report_name,
199 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
200 'notes' => $report->notes,
202 'cache_expiry' => $report->cache_expiry,
203 'public' => $report->public,
204 'usecache' => $usecache,
206 'mana_id' => $report->{mana_id},
207 'mana_comments' => $report->{comments}
211 elsif ( $phase eq 'Update SQL'){
212 my $id = $input->param('id');
213 my $sql = $input->param('sql');
214 my $reportname = $input->param('reportname');
215 my $group = $input->param('group');
216 my $subgroup = $input->param('subgroup');
217 my $notes = $input->param('notes');
218 my $cache_expiry = $input->param('cache_expiry');
219 my $cache_expiry_units = $input->param('cache_expiry_units');
220 my $public = $input->param('public');
221 my $save_anyway = $input->param('save_anyway');
224 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
225 if( $cache_expiry_units ){
226 if( $cache_expiry_units eq "minutes" ){
228 } elsif( $cache_expiry_units eq "hours" ){
229 $cache_expiry *= 3600; # 60 * 60
230 } elsif( $cache_expiry_units eq "days" ){
231 $cache_expiry *= 86400; # 60 * 60 * 24
234 # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
235 if( $cache_expiry >= 2592000 ){
236 push @errors, {cache_expiry => $cache_expiry};
239 create_non_existing_group_and_subgroup($input, $group, $subgroup);
241 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
242 push(@errors, @$validation_errors) unless $is_sql_valid;
246 'errors' => \@errors,
251 # Check defined SQL parameters for authorised value validity
252 my $problematic_authvals = ValidateSQLParameters($sql);
254 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
255 # There's at least one problematic parameter, report to the
256 # GUI and provide all user input for further actions
260 'reportname' => $reportname,
262 'subgroup' => $subgroup,
265 'problematic_authvals' => $problematic_authvals,
266 'warn_authval_problem' => 1,
271 # No params problem found or asked to save anyway
276 subgroup => $subgroup,
279 cache_expiry => $cache_expiry,
282 'save_successful' => 1,
283 'reportname' => $reportname,
287 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
289 'cache_expiry' => $cache_expiry,
291 'usecache' => $usecache,
293 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
297 cache_expiry => $cache_expiry,
298 cache_expiry_units => $cache_expiry_units,
304 elsif ($phase eq 'retrieve results') {
305 my $id = $input->param('id');
306 my $result = format_results( $id );
308 report_name => $result->{report_name},
309 notes => $result->{notes},
310 saved_results => $result->{results},
311 date_run => $result->{date_run},
315 elsif ( $phase eq 'Report on this Area' ) {
316 my $cache_expiry_units = $input->param('cache_expiry_units'),
317 my $cache_expiry = $input->param('cache_expiry');
319 # we need to handle converting units
320 if( $cache_expiry_units eq "minutes" ){
322 } elsif( $cache_expiry_units eq "hours" ){
323 $cache_expiry *= 3600; # 60 * 60
324 } elsif( $cache_expiry_units eq "days" ){
325 $cache_expiry *= 86400; # 60 * 60 * 24
327 # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
328 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
329 # report error to user
333 'areas' => get_report_areas(),
334 'cache_expiry' => $cache_expiry,
335 'usecache' => $usecache,
336 'public' => scalar $input->param('public'),
339 # they have chosen a new report and the area to report on
342 'area' => scalar $input->param('area'),
343 'types' => get_report_types(),
344 'cache_expiry' => $cache_expiry,
345 'public' => scalar $input->param('public'),
350 elsif ( $phase eq 'Choose this type' ) {
351 # they have chosen type and area
352 # get area and type and pass them to the template
353 my $area = $input->param('area');
354 my $type = $input->param('types');
359 columns => get_columns($area,$input),
360 'cache_expiry' => scalar $input->param('cache_expiry'),
361 'public' => scalar $input->param('public'),
365 elsif ( $phase eq 'Choose these columns' ) {
366 # we now know type, area, and columns
367 # next step is the constraints
368 my $area = $input->param('area');
369 my $type = $input->param('type');
370 my @columns = $input->multi_param('columns');
371 my $column = join( ',', @columns );
378 definitions => get_from_dictionary($area),
379 criteria => get_criteria($area,$input),
380 'public' => scalar $input->param('public'),
384 cache_expiry => scalar $input->param('cache_expiry'),
385 cache_expiry_units => scalar $input->param('cache_expiry_units'),
391 elsif ( $phase eq 'Choose these criteria' ) {
392 my $area = $input->param('area');
393 my $type = $input->param('type');
394 my $column = $input->param('column');
395 my @definitions = $input->multi_param('definition');
396 my $definition = join (',',@definitions);
397 my @criteria = $input->multi_param('criteria_column');
399 foreach my $crit (@criteria) {
400 my $value = $input->param( $crit . "_value" );
402 # If value is not defined, then it may be range values
403 if (!defined $value) {
405 my $fromvalue = $input->param( "from_" . $crit . "_value" );
406 my $tovalue = $input->param( "to_" . $crit . "_value" );
408 # If the range values are dates
410 $fromvalue_dt = eval { dt_from_string( $fromvalue ); } if ( $fromvalue );
412 $tovalue_dt = eval { dt_from_string( $tovalue ); } if ($tovalue);
413 if ( $fromvalue_dt && $tovalue_dt ) {
414 $fromvalue = output_pref( { dt => dt_from_string( $fromvalue_dt ), dateonly => 1, dateformat => 'iso' } );
415 $tovalue = output_pref( { dt => dt_from_string( $tovalue_dt ), dateonly => 1, dateformat => 'iso' } );
418 if ($fromvalue && $tovalue) {
419 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
426 $value_dt = eval { dt_from_string( $value ); } if ( $value );
428 $value = output_pref( { dt => dt_from_string( $value_dt ), dateonly => 1, dateformat => 'iso' } );
430 # don't escape runtime parameters, they'll be at runtime
431 if ($value =~ /<<.*>>/) {
432 $query_criteria .= " AND $crit=$value";
434 $query_criteria .= " AND $crit='$value'";
443 'definition' => $definition,
444 'criteriastring' => $query_criteria,
445 'public' => scalar $input->param('public'),
449 cache_expiry => scalar $input->param('cache_expiry'),
450 cache_expiry_units => scalar $input->param('cache_expiry_units'),
455 my @columns = split( ',', $column );
458 # build structue for use by tmpl_loop to choose columns to order by
459 # need to do something about the order of the order :)
460 # we also want to use the %columns hash to get the plain english names
461 foreach my $col (@columns) {
462 my %total = (name => $col);
463 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
464 $total{'select'} = \@selects;
465 push @total_by, \%total;
468 $template->param( 'total_by' => \@total_by );
471 elsif ( $phase eq 'Choose these operations' ) {
472 my $area = $input->param('area');
473 my $type = $input->param('type');
474 my $column = $input->param('column');
475 my $criteria = $input->param('criteria');
476 my $definition = $input->param('definition');
477 my @total_by = $input->multi_param('total_by');
479 foreach my $total (@total_by) {
480 my $value = $input->param( $total . "_tvalue" );
481 $totals .= "$value($total),";
489 'criteriastring' => $criteria,
491 'definition' => $definition,
492 'cache_expiry' => scalar $input->param('cache_expiry'),
493 'public' => scalar $input->param('public'),
497 my @columns = split( ',', $column );
500 # build structue for use by tmpl_loop to choose columns to order by
501 # need to do something about the order of the order :)
502 foreach my $col (@columns) {
503 my %order = (name => $col);
504 my @selects = map {+{ value => $_ }} (qw(asc desc));
505 $order{'select'} = \@selects;
506 push @order_by, \%order;
509 $template->param( 'order_by' => \@order_by );
512 elsif ( $phase eq 'Build report' ) {
514 # now we have all the info we need and can build the sql
515 my $area = $input->param('area');
516 my $type = $input->param('type');
517 my $column = $input->param('column');
518 my $crit = $input->param('criteria');
519 my $totals = $input->param('totals');
520 my $definition = $input->param('definition');
521 my $query_criteria=$crit;
522 # split the columns up by ,
523 my @columns = split( ',', $column );
524 my @order_by = $input->multi_param('order_by');
527 foreach my $order (@order_by) {
528 my $value = $input->param( $order . "_ovalue" );
529 if ($query_orderby) {
530 $query_orderby .= ",$order $value";
533 $query_orderby = " ORDER BY $order $value";
539 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
545 'cache_expiry' => scalar $input->param('cache_expiry'),
546 'public' => scalar $input->param('public'),
550 elsif ( $phase eq 'Save' ) {
551 # Save the report that has just been built
552 my $area = $input->param('area');
553 my $sql = $input->param('sql');
554 my $type = $input->param('type');
560 'cache_expiry' => scalar $input->param('cache_expiry'),
561 'public' => scalar $input->param('public'),
562 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
566 elsif ( $phase eq 'Save Report' ) {
567 # save the sql pasted in by a user
568 my $area = $input->param('area');
569 my $group = $input->param('group');
570 my $subgroup = $input->param('subgroup');
571 my $sql = $input->param('sql');
572 my $name = $input->param('reportname');
573 my $type = $input->param('types');
574 my $notes = $input->param('notes');
575 my $cache_expiry = $input->param('cache_expiry');
576 my $cache_expiry_units = $input->param('cache_expiry_units');
577 my $public = $input->param('public');
578 my $save_anyway = $input->param('save_anyway');
581 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
582 if( $cache_expiry_units ){
583 if( $cache_expiry_units eq "minutes" ){
585 } elsif( $cache_expiry_units eq "hours" ){
586 $cache_expiry *= 3600; # 60 * 60
587 } elsif( $cache_expiry_units eq "days" ){
588 $cache_expiry *= 86400; # 60 * 60 * 24
591 # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp
592 if( $cache_expiry && $cache_expiry >= 2592000 ){
593 push @errors, {cache_expiry => $cache_expiry};
596 create_non_existing_group_and_subgroup($input, $group, $subgroup);
597 ## FIXME this is AFTER entering a name to save the report under
598 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
599 push(@errors, @$validation_errors) unless $is_sql_valid;
603 'errors' => \@errors,
605 'reportname'=> $name,
608 'cache_expiry' => $cache_expiry,
612 # Check defined SQL parameters for authorised value validity
613 my $problematic_authvals = ValidateSQLParameters($sql);
615 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
616 # There's at least one problematic parameter, report to the
617 # GUI and provide all user input for further actions
621 'subgroup' => $subgroup,
623 'reportname' => $name,
627 'problematic_authvals' => $problematic_authvals,
628 'warn_authval_problem' => 1,
633 cache_expiry => $cache_expiry,
634 cache_expiry_units => $cache_expiry_units,
638 # No params problem found or asked to save anyway
639 my $id = save_report( {
640 borrowernumber => $borrowernumber,
645 subgroup => $subgroup,
648 cache_expiry => $cache_expiry,
651 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
653 'save_successful' => 1,
654 'reportname' => $name,
658 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
660 'cache_expiry' => $cache_expiry,
662 'usecache' => $usecache,
668 elsif ($phase eq 'Share'){
669 my $lang = $input->param('mana_language') || '';
670 my $reportid = $input->param('reportid');
671 my $result = Koha::SharedContent::send_entity($lang, $borrowernumber, $reportid, 'report');
673 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=".$result->{msg});
675 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=noanswer");
678 elsif ($phase eq 'Run this report'){
679 # execute a saved report
680 my $limit = $input->param('limit') || 20;
682 my $report_id = $input->param('reports');
683 my @sql_params = $input->multi_param('sql_params');
684 my @param_names = $input->multi_param('param_name');
685 my $want_full_chart = $input->param('want_full_chart') || 0;
688 if ($input->param('page')) {
689 $offset = ($input->param('page') - 1) * $limit;
694 'report_id' => $report_id,
697 my ( $sql, $original_sql, $type, $name, $notes );
698 if (my $report = Koha::Reports->find($report_id)) {
699 $sql = $original_sql = $report->savedsql;
700 $name = $report->report_name;
701 $notes = $report->notes;
705 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
706 if ($sql =~ /<</ && !@sql_params) {
707 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
708 my @split = split /<<|>>/,$sql;
712 for(my $i=0;$i<($#split/2);$i++) {
713 my ($text,$authorised_value_all) = split /\|/,$split[$i*2+1];
714 my $sep = $authorised_value_all ? "|" : "";
715 if( defined $uniq_params{$text.$sep.$authorised_value_all} ){
717 } else { $uniq_params{$text.$sep.$authorised_value_all} = "$i"; }
718 my ($authorised_value, $all) = split /:/, $authorised_value_all;
721 if ( not defined $authorised_value ) {
722 # no authorised value input, provide a text box
724 } elsif ( $authorised_value eq "date" ) {
725 # require a date, provide a date picker
727 } elsif ( $authorised_value eq "list" ) {
728 # require a list, provide a textarea
731 # defined $authorised_value, and not 'date'
732 my $dbh=C4::Context->dbh;
733 my @authorised_values;
735 # builds list, depending on authorised value...
736 if ( $authorised_value eq "branches" ) {
737 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } );
738 while ( my $library = $libraries->next ) {
739 push @authorised_values, $library->branchcode;
740 $authorised_lib{$library->branchcode} = $library->branchname;
743 elsif ( $authorised_value eq "itemtypes" ) {
744 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
746 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
747 push @authorised_values, $itemtype;
748 $authorised_lib{$itemtype} = $description;
751 elsif ( $authorised_value eq "biblio_framework" ) {
752 my @frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] });
753 my $default_source = '';
754 push @authorised_values,$default_source;
755 $authorised_lib{$default_source} = 'Default';
756 foreach my $framework (@frameworks) {
757 push @authorised_values, $framework->frameworkcode;
758 $authorised_lib{$framework->frameworkcode} = $framework->frameworktext;
761 elsif ( $authorised_value eq "cn_source" ) {
762 my $class_sources = GetClassSources();
763 my $default_source = C4::Context->preference("DefaultClassificationSource");
764 foreach my $class_source (sort keys %$class_sources) {
765 next unless $class_sources->{$class_source}->{'used'} or
766 ($class_source eq $default_source);
767 push @authorised_values, $class_source;
768 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
771 elsif ( $authorised_value eq "categorycode" ) {
772 my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']});
773 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
774 push @authorised_values, $_->categorycode for @patron_categories;
777 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
779 SELECT authorised_value,lib
780 FROM authorised_values
784 my $authorised_values_sth = $dbh->prepare($query);
785 $authorised_values_sth->execute( $authorised_value);
787 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
788 push @authorised_values, $value;
789 $authorised_lib{$value} = $lib;
790 # For item location, we show the code and the libelle
791 $authorised_lib{$value} = $lib;
794 # not exists $authorised_value_categories{$authorised_value})
795 push @authval_errors, {'entry' => $text,
796 'auth_val' => $authorised_value };
797 # tell the template there's an error
798 $template->param( auth_val_error => 1 );
799 # skip scrolling list creation and params push
806 name => "sql_params",
807 id => "sql_params_".$labelid,
808 values => \@authorised_values,
809 labels => \%authorised_lib,
813 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid, 'name' => $text.$sep.$authorised_value_all, 'include_all' => $all };
815 $template->param('sql' => $sql,
817 'sql_params' => \@tmpl_parameters,
818 'auth_val_errors' => \@authval_errors,
820 'reports' => $report_id,
823 my ($sql,$header_types) = $report->prep_report( \@param_names, \@sql_params );
824 $template->param(header_types => $header_types);
825 my ( $sth, $errors ) = execute_query( $sql, $offset, $limit, undef, $report_id );
828 die "execute_query failed to return sth for report $report_id: $sql";
829 } elsif ( !$errors ) {
830 $total = nb_rows($sql) || 0;
831 my $headers = header_cell_loop($sth);
832 $template->param(header_row => $headers);
833 while (my $row = $sth->fetchrow_arrayref()) {
834 my @cells = map { +{ cell => $_ } } @$row;
835 push @rows, { cells => \@cells };
837 if( $want_full_chart ){
838 my ($sth2, $errors2) = execute_query($sql);
839 while (my $row = $sth2->fetchrow_arrayref()) {
840 my @cells = map { +{ cell => $_ } } @$row;
841 push @allrows, { cells => \@cells };
845 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
846 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit&want_full_chart=$want_full_chart";
848 $url = join('&param_name=', $url, map { URI::Escape::uri_escape_utf8($_) } @param_names);
851 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
856 'allresults' => \@allrows,
857 'pagination_bar' => pagination_bar($url, $totpages, scalar $input->param('page')),
858 'unlimited_total' => $total,
863 original_sql => $original_sql,
868 'errors' => defined($errors) ? [$errors] : undef,
869 'sql_params' => \@sql_params,
870 'param_names' => \@param_names,
875 push @errors, { no_sql_for_id => $report_id };
879 elsif ($phase eq 'Export'){
881 # export results to tab separated text or CSV
882 my $report_id = $input->param('report_id');
883 my $report = Koha::Reports->find($report_id);
884 my $sql = $report->savedsql;
885 my @param_names = $input->multi_param('param_name');
886 my @sql_params = $input->multi_param('sql_params');
887 my $format = $input->param('format');
888 my $reportname = $input->param('reportname');
889 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
891 ($sql, undef) = $report->prep_report( \@param_names, \@sql_params );
892 my ($sth, $q_errors) = execute_query($sql);
893 unless ($q_errors and @$q_errors) {
894 my ( $type, $content );
895 if ($format eq 'tab') {
896 $type = 'application/octet-stream';
897 $content .= join("\t", header_cell_values($sth)) . "\n";
898 $content = Encode::decode('UTF-8', $content);
899 while (my $row = $sth->fetchrow_arrayref()) {
900 $content .= join("\t", map { $_ // '' } @$row) . "\n";
903 my $delimiter = C4::Context->preference('CSVDelimiter') || ',';
904 if ( $format eq 'csv' ) {
905 $delimiter = "\t" if $delimiter eq 'tabulation';
906 $type = 'application/csv';
907 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
908 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
909 if ($csv->combine(header_cell_values($sth))) {
910 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
912 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
914 while (my $row = $sth->fetchrow_arrayref()) {
915 if ($csv->combine(@$row)) {
916 $content .= $csv->string() . "\n";
918 push @$q_errors, { combine => $csv->error_diag() } ;
922 elsif ( $format eq 'ods' ) {
923 $type = 'application/vnd.oasis.opendocument.spreadsheet';
924 my $ods_fh = File::Temp->new( UNLINK => 0 );
925 my $ods_filepath = $ods_fh->filename;
928 # First line is headers
929 my @headers = header_cell_values($sth);
930 push @$ods_content, \@headers;
932 # Other line in Unicode
933 my $sql_rows = $sth->fetchall_arrayref();
934 foreach my $sql_row ( @$sql_rows ) {
936 foreach my $sql_cell ( @$sql_row ) {
937 push @content_row, Encode::encode( 'UTF8', $sql_cell );
939 push @$ods_content, \@content_row;
943 generate_ods($ods_filepath, $ods_content);
947 open $ods_fh, '<', $ods_filepath;
948 $content .= $_ while <$ods_fh>;
949 unlink $ods_filepath;
952 print $input->header(
954 -attachment=> $reportfilename
958 foreach my $err (@$q_errors, @errors) {
959 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
960 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
966 'name' => 'Error exporting report!',
968 'errors' => $q_errors,
972 elsif ( $phase eq 'Create report from SQL' || $phase eq 'Create report from existing' ) {
974 my ($group, $subgroup, $sql, $reportname, $notes);
975 if ( $input->param('sql') ) {
976 $group = $input->param('report_group');
977 $subgroup = $input->param('report_subgroup');
978 $sql = $input->param('sql') // '';
979 $reportname = $input->param('reportname') // '';
980 $notes = $input->param('notes') // '';
982 elsif ( my $report_id = $input->param('report_id') ) {
983 my $report = Koha::Reports->find($report_id);
984 $group = $report->report_group;
985 $subgroup = $report->report_subgroup;
986 $sql = $report->savedsql // '';
987 $reportname = $report->report_name // '';
988 $notes = $report->notes // '';
993 reportname => $reportname,
996 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
998 'cache_expiry' => 300,
999 'usecache' => $usecache,
1004 # pass $sth, get back an array of names for the column headers
1005 sub header_cell_values {
1006 my $sth = shift or return ();
1007 return '' unless ($sth->{NAME});
1008 return @{$sth->{NAME}};
1011 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
1012 sub header_cell_loop {
1013 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
1018 $template->{VARS}->{'build' . $_} and last;
1020 $template->param( 'referer' => $input->referer(),
1023 output_html_with_http_headers $input, $cookie, $template->output;
1025 sub groups_with_subgroups {
1026 my ($group, $subgroup) = @_;
1028 my $groups_with_subgroups = get_report_groups();
1030 my @sorted_keys = sort {
1031 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
1032 } keys %$groups_with_subgroups;
1033 foreach my $g_id (@sorted_keys) {
1034 my $v = $groups_with_subgroups->{$g_id};
1036 if (my $sg = $v->{subgroups}) {
1037 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
1040 name => $sg->{$sg_id},
1041 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
1048 selected => ($group && $g_id eq $group),
1049 subgroups => \@subgroups,
1055 sub create_non_existing_group_and_subgroup {
1056 my ($input, $group, $subgroup) = @_;
1057 if (defined $group and $group ne '') {
1058 my $report_groups = C4::Reports::Guided::get_report_groups;
1059 if (not exists $report_groups->{$group}) {
1060 my $groupdesc = $input->param('groupdesc') // $group;
1061 Koha::AuthorisedValue->new({
1062 category => 'REPORT_GROUP',
1063 authorised_value => $group,
1066 my $cache_key = "AuthorisedValues-REPORT_GROUP-0-".C4::Context->userenv->{"branch"};
1067 my $cache = Koha::Caches->get_instance();
1068 my $result = $cache->clear_from_cache($cache_key);
1070 if (defined $subgroup and $subgroup ne '') {
1071 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1072 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1073 Koha::AuthorisedValue->new({
1074 category => 'REPORT_SUBGROUP',
1075 authorised_value => $subgroup,
1076 lib => $subgroupdesc,
1079 my $cache_key = "AuthorisedValues-REPORT_SUBGROUP-0-".C4::Context->userenv->{"branch"};
1080 my $cache = Koha::Caches->get_instance();
1081 my $result = $cache->clear_from_cache($cache_key);