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 Koha::Notice::Templates;
41 use Koha::TemplateUtils qw( process_tt );
42 use C4::ClassSource qw( GetClassSources );
50 Script to control the guided report creation
55 my $usecache = Koha::Caches->get_instance->memcached_cache;
57 my $phase = $input->param('phase') // '';
59 if ( ( $phase eq 'Build new' ) || ( $phase eq 'Create report from SQL' ) || ( $phase eq 'Edit SQL' )
60 || ( $phase eq 'Build new from existing' ) ) {
61 $flagsrequired = 'create_reports';
63 elsif ( $phase eq 'Use saved' ) {
64 $flagsrequired = 'execute_reports';
66 elsif ( $phase eq 'Delete Saved' ) {
67 $flagsrequired = 'delete_reports';
73 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
75 template_name => "reports/guided_reports_start.tt",
78 flagsrequired => { reports => $flagsrequired },
81 my $session_id = $input->cookie('CGISESSID');
82 my $session = $session_id ? get_session($session_id) : undef;
84 $template->param( templates => Koha::Notice::Templates->search( { module => 'report' } ) );
87 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
89 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
90 $session->param('report_filter', $filter) if $session;
91 $template->param( 'filter_set' => 1 );
93 elsif ($session and not $input->param('clear_filters')) {
94 $filter = $session->param('report_filter');
97 my $op = $input->param('op') || q||;
101 $template->param( 'start' => 1 );
104 elsif ( $phase eq 'Build new' ) {
106 $template->param( 'build1' => 1 );
108 'areas' => get_report_areas(),
109 'usecache' => $usecache,
110 'cache_expiry' => 300,
113 } elsif ( $phase eq 'Use saved' ) {
115 if ( $op eq 'convert' ) {
116 my $report_id = $input->param('report_id');
117 my $report = Koha::Reports->find($report_id);
119 my $updated_sql = C4::Reports::Guided::convert_sql( $report->savedsql );
120 C4::Reports::Guided::update_sql(
124 name => $report->report_name,
125 group => $report->report_group,
126 subgroup => $report->report_subgroup,
127 notes => $report->notes,
128 public => $report->public,
129 cache_expiry => $report->cache_expiry,
132 $template->param( report_converted => $report->report_name );
137 # get list of reports and display them
138 my $group = $input->param('group');
139 my $subgroup = $input->param('subgroup');
140 $filter->{group} = $group;
141 $filter->{subgroup} = $subgroup;
142 my $reports = get_saved_reports($filter);
143 my $has_obsolete_reports;
144 for my $report ( @$reports ) {
145 $report->{results} = C4::Reports::Guided::get_results( $report->{id} );
146 if ( $report->{savedsql} =~ m|biblioitems| and $report->{savedsql} =~ m|marcxml| ) {
147 $report->{seems_obsolete} = 1;
148 $has_obsolete_reports++;
152 'manamsg' => $input->param('manamsg') || '',
154 'savedreports' => $reports,
155 'usecache' => $usecache,
156 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ),
158 has_obsolete_reports => $has_obsolete_reports,
162 elsif ( $phase eq 'Delete Multiple') {
163 my @ids = $input->multi_param('ids');
164 delete_report( @ids );
165 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
169 elsif ( $phase eq 'Delete Saved') {
171 # delete a report from the saved reports list
172 my $ids = $input->param('reports');
174 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
178 elsif ( $phase eq 'Show SQL'){
180 my $id = $input->param('reports');
181 my $report = Koha::Reports->find($id);
184 'reportname' => $report->report_name,
185 'notes' => $report->notes,
186 'sql' => $report->savedsql,
188 'mana_success' => scalar $input->param('mana_success'),
189 'mana_id' => $report->{mana_id},
190 'mana_comments' => $report->{comments}
194 elsif ( $phase eq 'Edit SQL'){
195 my $id = $input->param('reports');
196 my $report = Koha::Reports->find($id);
197 my $group = $report->report_group;
198 my $subgroup = $report->report_subgroup;
199 my $tables = get_tables();
201 'sql' => $report->savedsql,
202 'reportname' => $report->report_name,
203 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
204 'notes' => $report->notes,
206 'cache_expiry' => $report->cache_expiry,
207 'public' => $report->public,
208 'usecache' => $usecache,
210 'mana_id' => $report->{mana_id},
211 'mana_comments' => $report->{comments},
216 elsif ( $phase eq 'update_sql' || $phase eq 'update_and_run_sql' ){
217 my $id = $input->param('id');
218 my $sql = $input->param('sql');
219 my $reportname = $input->param('reportname');
220 my $group = $input->param('group');
221 my $subgroup = $input->param('subgroup');
222 my $notes = $input->param('notes');
223 my $cache_expiry = $input->param('cache_expiry');
224 my $cache_expiry_units = $input->param('cache_expiry_units');
225 my $public = $input->param('public');
226 my $save_anyway = $input->param('save_anyway');
228 my $tables = get_tables();
230 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
231 if( $cache_expiry_units ){
232 if( $cache_expiry_units eq "minutes" ){
234 } elsif( $cache_expiry_units eq "hours" ){
235 $cache_expiry *= 3600; # 60 * 60
236 } elsif( $cache_expiry_units eq "days" ){
237 $cache_expiry *= 86400; # 60 * 60 * 24
240 # 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
241 if( $cache_expiry >= 2592000 ){
242 push @errors, {cache_expiry => $cache_expiry};
245 create_non_existing_group_and_subgroup($input, $group, $subgroup);
247 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
248 push(@errors, @$validation_errors) unless $is_sql_valid;
252 'errors' => \@errors,
257 # Check defined SQL parameters for authorised value validity
258 my $problematic_authvals = ValidateSQLParameters($sql);
260 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
261 # There's at least one problematic parameter, report to the
262 # GUI and provide all user input for further actions
266 'reportname' => $reportname,
268 'subgroup' => $subgroup,
271 'problematic_authvals' => $problematic_authvals,
272 'warn_authval_problem' => 1,
277 # No params problem found or asked to save anyway
282 subgroup => $subgroup,
285 cache_expiry => $cache_expiry,
288 'save_successful' => 1,
289 'reportname' => $reportname,
293 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
295 'cache_expiry' => $cache_expiry,
297 'usecache' => $usecache,
300 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
304 cache_expiry => $cache_expiry,
305 cache_expiry_units => $cache_expiry_units,
308 if ( $phase eq 'update_and_run_sql' ) {
309 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?reports=$id&phase=Run%20this%20report");
314 elsif ($phase eq 'retrieve results') {
315 my $id = $input->param('id');
316 my $result = format_results( $id );
318 report_name => $result->{report_name},
319 notes => $result->{notes},
320 saved_results => $result->{results},
321 date_run => $result->{date_run},
325 elsif ( $phase eq 'Report on this Area' ) {
326 my $cache_expiry_units = $input->param('cache_expiry_units'),
327 my $cache_expiry = $input->param('cache_expiry');
329 # we need to handle converting units
330 if( $cache_expiry_units eq "minutes" ){
332 } elsif( $cache_expiry_units eq "hours" ){
333 $cache_expiry *= 3600; # 60 * 60
334 } elsif( $cache_expiry_units eq "days" ){
335 $cache_expiry *= 86400; # 60 * 60 * 24
337 # 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
338 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
339 # report error to user
343 'areas' => get_report_areas(),
344 'cache_expiry' => $cache_expiry,
345 'usecache' => $usecache,
346 'public' => scalar $input->param('public'),
349 # they have chosen a new report and the area to report on
352 'area' => scalar $input->param('area'),
353 'types' => get_report_types(),
354 'cache_expiry' => $cache_expiry,
355 'public' => scalar $input->param('public'),
360 elsif ( $phase eq 'Choose this type' ) {
361 # they have chosen type and area
362 # get area and type and pass them to the template
363 my $area = $input->param('area');
364 my $type = $input->param('types');
369 columns => get_columns($area,$input),
370 'cache_expiry' => scalar $input->param('cache_expiry'),
371 'public' => scalar $input->param('public'),
375 elsif ( $phase eq 'Choose these columns' ) {
376 # we now know type, area, and columns
377 # next step is the constraints
378 my $area = $input->param('area');
379 my $type = $input->param('type');
380 my @columns = $input->multi_param('columns');
381 my $column = join( ',', @columns );
388 definitions => get_from_dictionary($area),
389 criteria => get_criteria($area,$input),
390 'public' => scalar $input->param('public'),
394 cache_expiry => scalar $input->param('cache_expiry'),
395 cache_expiry_units => scalar $input->param('cache_expiry_units'),
401 elsif ( $phase eq 'Choose these criteria' ) {
402 my $area = $input->param('area');
403 my $type = $input->param('type');
404 my $column = $input->param('column');
405 my @definitions = $input->multi_param('definition');
406 my $definition = join (',',@definitions);
407 my @criteria = $input->multi_param('criteria_column');
409 foreach my $crit (@criteria) {
410 my $value = $input->param( $crit . "_value" );
412 # If value is not defined, then it may be range values
413 if (!defined $value) {
414 my $fromvalue = $input->param( "from_" . $crit . "_value" );
415 my $tovalue = $input->param( "to_" . $crit . "_value" );
417 if ($fromvalue && $tovalue) {
418 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
421 # don't escape runtime parameters, they'll be at runtime
422 if ($value =~ /<<.*>>/) {
423 $query_criteria .= " AND $crit=$value";
425 $query_criteria .= " AND $crit='$value'";
434 'definition' => $definition,
435 'criteriastring' => $query_criteria,
436 'public' => scalar $input->param('public'),
440 cache_expiry => scalar $input->param('cache_expiry'),
441 cache_expiry_units => scalar $input->param('cache_expiry_units'),
446 my @columns = split( ',', $column );
449 # build structue for use by tmpl_loop to choose columns to order by
450 # need to do something about the order of the order :)
451 # we also want to use the %columns hash to get the plain english names
452 foreach my $col (@columns) {
453 my %total = (name => $col);
454 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
455 $total{'cud-select'} = \@selects;
456 push @total_by, \%total;
459 $template->param( 'total_by' => \@total_by );
462 elsif ( $phase eq 'Choose these operations' ) {
463 my $area = $input->param('area');
464 my $type = $input->param('type');
465 my $column = $input->param('column');
466 my $criteria = $input->param('criteria');
467 my $definition = $input->param('definition');
468 my @total_by = $input->multi_param('total_by');
470 foreach my $total (@total_by) {
471 my $value = $input->param( $total . "_tvalue" );
472 $totals .= "$value($total),";
480 'criteriastring' => $criteria,
482 'definition' => $definition,
483 'cache_expiry' => scalar $input->param('cache_expiry'),
484 'public' => scalar $input->param('public'),
488 my @columns = split( ',', $column );
491 # build structue for use by tmpl_loop to choose columns to order by
492 # need to do something about the order of the order :)
493 foreach my $col (@columns) {
494 my %order = (name => $col);
495 my @selects = map {+{ value => $_ }} (qw(asc desc));
496 $order{'cud-select'} = \@selects;
497 push @order_by, \%order;
500 $template->param( 'order_by' => \@order_by );
503 elsif ( $phase eq 'Build report' ) {
505 # now we have all the info we need and can build the sql
506 my $area = $input->param('area');
507 my $type = $input->param('type');
508 my $column = $input->param('column');
509 my $crit = $input->param('criteria');
510 my $totals = $input->param('totals');
511 my $definition = $input->param('definition');
512 my $query_criteria=$crit;
513 # split the columns up by ,
514 my @columns = split( ',', $column );
515 my @order_by = $input->multi_param('order_by');
518 foreach my $order (@order_by) {
519 my $value = $input->param( $order . "_ovalue" );
520 if ($query_orderby) {
521 $query_orderby .= ",$order $value";
524 $query_orderby = " ORDER BY $order $value";
530 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
536 'cache_expiry' => scalar $input->param('cache_expiry'),
537 'public' => scalar $input->param('public'),
541 elsif ( $phase eq 'Save' ) {
542 # Save the report that has just been built
543 my $area = $input->param('area');
544 my $sql = $input->param('sql');
545 my $type = $input->param('type');
551 'cache_expiry' => scalar $input->param('cache_expiry'),
552 'public' => scalar $input->param('public'),
553 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
557 elsif ( $phase eq 'Save Report' ) {
558 # save the sql pasted in by a user
559 my $area = $input->param('area');
560 my $group = $input->param('group');
561 my $subgroup = $input->param('subgroup');
562 my $sql = $input->param('sql');
563 my $name = $input->param('reportname');
564 my $type = $input->param('types');
565 my $notes = $input->param('notes');
566 my $cache_expiry = $input->param('cache_expiry');
567 my $cache_expiry_units = $input->param('cache_expiry_units');
568 my $public = $input->param('public');
569 my $save_anyway = $input->param('save_anyway');
570 my $tables = get_tables();
573 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
574 if( $cache_expiry_units ){
575 if( $cache_expiry_units eq "minutes" ){
577 } elsif( $cache_expiry_units eq "hours" ){
578 $cache_expiry *= 3600; # 60 * 60
579 } elsif( $cache_expiry_units eq "days" ){
580 $cache_expiry *= 86400; # 60 * 60 * 24
583 # 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
584 if( $cache_expiry && $cache_expiry >= 2592000 ){
585 push @errors, {cache_expiry => $cache_expiry};
588 create_non_existing_group_and_subgroup($input, $group, $subgroup);
589 ## FIXME this is AFTER entering a name to save the report under
590 my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid;
591 push(@errors, @$validation_errors) unless $is_sql_valid;
595 'errors' => \@errors,
597 'reportname'=> $name,
600 'cache_expiry' => $cache_expiry,
604 # Check defined SQL parameters for authorised value validity
605 my $problematic_authvals = ValidateSQLParameters($sql);
607 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
608 # There's at least one problematic parameter, report to the
609 # GUI and provide all user input for further actions
613 'subgroup' => $subgroup,
615 'reportname' => $name,
619 'problematic_authvals' => $problematic_authvals,
620 'warn_authval_problem' => 1,
625 cache_expiry => $cache_expiry,
626 cache_expiry_units => $cache_expiry_units,
630 # No params problem found or asked to save anyway
631 my $id = save_report( {
632 borrowernumber => $borrowernumber,
637 subgroup => $subgroup,
640 cache_expiry => $cache_expiry,
643 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
645 'save_successful' => 1,
646 'reportname' => $name,
650 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
652 'cache_expiry' => $cache_expiry,
654 'usecache' => $usecache,
661 elsif ($phase eq 'Share'){
662 my $lang = $input->param('mana_language') || '';
663 my $reportid = $input->param('reportid');
664 my $result = Koha::SharedContent::send_entity($lang, $borrowernumber, $reportid, 'report');
666 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=".$result->{msg});
668 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved&manamsg=noanswer");
671 elsif ($phase eq 'Run this report'){
672 # execute a saved report
673 my $limit = $input->param('limit') || 20;
675 my $report_id = $input->param('reports');
676 my @sql_params = $input->multi_param('sql_params');
677 my @param_names = $input->multi_param('param_name');
678 my $template_id = $input->param('template');
679 my $want_full_chart = $input->param('want_full_chart') || 0;
683 if ($input->param('page')) {
684 $offset = ($input->param('page') - 1) * $limit;
689 'report_id' => $report_id,
692 my ( $sql, $original_sql, $type, $name, $notes );
693 if (my $report = Koha::Reports->find($report_id)) {
694 $sql = $original_sql = $report->savedsql;
695 $name = $report->report_name;
696 $notes = $report->notes;
700 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
701 if ($sql =~ /<</ && !@sql_params) {
702 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
703 my @split = split /<<|>>/,$sql;
707 for(my $i=0;$i<($#split/2);$i++) {
708 my ($text,$authorised_value_all) = split /\|/,$split[$i*2+1];
709 my $sep = $authorised_value_all ? "|" : "";
710 if( defined $uniq_params{$text.$sep.$authorised_value_all} ){
712 } else { $uniq_params{$text.$sep.$authorised_value_all} = "$i"; }
713 my ($authorised_value, $all) = split /:/, $authorised_value_all;
716 if ( not defined $authorised_value ) {
717 # no authorised value input, provide a text box
719 } elsif ( $authorised_value eq "date" ) {
720 # require a date, provide a date picker
722 } elsif ( $authorised_value eq "list" ) {
723 # require a list, provide a textarea
726 # defined $authorised_value, and not 'date'
727 my $dbh=C4::Context->dbh;
728 my @authorised_values;
730 # builds list, depending on authorised value...
731 if ( $authorised_value eq "branches" ) {
732 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } );
733 while ( my $library = $libraries->next ) {
734 push @authorised_values, $library->branchcode;
735 $authorised_lib{$library->branchcode} = $library->branchname;
738 elsif ( $authorised_value eq "itemtypes" ) {
739 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
741 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
742 push @authorised_values, $itemtype;
743 $authorised_lib{$itemtype} = $description;
746 elsif ( $authorised_value eq "biblio_framework" ) {
747 my @frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->as_list;
748 my $default_source = '';
749 push @authorised_values,$default_source;
750 $authorised_lib{$default_source} = 'Default';
751 foreach my $framework (@frameworks) {
752 push @authorised_values, $framework->frameworkcode;
753 $authorised_lib{$framework->frameworkcode} = $framework->frameworktext;
756 elsif ( $authorised_value eq "cn_source" ) {
757 my $class_sources = GetClassSources();
758 my $default_source = C4::Context->preference("DefaultClassificationSource");
759 foreach my $class_source (sort keys %$class_sources) {
760 next unless $class_sources->{$class_source}->{'used'} or
761 ($class_source eq $default_source);
762 push @authorised_values, $class_source;
763 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
766 elsif ( $authorised_value eq "categorycode" ) {
767 my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']})->as_list;
768 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
769 push @authorised_values, $_->categorycode for @patron_categories;
771 elsif ( $authorised_value eq "cash_registers" ) {
772 my $sth = $dbh->prepare("SELECT id, name FROM cash_registers ORDER BY description");
774 while ( my ( $id, $name ) = $sth->fetchrow_array ) {
775 push @authorised_values, $id;
776 $authorised_lib{$id} = $name;
779 elsif ( $authorised_value eq "debit_types" ) {
780 my $sth = $dbh->prepare("SELECT code, description FROM account_debit_types ORDER BY code");
782 while ( my ( $code, $description ) = $sth->fetchrow_array ) {
783 push @authorised_values, $code;
784 $authorised_lib{$code} = $description;
787 elsif ( $authorised_value eq "credit_types" ) {
788 my $sth = $dbh->prepare("SELECT code, description FROM account_credit_types ORDER BY code");
790 while ( my ( $code, $description ) = $sth->fetchrow_array ) {
791 push @authorised_values, $code;
792 $authorised_lib{$code} = $description;
796 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
798 SELECT authorised_value,lib
799 FROM authorised_values
803 my $authorised_values_sth = $dbh->prepare($query);
804 $authorised_values_sth->execute( $authorised_value);
806 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
807 push @authorised_values, $value;
808 $authorised_lib{$value} = $lib;
809 # For item location, we show the code and the libelle
810 $authorised_lib{$value} = $lib;
813 # not exists $authorised_value_categories{$authorised_value})
814 push @authval_errors, {'entry' => $text,
815 'auth_val' => $authorised_value };
816 # tell the template there's an error
817 $template->param( auth_val_error => 1 );
818 # skip scrolling list creation and params push
825 name => "sql_params",
826 id => "sql_params_".$labelid,
827 values => \@authorised_values,
828 labels => \%authorised_lib,
832 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid, 'name' => $text.$sep.$authorised_value_all, 'include_all' => $all };
834 $template->param('sql' => $sql,
837 'sql_params' => \@tmpl_parameters,
838 'auth_val_errors' => \@authval_errors,
840 'reports' => $report_id,
843 my ($sql,$header_types) = $report->prep_report( \@param_names, \@sql_params );
844 $template->param(header_types => $header_types);
845 my ( $sth, $errors ) = execute_query(
850 report_id => $report_id,
855 die "execute_query failed to return sth for report $report_id: $sql";
856 } elsif ( !$errors ) {
857 $total = nb_rows($sql) || 0;
858 my $headers = header_cell_loop($sth);
859 $template->param(header_row => $headers);
860 while (my $row = $sth->fetchrow_arrayref()) {
861 my @cells = map { +{ cell => $_ } } @$row;
862 push @rows, { cells => \@cells };
864 if( $want_full_chart ){
865 my ( $sth2, $errors2 ) = execute_query( { sql => $sql, report_id => $report_id } );
866 while (my $row = $sth2->fetchrow_arrayref()) {
867 my @cells = map { +{ cell => $_ } } @$row;
868 push @allrows, { cells => \@cells };
872 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
873 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit&want_full_chart=$want_full_chart";
875 $url = join('&param_name=', $url, map { URI::Escape::uri_escape_utf8($_) } @param_names);
878 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
882 my $notice_template = Koha::Notice::Templates->find($template_id);
883 my ( $sth2, $errors2 ) = execute_query( { sql => $sql, report_id => $report_id } );
884 my $data = $sth2->fetchall_arrayref( {} );
885 my $notice_rendered =
886 process_tt( $notice_template->content, { data => $data, report_id => $report_id } );
888 process_tt( $notice_template->title, { data => $data, report_id => $report_id } );
890 template_id => $template_id,
891 processed_notice => $notice_rendered,
892 processed_notice_title => $title_rendered,
898 'allresults' => \@allrows,
899 'pagination_bar' => pagination_bar($url, $totpages, scalar $input->param('page')),
900 'unlimited_total' => $total,
905 original_sql => $original_sql,
910 'errors' => defined($errors) ? [$errors] : undef,
911 'sql_params' => \@sql_params,
912 'param_names' => \@param_names,
917 push @errors, { no_sql_for_id => $report_id };
921 elsif ($phase eq 'Export'){
923 # export results to tab separated text or CSV
924 my $report_id = $input->param('report_id');
925 my $report = Koha::Reports->find($report_id);
926 my $sql = $report->savedsql;
927 my @param_names = $input->multi_param('param_name');
928 my @sql_params = $input->multi_param('sql_params');
929 my $format = $input->param('format');
930 my $reportname = $input->param('reportname');
931 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
933 ($sql, undef) = $report->prep_report( \@param_names, \@sql_params );
934 my ( $sth, $q_errors ) = execute_query( { sql => $sql, report_id => $report_id } );
935 unless ($q_errors and @$q_errors) {
936 my ( $type, $content );
937 if ($format eq 'tab') {
938 $type = 'application/octet-stream';
939 $content .= join("\t", header_cell_values($sth)) . "\n";
940 $content = Encode::decode('UTF-8', $content);
941 while (my $row = $sth->fetchrow_arrayref()) {
942 $content .= join("\t", map { $_ // '' } @$row) . "\n";
945 if ( $format eq 'csv' ) {
946 my $delimiter = C4::Context->csv_delimiter;
947 $type = 'application/csv';
948 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
949 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
950 if ($csv->combine(header_cell_values($sth))) {
951 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
953 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
955 while (my $row = $sth->fetchrow_arrayref()) {
956 if ($csv->combine(@$row)) {
957 $content .= $csv->string() . "\n";
959 push @$q_errors, { combine => $csv->error_diag() } ;
963 elsif ( $format eq 'ods' ) {
964 $type = 'application/vnd.oasis.opendocument.spreadsheet';
965 my $ods_fh = File::Temp->new( UNLINK => 0 );
966 my $ods_filepath = $ods_fh->filename;
969 # First line is headers
970 my @headers = header_cell_values($sth);
971 push @$ods_content, \@headers;
973 # Other line in Unicode
974 my $sql_rows = $sth->fetchall_arrayref();
975 foreach my $sql_row ( @$sql_rows ) {
977 foreach my $sql_cell ( @$sql_row ) {
978 push @content_row, Encode::encode( 'UTF8', $sql_cell );
980 push @$ods_content, \@content_row;
984 generate_ods($ods_filepath, $ods_content);
988 open $ods_fh, '<', $ods_filepath;
989 $content .= $_ while <$ods_fh>;
990 unlink $ods_filepath;
992 elsif ( $format eq 'template' ) {
993 my $template_id = $input->param('template');
994 my $notice_template = Koha::Notice::Templates->find($template_id);
995 my $data = $sth->fetchall_arrayref( {} );
996 $content = process_tt(
997 $notice_template->content,
1000 report_id => $report_id,
1004 $reportfilename = process_tt(
1005 $notice_template->title,
1008 report_id => $report_id,
1013 print $input->header(
1015 -attachment=> $reportfilename
1019 foreach my $err (@$q_errors, @errors) {
1020 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
1021 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
1027 'name' => 'Error exporting report!',
1029 'errors' => $q_errors,
1033 elsif ( $phase eq 'Create report from SQL' || $phase eq 'Create report from existing' ) {
1035 my ($group, $subgroup, $sql, $reportname, $notes);
1036 if ( $input->param('sql') ) {
1037 $group = $input->param('report_group');
1038 $subgroup = $input->param('report_subgroup');
1039 $sql = $input->param('sql') // '';
1040 $reportname = $input->param('reportname') // '';
1041 $notes = $input->param('notes') // '';
1043 elsif ( my $report_id = $input->param('report_id') ) {
1044 my $report = Koha::Reports->find($report_id);
1045 $group = $report->report_group;
1046 $subgroup = $report->report_subgroup;
1047 $sql = $report->savedsql // '';
1048 $reportname = $report->report_name // '';
1049 $notes = $report->notes // '';
1052 my $tables = get_tables();
1056 reportname => $reportname,
1059 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
1061 'cache_expiry' => 300,
1062 'usecache' => $usecache,
1063 'tables' => $tables,
1068 # pass $sth, get back an array of names for the column headers
1069 sub header_cell_values {
1070 my $sth = shift or return ();
1071 return '' unless ($sth->{NAME});
1072 return @{$sth->{NAME}};
1075 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
1076 sub header_cell_loop {
1077 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
1081 #get a list of available tables for auto-complete
1084 my $cache = Koha::Caches->get_instance();
1085 my $tables = $cache->get_from_cache("Reports-SQL_tables-for-autocomplete");
1090 $tables = C4::Reports::Guided->get_all_tables();
1091 for my $table (@{$tables}) {
1092 my $sql = "SHOW COLUMNS FROM $table";
1093 my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} });
1094 for my $row (@{$rows}) {
1095 push @{$result->{$table}}, $row->{Field};
1098 $cache->set_in_cache("Reports-SQL_tables-for-autocomplete",$result);
1103 $template->{VARS}->{'build' . $_} and last;
1105 $template->param( 'referer' => $input->referer(),
1108 output_html_with_http_headers $input, $cookie, $template->output;
1110 sub groups_with_subgroups {
1111 my ($group, $subgroup) = @_;
1113 my $groups_with_subgroups = get_report_groups();
1115 my @sorted_keys = sort {
1116 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
1117 } keys %$groups_with_subgroups;
1118 foreach my $g_id (@sorted_keys) {
1119 my $v = $groups_with_subgroups->{$g_id};
1121 if (my $sg = $v->{subgroups}) {
1122 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
1125 name => $sg->{$sg_id},
1126 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
1133 selected => ($group && $g_id eq $group),
1134 subgroups => \@subgroups,
1140 sub create_non_existing_group_and_subgroup {
1141 my ($input, $group, $subgroup) = @_;
1142 if (defined $group and $group ne '') {
1143 my $report_groups = C4::Reports::Guided::get_report_groups;
1144 if (not exists $report_groups->{$group}) {
1145 my $groupdesc = $input->param('groupdesc') // $group;
1146 Koha::AuthorisedValue->new({
1147 category => 'REPORT_GROUP',
1148 authorised_value => $group,
1151 my $cache_key = "AuthorisedValues-REPORT_GROUP-0-".C4::Context->userenv->{"branch"};
1152 my $cache = Koha::Caches->get_instance();
1153 my $result = $cache->clear_from_cache($cache_key);
1155 if (defined $subgroup and $subgroup ne '') {
1156 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1157 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1158 Koha::AuthorisedValue->new({
1159 category => 'REPORT_SUBGROUP',
1160 authorised_value => $subgroup,
1161 lib => $subgroupdesc,
1164 my $cache_key = "AuthorisedValues-REPORT_SUBGROUP-0-".C4::Context->userenv->{"branch"};
1165 my $cache = Koha::Caches->get_instance();
1166 my $result = $cache->clear_from_cache($cache_key);