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::AuthorisedValue;
34 use Koha::AuthorisedValues;
35 use Koha::BiblioFrameworks;
37 use Koha::Patron::Categories;
38 use Koha::SharedContent;
39 use Koha::Util::OpenDocument qw( generate_ods );
40 use C4::ClassSource qw( GetClassSources );
48 Script to control the guided report creation
53 my $usecache = Koha::Caches->get_instance->memcached_cache;
55 my $phase = $input->param('phase') // '';
57 if ( ( $phase eq 'Build new' ) || ( $phase eq 'Create report from SQL' ) || ( $phase eq 'Edit SQL' )
58 || ( $phase eq 'Build new from existing' ) ) {
59 $flagsrequired = 'create_reports';
61 elsif ( $phase eq 'Use saved' ) {
62 $flagsrequired = 'execute_reports';
64 elsif ( $phase eq 'Delete Saved' ) {
65 $flagsrequired = 'delete_reports';
71 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
73 template_name => "reports/guided_reports_start.tt",
76 flagsrequired => { reports => $flagsrequired },
79 my $session_id = $input->cookie('CGISESSID');
80 my $session = $session_id ? get_session($session_id) : 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' => scalar $input->param('mana_success'),
185 'mana_id' => $report->{mana_id},
186 'mana_comments' => $report->{comments}
190 elsif ( $phase eq 'Edit SQL'){
191 my $id = $input->param('reports');
192 my $report = Koha::Reports->find($id);
193 my $group = $report->report_group;
194 my $subgroup = $report->report_subgroup;
195 my $tables = get_tables();
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},
212 elsif ( $phase eq 'Update SQL'){
213 my $id = $input->param('id');
214 my $sql = $input->param('sql');
215 my $reportname = $input->param('reportname');
216 my $group = $input->param('group');
217 my $subgroup = $input->param('subgroup');
218 my $notes = $input->param('notes');
219 my $cache_expiry = $input->param('cache_expiry');
220 my $cache_expiry_units = $input->param('cache_expiry_units');
221 my $public = $input->param('public');
222 my $save_anyway = $input->param('save_anyway');
224 my $tables = get_tables();
226 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
227 if( $cache_expiry_units ){
228 if( $cache_expiry_units eq "minutes" ){
230 } elsif( $cache_expiry_units eq "hours" ){
231 $cache_expiry *= 3600; # 60 * 60
232 } elsif( $cache_expiry_units eq "days" ){
233 $cache_expiry *= 86400; # 60 * 60 * 24
236 # 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
237 if( $cache_expiry >= 2592000 ){
238 push @errors, {cache_expiry => $cache_expiry};
241 create_non_existing_group_and_subgroup($input, $group, $subgroup);
243 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
244 push(@errors, @$validation_errors) unless $is_sql_valid;
248 'errors' => \@errors,
253 # Check defined SQL parameters for authorised value validity
254 my $problematic_authvals = ValidateSQLParameters($sql);
256 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
257 # There's at least one problematic parameter, report to the
258 # GUI and provide all user input for further actions
262 'reportname' => $reportname,
264 'subgroup' => $subgroup,
267 'problematic_authvals' => $problematic_authvals,
268 'warn_authval_problem' => 1,
273 # No params problem found or asked to save anyway
278 subgroup => $subgroup,
281 cache_expiry => $cache_expiry,
284 'save_successful' => 1,
285 'reportname' => $reportname,
289 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
291 'cache_expiry' => $cache_expiry,
293 'usecache' => $usecache,
296 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
300 cache_expiry => $cache_expiry,
301 cache_expiry_units => $cache_expiry_units,
307 elsif ($phase eq 'retrieve results') {
308 my $id = $input->param('id');
309 my $result = format_results( $id );
311 report_name => $result->{report_name},
312 notes => $result->{notes},
313 saved_results => $result->{results},
314 date_run => $result->{date_run},
318 elsif ( $phase eq 'Report on this Area' ) {
319 my $cache_expiry_units = $input->param('cache_expiry_units'),
320 my $cache_expiry = $input->param('cache_expiry');
322 # we need to handle converting units
323 if( $cache_expiry_units eq "minutes" ){
325 } elsif( $cache_expiry_units eq "hours" ){
326 $cache_expiry *= 3600; # 60 * 60
327 } elsif( $cache_expiry_units eq "days" ){
328 $cache_expiry *= 86400; # 60 * 60 * 24
330 # 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
331 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
332 # report error to user
336 'areas' => get_report_areas(),
337 'cache_expiry' => $cache_expiry,
338 'usecache' => $usecache,
339 'public' => scalar $input->param('public'),
342 # they have chosen a new report and the area to report on
345 'area' => scalar $input->param('area'),
346 'types' => get_report_types(),
347 'cache_expiry' => $cache_expiry,
348 'public' => scalar $input->param('public'),
353 elsif ( $phase eq 'Choose this type' ) {
354 # they have chosen type and area
355 # get area and type and pass them to the template
356 my $area = $input->param('area');
357 my $type = $input->param('types');
362 columns => get_columns($area,$input),
363 'cache_expiry' => scalar $input->param('cache_expiry'),
364 'public' => scalar $input->param('public'),
368 elsif ( $phase eq 'Choose these columns' ) {
369 # we now know type, area, and columns
370 # next step is the constraints
371 my $area = $input->param('area');
372 my $type = $input->param('type');
373 my @columns = $input->multi_param('columns');
374 my $column = join( ',', @columns );
381 definitions => get_from_dictionary($area),
382 criteria => get_criteria($area,$input),
383 'public' => scalar $input->param('public'),
387 cache_expiry => scalar $input->param('cache_expiry'),
388 cache_expiry_units => scalar $input->param('cache_expiry_units'),
394 elsif ( $phase eq 'Choose these criteria' ) {
395 my $area = $input->param('area');
396 my $type = $input->param('type');
397 my $column = $input->param('column');
398 my @definitions = $input->multi_param('definition');
399 my $definition = join (',',@definitions);
400 my @criteria = $input->multi_param('criteria_column');
402 foreach my $crit (@criteria) {
403 my $value = $input->param( $crit . "_value" );
405 # If value is not defined, then it may be range values
406 if (!defined $value) {
407 my $fromvalue = $input->param( "from_" . $crit . "_value" );
408 my $tovalue = $input->param( "to_" . $crit . "_value" );
410 if ($fromvalue && $tovalue) {
411 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
414 # don't escape runtime parameters, they'll be at runtime
415 if ($value =~ /<<.*>>/) {
416 $query_criteria .= " AND $crit=$value";
418 $query_criteria .= " AND $crit='$value'";
427 'definition' => $definition,
428 'criteriastring' => $query_criteria,
429 'public' => scalar $input->param('public'),
433 cache_expiry => scalar $input->param('cache_expiry'),
434 cache_expiry_units => scalar $input->param('cache_expiry_units'),
439 my @columns = split( ',', $column );
442 # build structue for use by tmpl_loop to choose columns to order by
443 # need to do something about the order of the order :)
444 # we also want to use the %columns hash to get the plain english names
445 foreach my $col (@columns) {
446 my %total = (name => $col);
447 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
448 $total{'select'} = \@selects;
449 push @total_by, \%total;
452 $template->param( 'total_by' => \@total_by );
455 elsif ( $phase eq 'Choose these operations' ) {
456 my $area = $input->param('area');
457 my $type = $input->param('type');
458 my $column = $input->param('column');
459 my $criteria = $input->param('criteria');
460 my $definition = $input->param('definition');
461 my @total_by = $input->multi_param('total_by');
463 foreach my $total (@total_by) {
464 my $value = $input->param( $total . "_tvalue" );
465 $totals .= "$value($total),";
473 'criteriastring' => $criteria,
475 'definition' => $definition,
476 'cache_expiry' => scalar $input->param('cache_expiry'),
477 'public' => scalar $input->param('public'),
481 my @columns = split( ',', $column );
484 # build structue for use by tmpl_loop to choose columns to order by
485 # need to do something about the order of the order :)
486 foreach my $col (@columns) {
487 my %order = (name => $col);
488 my @selects = map {+{ value => $_ }} (qw(asc desc));
489 $order{'select'} = \@selects;
490 push @order_by, \%order;
493 $template->param( 'order_by' => \@order_by );
496 elsif ( $phase eq 'Build report' ) {
498 # now we have all the info we need and can build the sql
499 my $area = $input->param('area');
500 my $type = $input->param('type');
501 my $column = $input->param('column');
502 my $crit = $input->param('criteria');
503 my $totals = $input->param('totals');
504 my $definition = $input->param('definition');
505 my $query_criteria=$crit;
506 # split the columns up by ,
507 my @columns = split( ',', $column );
508 my @order_by = $input->multi_param('order_by');
511 foreach my $order (@order_by) {
512 my $value = $input->param( $order . "_ovalue" );
513 if ($query_orderby) {
514 $query_orderby .= ",$order $value";
517 $query_orderby = " ORDER BY $order $value";
523 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
529 'cache_expiry' => scalar $input->param('cache_expiry'),
530 'public' => scalar $input->param('public'),
534 elsif ( $phase eq 'Save' ) {
535 # Save the report that has just been built
536 my $area = $input->param('area');
537 my $sql = $input->param('sql');
538 my $type = $input->param('type');
544 'cache_expiry' => scalar $input->param('cache_expiry'),
545 'public' => scalar $input->param('public'),
546 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
550 elsif ( $phase eq 'Save Report' ) {
551 # save the sql pasted in by a user
552 my $area = $input->param('area');
553 my $group = $input->param('group');
554 my $subgroup = $input->param('subgroup');
555 my $sql = $input->param('sql');
556 my $name = $input->param('reportname');
557 my $type = $input->param('types');
558 my $notes = $input->param('notes');
559 my $cache_expiry = $input->param('cache_expiry');
560 my $cache_expiry_units = $input->param('cache_expiry_units');
561 my $public = $input->param('public');
562 my $save_anyway = $input->param('save_anyway');
563 my $tables = get_tables();
566 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
567 if( $cache_expiry_units ){
568 if( $cache_expiry_units eq "minutes" ){
570 } elsif( $cache_expiry_units eq "hours" ){
571 $cache_expiry *= 3600; # 60 * 60
572 } elsif( $cache_expiry_units eq "days" ){
573 $cache_expiry *= 86400; # 60 * 60 * 24
576 # 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
577 if( $cache_expiry && $cache_expiry >= 2592000 ){
578 push @errors, {cache_expiry => $cache_expiry};
581 create_non_existing_group_and_subgroup($input, $group, $subgroup);
582 ## FIXME this is AFTER entering a name to save the report under
583 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
584 push(@errors, @$validation_errors) unless $is_sql_valid;
588 'errors' => \@errors,
590 'reportname'=> $name,
593 'cache_expiry' => $cache_expiry,
597 # Check defined SQL parameters for authorised value validity
598 my $problematic_authvals = ValidateSQLParameters($sql);
600 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
601 # There's at least one problematic parameter, report to the
602 # GUI and provide all user input for further actions
606 'subgroup' => $subgroup,
608 'reportname' => $name,
612 'problematic_authvals' => $problematic_authvals,
613 'warn_authval_problem' => 1,
618 cache_expiry => $cache_expiry,
619 cache_expiry_units => $cache_expiry_units,
623 # No params problem found or asked to save anyway
624 my $id = save_report( {
625 borrowernumber => $borrowernumber,
630 subgroup => $subgroup,
633 cache_expiry => $cache_expiry,
636 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
638 'save_successful' => 1,
639 'reportname' => $name,
643 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
645 'cache_expiry' => $cache_expiry,
647 'usecache' => $usecache,
654 elsif ($phase eq 'Share'){
655 my $lang = $input->param('mana_language') || '';
656 my $reportid = $input->param('reportid');
657 my $result = Koha::SharedContent::send_entity($lang, $borrowernumber, $reportid, 'report');
659 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=".$result->{msg});
661 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=noanswer");
664 elsif ($phase eq 'Run this report'){
665 # execute a saved report
666 my $limit = $input->param('limit') || 20;
668 my $report_id = $input->param('reports');
669 my @sql_params = $input->multi_param('sql_params');
670 my @param_names = $input->multi_param('param_name');
671 my $want_full_chart = $input->param('want_full_chart') || 0;
674 if ($input->param('page')) {
675 $offset = ($input->param('page') - 1) * $limit;
680 'report_id' => $report_id,
683 my ( $sql, $original_sql, $type, $name, $notes );
684 if (my $report = Koha::Reports->find($report_id)) {
685 $sql = $original_sql = $report->savedsql;
686 $name = $report->report_name;
687 $notes = $report->notes;
691 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
692 if ($sql =~ /<</ && !@sql_params) {
693 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
694 my @split = split /<<|>>/,$sql;
698 for(my $i=0;$i<($#split/2);$i++) {
699 my ($text,$authorised_value_all) = split /\|/,$split[$i*2+1];
700 my $sep = $authorised_value_all ? "|" : "";
701 if( defined $uniq_params{$text.$sep.$authorised_value_all} ){
703 } else { $uniq_params{$text.$sep.$authorised_value_all} = "$i"; }
704 my ($authorised_value, $all) = split /:/, $authorised_value_all;
707 if ( not defined $authorised_value ) {
708 # no authorised value input, provide a text box
710 } elsif ( $authorised_value eq "date" ) {
711 # require a date, provide a date picker
713 } elsif ( $authorised_value eq "list" ) {
714 # require a list, provide a textarea
717 # defined $authorised_value, and not 'date'
718 my $dbh=C4::Context->dbh;
719 my @authorised_values;
721 # builds list, depending on authorised value...
722 if ( $authorised_value eq "branches" ) {
723 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } );
724 while ( my $library = $libraries->next ) {
725 push @authorised_values, $library->branchcode;
726 $authorised_lib{$library->branchcode} = $library->branchname;
729 elsif ( $authorised_value eq "itemtypes" ) {
730 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
732 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
733 push @authorised_values, $itemtype;
734 $authorised_lib{$itemtype} = $description;
737 elsif ( $authorised_value eq "biblio_framework" ) {
738 my @frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->as_list;
739 my $default_source = '';
740 push @authorised_values,$default_source;
741 $authorised_lib{$default_source} = 'Default';
742 foreach my $framework (@frameworks) {
743 push @authorised_values, $framework->frameworkcode;
744 $authorised_lib{$framework->frameworkcode} = $framework->frameworktext;
747 elsif ( $authorised_value eq "cn_source" ) {
748 my $class_sources = GetClassSources();
749 my $default_source = C4::Context->preference("DefaultClassificationSource");
750 foreach my $class_source (sort keys %$class_sources) {
751 next unless $class_sources->{$class_source}->{'used'} or
752 ($class_source eq $default_source);
753 push @authorised_values, $class_source;
754 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
757 elsif ( $authorised_value eq "categorycode" ) {
758 my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']})->as_list;
759 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
760 push @authorised_values, $_->categorycode for @patron_categories;
762 elsif ( $authorised_value eq "cash_registers" ) {
763 my $sth = $dbh->prepare("SELECT id, name FROM cash_registers ORDER BY description");
765 while ( my ( $id, $name ) = $sth->fetchrow_array ) {
766 push @authorised_values, $id;
767 $authorised_lib{$id} = $name;
770 elsif ( $authorised_value eq "debit_types" ) {
771 my $sth = $dbh->prepare("SELECT code, description FROM account_debit_types ORDER BY code");
773 while ( my ( $code, $description ) = $sth->fetchrow_array ) {
774 push @authorised_values, $code;
775 $authorised_lib{$code} = $description;
778 elsif ( $authorised_value eq "credit_types" ) {
779 my $sth = $dbh->prepare("SELECT code, description FROM account_credit_types ORDER BY code");
781 while ( my ( $code, $description ) = $sth->fetchrow_array ) {
782 push @authorised_values, $code;
783 $authorised_lib{$code} = $description;
787 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
789 SELECT authorised_value,lib
790 FROM authorised_values
794 my $authorised_values_sth = $dbh->prepare($query);
795 $authorised_values_sth->execute( $authorised_value);
797 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
798 push @authorised_values, $value;
799 $authorised_lib{$value} = $lib;
800 # For item location, we show the code and the libelle
801 $authorised_lib{$value} = $lib;
804 # not exists $authorised_value_categories{$authorised_value})
805 push @authval_errors, {'entry' => $text,
806 'auth_val' => $authorised_value };
807 # tell the template there's an error
808 $template->param( auth_val_error => 1 );
809 # skip scrolling list creation and params push
816 name => "sql_params",
817 id => "sql_params_".$labelid,
818 values => \@authorised_values,
819 labels => \%authorised_lib,
823 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid, 'name' => $text.$sep.$authorised_value_all, 'include_all' => $all };
825 $template->param('sql' => $sql,
827 'sql_params' => \@tmpl_parameters,
828 'auth_val_errors' => \@authval_errors,
830 'reports' => $report_id,
833 my ($sql,$header_types) = $report->prep_report( \@param_names, \@sql_params );
834 $template->param(header_types => $header_types);
835 my ( $sth, $errors ) = execute_query(
840 report_id => $report_id,
845 die "execute_query failed to return sth for report $report_id: $sql";
846 } elsif ( !$errors ) {
847 $total = nb_rows($sql) || 0;
848 my $headers = header_cell_loop($sth);
849 $template->param(header_row => $headers);
850 while (my $row = $sth->fetchrow_arrayref()) {
851 my @cells = map { +{ cell => $_ } } @$row;
852 push @rows, { cells => \@cells };
854 if( $want_full_chart ){
855 my ( $sth2, $errors2 ) = execute_query( { sql => $sql, report_id => $report_id } );
856 while (my $row = $sth2->fetchrow_arrayref()) {
857 my @cells = map { +{ cell => $_ } } @$row;
858 push @allrows, { cells => \@cells };
862 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
863 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit&want_full_chart=$want_full_chart";
865 $url = join('&param_name=', $url, map { URI::Escape::uri_escape_utf8($_) } @param_names);
868 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
873 'allresults' => \@allrows,
874 'pagination_bar' => pagination_bar($url, $totpages, scalar $input->param('page')),
875 'unlimited_total' => $total,
880 original_sql => $original_sql,
885 'errors' => defined($errors) ? [$errors] : undef,
886 'sql_params' => \@sql_params,
887 'param_names' => \@param_names,
892 push @errors, { no_sql_for_id => $report_id };
896 elsif ($phase eq 'Export'){
898 # export results to tab separated text or CSV
899 my $report_id = $input->param('report_id');
900 my $report = Koha::Reports->find($report_id);
901 my $sql = $report->savedsql;
902 my @param_names = $input->multi_param('param_name');
903 my @sql_params = $input->multi_param('sql_params');
904 my $format = $input->param('format');
905 my $reportname = $input->param('reportname');
906 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
908 ($sql, undef) = $report->prep_report( \@param_names, \@sql_params );
909 my ( $sth, $q_errors ) = execute_query( { sql => $sql, report_id => $report_id } );
910 unless ($q_errors and @$q_errors) {
911 my ( $type, $content );
912 if ($format eq 'tab') {
913 $type = 'application/octet-stream';
914 $content .= join("\t", header_cell_values($sth)) . "\n";
915 $content = Encode::decode('UTF-8', $content);
916 while (my $row = $sth->fetchrow_arrayref()) {
917 $content .= join("\t", map { $_ // '' } @$row) . "\n";
920 if ( $format eq 'csv' ) {
921 my $delimiter = C4::Context->csv_delimiter;
922 $type = 'application/csv';
923 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
924 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
925 if ($csv->combine(header_cell_values($sth))) {
926 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
928 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
930 while (my $row = $sth->fetchrow_arrayref()) {
931 if ($csv->combine(@$row)) {
932 $content .= $csv->string() . "\n";
934 push @$q_errors, { combine => $csv->error_diag() } ;
938 elsif ( $format eq 'ods' ) {
939 $type = 'application/vnd.oasis.opendocument.spreadsheet';
940 my $ods_fh = File::Temp->new( UNLINK => 0 );
941 my $ods_filepath = $ods_fh->filename;
944 # First line is headers
945 my @headers = header_cell_values($sth);
946 push @$ods_content, \@headers;
948 # Other line in Unicode
949 my $sql_rows = $sth->fetchall_arrayref();
950 foreach my $sql_row ( @$sql_rows ) {
952 foreach my $sql_cell ( @$sql_row ) {
953 push @content_row, Encode::encode( 'UTF8', $sql_cell );
955 push @$ods_content, \@content_row;
959 generate_ods($ods_filepath, $ods_content);
963 open $ods_fh, '<', $ods_filepath;
964 $content .= $_ while <$ods_fh>;
965 unlink $ods_filepath;
968 print $input->header(
970 -attachment=> $reportfilename
974 foreach my $err (@$q_errors, @errors) {
975 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
976 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
982 'name' => 'Error exporting report!',
984 'errors' => $q_errors,
988 elsif ( $phase eq 'Create report from SQL' || $phase eq 'Create report from existing' ) {
990 my ($group, $subgroup, $sql, $reportname, $notes);
991 if ( $input->param('sql') ) {
992 $group = $input->param('report_group');
993 $subgroup = $input->param('report_subgroup');
994 $sql = $input->param('sql') // '';
995 $reportname = $input->param('reportname') // '';
996 $notes = $input->param('notes') // '';
998 elsif ( my $report_id = $input->param('report_id') ) {
999 my $report = Koha::Reports->find($report_id);
1000 $group = $report->report_group;
1001 $subgroup = $report->report_subgroup;
1002 $sql = $report->savedsql // '';
1003 $reportname = $report->report_name // '';
1004 $notes = $report->notes // '';
1007 my $tables = get_tables();
1011 reportname => $reportname,
1014 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
1016 'cache_expiry' => 300,
1017 'usecache' => $usecache,
1018 'tables' => $tables,
1023 # pass $sth, get back an array of names for the column headers
1024 sub header_cell_values {
1025 my $sth = shift or return ();
1026 return '' unless ($sth->{NAME});
1027 return @{$sth->{NAME}};
1030 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
1031 sub header_cell_loop {
1032 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
1036 #get a list of available tables for auto-complete
1039 my $cache = Koha::Caches->get_instance();
1040 my $tables = $cache->get_from_cache("Reports-SQL_tables-for-autocomplete");
1045 $tables = C4::Reports::Guided->get_all_tables();
1046 for my $table (@{$tables}) {
1047 my $sql = "SHOW COLUMNS FROM $table";
1048 my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
1049 for my $row (@{$rows}) {
1050 push @{$result->{$table}}, $row->{Field};
1053 $cache->set_in_cache("Reports-SQL_tables-for-autocomplete",$result);
1058 $template->{VARS}->{'build' . $_} and last;
1060 $template->param( 'referer' => $input->referer(),
1063 output_html_with_http_headers $input, $cookie, $template->output;
1065 sub groups_with_subgroups {
1066 my ($group, $subgroup) = @_;
1068 my $groups_with_subgroups = get_report_groups();
1070 my @sorted_keys = sort {
1071 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
1072 } keys %$groups_with_subgroups;
1073 foreach my $g_id (@sorted_keys) {
1074 my $v = $groups_with_subgroups->{$g_id};
1076 if (my $sg = $v->{subgroups}) {
1077 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
1080 name => $sg->{$sg_id},
1081 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
1088 selected => ($group && $g_id eq $group),
1089 subgroups => \@subgroups,
1095 sub create_non_existing_group_and_subgroup {
1096 my ($input, $group, $subgroup) = @_;
1097 if (defined $group and $group ne '') {
1098 my $report_groups = C4::Reports::Guided::get_report_groups;
1099 if (not exists $report_groups->{$group}) {
1100 my $groupdesc = $input->param('groupdesc') // $group;
1101 Koha::AuthorisedValue->new({
1102 category => 'REPORT_GROUP',
1103 authorised_value => $group,
1106 my $cache_key = "AuthorisedValues-REPORT_GROUP-0-".C4::Context->userenv->{"branch"};
1107 my $cache = Koha::Caches->get_instance();
1108 my $result = $cache->clear_from_cache($cache_key);
1110 if (defined $subgroup and $subgroup ne '') {
1111 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1112 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1113 Koha::AuthorisedValue->new({
1114 category => 'REPORT_SUBGROUP',
1115 authorised_value => $subgroup,
1116 lib => $subgroupdesc,
1119 my $cache_key = "AuthorisedValues-REPORT_SUBGROUP-0-".C4::Context->userenv->{"branch"};
1120 my $cache = Koha::Caches->get_instance();
1121 my $result = $cache->clear_from_cache($cache_key);