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 File::Basename qw( dirname );
27 use C4::Reports::Guided;
28 use C4::Auth qw/:DEFAULT get_session/;
31 use C4::Koha qw/GetFrameworksLoop/;
36 use Koha::DateUtils qw/dt_from_string output_pref/;
37 use Koha::AuthorisedValue;
38 use Koha::AuthorisedValues;
46 Script to control the guided report creation
51 my $usecache = Koha::Caches->get_instance->memcached_cache;
53 my $phase = $input->param('phase') // '';
55 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
56 $flagsrequired = 'create_reports';
58 elsif ( $phase eq 'Use saved' ) {
59 $flagsrequired = 'execute_reports';
64 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
66 template_name => "reports/guided_reports_start.tt",
70 flagsrequired => { reports => $flagsrequired },
74 my $session = $cookie ? get_session($cookie->value) : undef;
77 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
79 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
80 $session->param('report_filter', $filter) if $session;
81 $template->param( 'filter_set' => 1 );
83 elsif ($session and not $input->param('clear_filters')) {
84 $filter = $session->param('report_filter');
90 $template->param( 'start' => 1 );
93 elsif ( $phase eq 'Build new' ) {
95 $template->param( 'build1' => 1 );
97 'areas' => get_report_areas(),
98 'usecache' => $usecache,
99 'cache_expiry' => 300,
102 } elsif ( $phase eq 'Use saved' ) {
105 # get list of reports and display them
106 my $group = $input->param('group');
107 my $subgroup = $input->param('subgroup');
108 $filter->{group} = $group;
109 $filter->{subgroup} = $subgroup;
112 'savedreports' => get_saved_reports($filter),
113 'usecache' => $usecache,
114 'groups_with_subgroups'=> groups_with_subgroups($group, $subgroup),
119 elsif ( $phase eq 'Delete Multiple') {
120 my @ids = $input->multi_param('ids');
121 delete_report( @ids );
122 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
126 elsif ( $phase eq 'Delete Saved') {
128 # delete a report from the saved reports list
129 my $ids = $input->param('reports');
131 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
135 elsif ( $phase eq 'Show SQL'){
137 my $id = $input->param('reports');
138 my $report = get_saved_report($id);
141 'reportname' => $report->{report_name},
142 'notes' => $report->{notes},
143 'sql' => $report->{savedsql},
148 elsif ( $phase eq 'Edit SQL'){
149 my $id = $input->param('reports');
150 my $report = get_saved_report($id);
151 my $group = $report->{report_group};
152 my $subgroup = $report->{report_subgroup};
154 'sql' => $report->{savedsql},
155 'reportname' => $report->{report_name},
156 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
157 'notes' => $report->{notes},
159 'cache_expiry' => $report->{cache_expiry},
160 'public' => $report->{public},
161 'usecache' => $usecache,
166 elsif ( $phase eq 'Update SQL'){
167 my $id = $input->param('id');
168 my $sql = $input->param('sql');
169 my $reportname = $input->param('reportname');
170 my $group = $input->param('group');
171 my $subgroup = $input->param('subgroup');
172 my $notes = $input->param('notes');
173 my $cache_expiry = $input->param('cache_expiry');
174 my $cache_expiry_units = $input->param('cache_expiry_units');
175 my $public = $input->param('public');
176 my $save_anyway = $input->param('save_anyway');
180 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
181 if( $cache_expiry_units ){
182 if( $cache_expiry_units eq "minutes" ){
184 } elsif( $cache_expiry_units eq "hours" ){
185 $cache_expiry *= 3600; # 60 * 60
186 } elsif( $cache_expiry_units eq "days" ){
187 $cache_expiry *= 86400; # 60 * 60 * 24
190 # check $cache_expiry isnt 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
191 if( $cache_expiry >= 2592000 ){
192 push @errors, {cache_expiry => $cache_expiry};
195 create_non_existing_group_and_subgroup($input, $group, $subgroup);
197 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
198 push @errors, {sqlerr => $1};
200 elsif ($sql !~ /^(SELECT)/i) {
201 push @errors, {queryerr => "No SELECT"};
206 'errors' => \@errors,
211 # Check defined SQL parameters for authorised value validity
212 my $problematic_authvals = ValidateSQLParameters($sql);
214 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
215 # There's at least one problematic parameter, report to the
216 # GUI and provide all user input for further actions
220 'reportname' => $reportname,
222 'subgroup' => $subgroup,
225 'problematic_authvals' => $problematic_authvals,
226 'warn_authval_problem' => 1,
231 # No params problem found or asked to save anyway
236 subgroup => $subgroup,
239 cache_expiry => $cache_expiry,
242 'save_successful' => 1,
243 'reportname' => $reportname,
246 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
250 cache_expiry => $cache_expiry,
251 cache_expiry_units => $cache_expiry_units,
257 elsif ($phase eq 'retrieve results') {
258 my $id = $input->param('id');
259 my ($results,$name,$notes) = format_results($id);
263 'results' => $results,
269 elsif ( $phase eq 'Report on this Area' ) {
270 my $cache_expiry_units = $input->param('cache_expiry_units'),
271 my $cache_expiry = $input->param('cache_expiry');
273 # we need to handle converting units
274 if( $cache_expiry_units eq "minutes" ){
276 } elsif( $cache_expiry_units eq "hours" ){
277 $cache_expiry *= 3600; # 60 * 60
278 } elsif( $cache_expiry_units eq "days" ){
279 $cache_expiry *= 86400; # 60 * 60 * 24
281 # check $cache_expiry isnt 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
282 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
283 # report error to user
287 'areas' => get_report_areas(),
288 'cache_expiry' => $cache_expiry,
289 'usecache' => $usecache,
290 'public' => scalar $input->param('public'),
293 # they have choosen a new report and the area to report on
296 'area' => scalar $input->param('area'),
297 'types' => get_report_types(),
298 'cache_expiry' => $cache_expiry,
299 'public' => scalar $input->param('public'),
304 elsif ( $phase eq 'Choose this type' ) {
305 # they have chosen type and area
306 # get area and type and pass them to the template
307 my $area = $input->param('area');
308 my $type = $input->param('types');
313 columns => get_columns($area,$input),
314 'cache_expiry' => scalar $input->param('cache_expiry'),
315 'public' => scalar $input->param('public'),
319 elsif ( $phase eq 'Choose these columns' ) {
320 # we now know type, area, and columns
321 # next step is the constraints
322 my $area = $input->param('area');
323 my $type = $input->param('type');
324 my @columns = $input->multi_param('columns');
325 my $column = join( ',', @columns );
332 definitions => get_from_dictionary($area),
333 criteria => get_criteria($area,$input),
334 'public' => scalar $input->param('public'),
338 cache_expiry => scalar $input->param('cache_expiry'),
339 cache_expiry_units => scalar $input->param('cache_expiry_units'),
345 elsif ( $phase eq 'Choose these criteria' ) {
346 my $area = $input->param('area');
347 my $type = $input->param('type');
348 my $column = $input->param('column');
349 my @definitions = $input->multi_param('definition');
350 my $definition = join (',',@definitions);
351 my @criteria = $input->multi_param('criteria_column');
353 foreach my $crit (@criteria) {
354 my $value = $input->param( $crit . "_value" );
356 # If value is not defined, then it may be range values
357 if (!defined $value) {
359 my $fromvalue = $input->param( "from_" . $crit . "_value" );
360 my $tovalue = $input->param( "to_" . $crit . "_value" );
362 # If the range values are dates
364 $fromvalue_dt = eval { dt_from_string( $fromvalue ); } if ( $fromvalue );
366 $tovalue_dt = eval { dt_from_string( $tovalue ); } if ($tovalue);
367 if ( $fromvalue_dt && $tovalue_dt ) {
368 $fromvalue = output_pref( { dt => dt_from_string( $fromvalue_dt ), dateonly => 1, dateformat => 'iso' } );
369 $tovalue = output_pref( { dt => dt_from_string( $tovalue_dt ), dateonly => 1, dateformat => 'iso' } );
372 if ($fromvalue && $tovalue) {
373 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
380 $value_dt = eval { dt_from_string( $value ); } if ( $value );
382 $value = output_pref( { dt => dt_from_string( $value_dt ), dateonly => 1, dateformat => 'iso' } );
384 # don't escape runtime parameters, they'll be at runtime
385 if ($value =~ /<<.*>>/) {
386 $query_criteria .= " AND $crit=$value";
388 $query_criteria .= " AND $crit='$value'";
397 'definition' => $definition,
398 'criteriastring' => $query_criteria,
399 'public' => scalar $input->param('public'),
403 cache_expiry => scalar $input->param('cache_expiry'),
404 cache_expiry_units => scalar $input->param('cache_expiry_units'),
409 my @columns = split( ',', $column );
412 # build structue for use by tmpl_loop to choose columns to order by
413 # need to do something about the order of the order :)
414 # we also want to use the %columns hash to get the plain english names
415 foreach my $col (@columns) {
416 my %total = (name => $col);
417 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
418 $total{'select'} = \@selects;
419 push @total_by, \%total;
422 $template->param( 'total_by' => \@total_by );
425 elsif ( $phase eq 'Choose these operations' ) {
426 my $area = $input->param('area');
427 my $type = $input->param('type');
428 my $column = $input->param('column');
429 my $criteria = $input->param('criteria');
430 my $definition = $input->param('definition');
431 my @total_by = $input->multi_param('total_by');
433 foreach my $total (@total_by) {
434 my $value = $input->param( $total . "_tvalue" );
435 $totals .= "$value($total),";
443 'criteriastring' => $criteria,
445 'definition' => $definition,
446 'cache_expiry' => scalar $input->param('cache_expiry'),
447 'public' => scalar $input->param('public'),
451 my @columns = split( ',', $column );
454 # build structue for use by tmpl_loop to choose columns to order by
455 # need to do something about the order of the order :)
456 foreach my $col (@columns) {
457 my %order = (name => $col);
458 my @selects = map {+{ value => $_ }} (qw(asc desc));
459 $order{'select'} = \@selects;
460 push @order_by, \%order;
463 $template->param( 'order_by' => \@order_by );
466 elsif ( $phase eq 'Build report' ) {
468 # now we have all the info we need and can build the sql
469 my $area = $input->param('area');
470 my $type = $input->param('type');
471 my $column = $input->param('column');
472 my $crit = $input->param('criteria');
473 my $totals = $input->param('totals');
474 my $definition = $input->param('definition');
475 my $query_criteria=$crit;
476 # split the columns up by ,
477 my @columns = split( ',', $column );
478 my @order_by = $input->multi_param('order_by');
481 foreach my $order (@order_by) {
482 my $value = $input->param( $order . "_ovalue" );
483 if ($query_orderby) {
484 $query_orderby .= ",$order $value";
487 $query_orderby = " ORDER BY $order $value";
493 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
499 'cache_expiry' => scalar $input->param('cache_expiry'),
500 'public' => scalar $input->param('public'),
504 elsif ( $phase eq 'Save' ) {
505 # Save the report that has just been built
506 my $area = $input->param('area');
507 my $sql = $input->param('sql');
508 my $type = $input->param('type');
514 'cache_expiry' => scalar $input->param('cache_expiry'),
515 'public' => scalar $input->param('public'),
516 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
520 elsif ( $phase eq 'Save Report' ) {
521 # save the sql pasted in by a user
522 my $area = $input->param('area');
523 my $group = $input->param('group');
524 my $subgroup = $input->param('subgroup');
525 my $sql = $input->param('sql');
526 my $name = $input->param('reportname');
527 my $type = $input->param('types');
528 my $notes = $input->param('notes');
529 my $cache_expiry = $input->param('cache_expiry');
530 my $cache_expiry_units = $input->param('cache_expiry_units');
531 my $public = $input->param('public');
532 my $save_anyway = $input->param('save_anyway');
535 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
536 if( $cache_expiry_units ){
537 if( $cache_expiry_units eq "minutes" ){
539 } elsif( $cache_expiry_units eq "hours" ){
540 $cache_expiry *= 3600; # 60 * 60
541 } elsif( $cache_expiry_units eq "days" ){
542 $cache_expiry *= 86400; # 60 * 60 * 24
545 # check $cache_expiry isnt 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
546 if( $cache_expiry && $cache_expiry >= 2592000 ){
547 push @errors, {cache_expiry => $cache_expiry};
550 create_non_existing_group_and_subgroup($input, $group, $subgroup);
552 ## FIXME this is AFTER entering a name to save the report under
553 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
554 push @errors, {sqlerr => $1};
556 elsif ($sql !~ /^(SELECT)/i) {
557 push @errors, {queryerr => "No SELECT"};
562 'errors' => \@errors,
564 'reportname'=> $name,
567 'cache_expiry' => $cache_expiry,
571 # Check defined SQL parameters for authorised value validity
572 my $problematic_authvals = ValidateSQLParameters($sql);
574 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
575 # There's at least one problematic parameter, report to the
576 # GUI and provide all user input for further actions
580 'subgroup' => $subgroup,
582 'reportname' => $name,
586 'problematic_authvals' => $problematic_authvals,
587 'warn_authval_problem' => 1,
592 cache_expiry => $cache_expiry,
593 cache_expiry_units => $cache_expiry_units,
597 # No params problem found or asked to save anyway
598 my $id = save_report( {
599 borrowernumber => $borrowernumber,
604 subgroup => $subgroup,
607 cache_expiry => $cache_expiry,
610 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
612 'save_successful' => 1,
613 'reportname' => $name,
620 elsif ($phase eq 'Run this report'){
621 # execute a saved report
622 my $limit = $input->param('limit') || 20;
624 my $report_id = $input->param('reports');
625 my @sql_params = $input->multi_param('sql_params');
627 if ($input->param('page')) {
628 $offset = ($input->param('page') - 1) * $limit;
633 'report_id' => $report_id,
636 my ( $sql, $type, $name, $notes );
637 if (my $report = get_saved_report($report_id)) {
638 $sql = $report->{savedsql};
639 $name = $report->{report_name};
640 $notes = $report->{notes};
643 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
644 if ($sql =~ /<</ && !@sql_params) {
645 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
646 my @split = split /<<|>>/,$sql;
649 for(my $i=0;$i<($#split/2);$i++) {
650 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
653 if ( not defined $authorised_value ) {
654 # no authorised value input, provide a text box
656 } elsif ( $authorised_value eq "date" ) {
657 # require a date, provide a date picker
660 # defined $authorised_value, and not 'date'
661 my $dbh=C4::Context->dbh;
662 my @authorised_values;
664 # builds list, depending on authorised value...
665 if ( $authorised_value eq "branches" ) {
666 my $branches = GetBranchesLoop();
667 foreach my $thisbranch (@$branches) {
668 push @authorised_values, $thisbranch->{value};
669 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
672 elsif ( $authorised_value eq "itemtypes" ) {
673 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
675 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
676 push @authorised_values, $itemtype;
677 $authorised_lib{$itemtype} = $description;
680 elsif ( $authorised_value eq "biblio_framework" ) {
681 my $frameworks = GetFrameworksLoop();
682 my $default_source = '';
683 push @authorised_values,$default_source;
684 $authorised_lib{$default_source} = 'Default';
685 foreach my $framework (@$frameworks) {
686 push @authorised_values, $framework->{value};
687 $authorised_lib{$framework->{value}} = $framework->{description};
690 elsif ( $authorised_value eq "cn_source" ) {
691 my $class_sources = GetClassSources();
692 my $default_source = C4::Context->preference("DefaultClassificationSource");
693 foreach my $class_source (sort keys %$class_sources) {
694 next unless $class_sources->{$class_source}->{'used'} or
695 ($class_source eq $default_source);
696 push @authorised_values, $class_source;
697 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
700 elsif ( $authorised_value eq "categorycode" ) {
701 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
703 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
704 push @authorised_values, $categorycode;
705 $authorised_lib{$categorycode} = $description;
708 #---- "true" authorised value
711 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
713 SELECT authorised_value,lib
714 FROM authorised_values
718 my $authorised_values_sth = $dbh->prepare($query);
719 $authorised_values_sth->execute( $authorised_value);
721 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
722 push @authorised_values, $value;
723 $authorised_lib{$value} = $lib;
724 # For item location, we show the code and the libelle
725 $authorised_lib{$value} = $lib;
728 # not exists $authorised_value_categories{$authorised_value})
729 push @authval_errors, {'entry' => $text,
730 'auth_val' => $authorised_value };
731 # tell the template there's an error
732 $template->param( auth_val_error => 1 );
733 # skip scrolling list creation and params push
740 name => "sql_params",
741 id => "sql_params_".$labelid,
742 values => \@authorised_values,
743 labels => \%authorised_lib,
747 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
749 $template->param('sql' => $sql,
751 'sql_params' => \@tmpl_parameters,
752 'auth_val_errors' => \@authval_errors,
754 'reports' => $report_id,
757 # OK, we have parameters, or there are none, we run the report
758 # if there were parameters, replace before running
759 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
760 my @split = split /<<|>>/,$sql;
762 for(my $i=0;$i<$#split/2;$i++) {
763 my $quoted = $sql_params[$i];
764 # if there are special regexp chars, we must \ them
765 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
766 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
767 $quoted = output_pref({ dt => dt_from_string($quoted), dateformat => 'iso', dateonly => 1 }) if $quoted;
769 $quoted = C4::Context->dbh->quote($quoted);
770 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
772 my ($sth, $errors) = execute_query($sql, $offset, $limit);
773 my $total = nb_rows($sql) || 0;
775 die "execute_query failed to return sth for report $report_id: $sql";
777 my $headers = header_cell_loop($sth);
778 $template->param(header_row => $headers);
779 while (my $row = $sth->fetchrow_arrayref()) {
780 my @cells = map { +{ cell => $_ } } @$row;
781 push @rows, { cells => \@cells };
785 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
786 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
788 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
797 'errors' => defined($errors) ? [ $errors ] : undef,
798 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
799 'unlimited_total' => $total,
800 'sql_params' => \@sql_params,
805 push @errors, { no_sql_for_id => $report_id };
809 elsif ($phase eq 'Export'){
811 # export results to tab separated text or CSV
812 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
813 my $format = $input->param('format');
814 my $reportname = $input->param('reportname');
815 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
816 my ($sth, $q_errors) = execute_query($sql);
817 unless ($q_errors and @$q_errors) {
818 my ( $type, $content );
819 if ($format eq 'tab') {
820 $type = 'application/octet-stream';
821 $content .= join("\t", header_cell_values($sth)) . "\n";
822 $content = Encode::decode('UTF-8', $content);
823 while (my $row = $sth->fetchrow_arrayref()) {
824 $content .= join("\t", @$row) . "\n";
827 my $delimiter = C4::Context->preference('delimiter') || ',';
828 if ( $format eq 'csv' ) {
829 $type = 'application/csv';
830 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
831 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
832 if ($csv->combine(header_cell_values($sth))) {
833 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
835 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
837 while (my $row = $sth->fetchrow_arrayref()) {
838 if ($csv->combine(@$row)) {
839 $content .= $csv->string() . "\n";
841 push @$q_errors, { combine => $csv->error_diag() } ;
845 elsif ( $format eq 'ods' ) {
846 $type = 'application/vnd.oasis.opendocument.spreadsheet';
847 my $ods_fh = File::Temp->new( UNLINK => 0 );
848 my $ods_filepath = $ods_fh->filename;
850 use OpenOffice::OODoc;
851 my $tmpdir = dirname $ods_filepath;
852 odfWorkingDirectory( $tmpdir );
853 my $container = odfContainer( $ods_filepath, create => 'spreadsheet' );
854 my $doc = odfDocument (
855 container => $container,
858 my $table = $doc->getTable(0);
859 my @headers = header_cell_values( $sth );
860 my $rows = $sth->fetchall_arrayref();
861 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
864 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
866 my $row = $doc->getRow( $table, 0 );
868 for my $header ( @headers ) {
869 $doc->cellValue( $row, $j, $header );
874 $row = $doc->getRow( $table, $i );
875 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
876 my $value = Encode::encode( 'UTF8', $rows->[$i - 1][$j] );
877 $doc->cellValue( $row, $j, $value );
883 open $ods_fh, '<', $ods_filepath;
884 $content .= $_ while <$ods_fh>;
885 unlink $ods_filepath;
888 print $input->header(
890 -attachment=> $reportfilename
894 foreach my $err (@$q_errors, @errors) {
895 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
896 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
902 'name' => 'Error exporting report!',
904 'errors' => $q_errors,
908 elsif ( $phase eq 'Create report from SQL' ) {
910 my ($group, $subgroup);
911 # allow the user to paste in sql
912 if ( $input->param('sql') ) {
913 $group = $input->param('report_group');
914 $subgroup = $input->param('report_subgroup');
916 'sql' => scalar $input->param('sql') // '',
917 'reportname' => scalar $input->param('reportname') // '',
918 'notes' => scalar $input->param('notes') // '',
923 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
925 'cache_expiry' => 300,
926 'usecache' => $usecache,
930 elsif ($phase eq 'Create Compound Report'){
931 $template->param( 'savedreports' => get_saved_reports(),
936 elsif ($phase eq 'Save Compound'){
937 my $master = $input->param('master');
938 my $subreport = $input->param('subreport');
939 my ($mastertables,$subtables) = create_compound($master,$subreport);
940 $template->param( 'save_compound' => 1,
941 master=>$mastertables,
946 # pass $sth, get back an array of names for the column headers
947 sub header_cell_values {
948 my $sth = shift or return ();
949 return '' unless ($sth->{NAME});
950 return @{$sth->{NAME}};
953 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
954 sub header_cell_loop {
955 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
960 $template->{VARS}->{'build' . $_} and last;
962 $template->param( 'referer' => $input->referer(),
965 output_html_with_http_headers $input, $cookie, $template->output;
967 sub groups_with_subgroups {
968 my ($group, $subgroup) = @_;
970 my $groups_with_subgroups = get_report_groups();
972 my @sorted_keys = sort {
973 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
974 } keys %$groups_with_subgroups;
975 foreach my $g_id (@sorted_keys) {
976 my $v = $groups_with_subgroups->{$g_id};
978 if (my $sg = $v->{subgroups}) {
979 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
982 name => $sg->{$sg_id},
983 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
990 selected => ($group && $g_id eq $group),
991 subgroups => \@subgroups,
997 sub create_non_existing_group_and_subgroup {
998 my ($input, $group, $subgroup) = @_;
1000 if (defined $group and $group ne '') {
1001 my $report_groups = C4::Reports::Guided::get_report_groups;
1002 if (not exists $report_groups->{$group}) {
1003 my $groupdesc = $input->param('groupdesc') // $group;
1004 Koha::AuthorisedValue->new({
1005 category => 'REPORT_GROUP',
1006 authorised_value => $group,
1010 if (defined $subgroup and $subgroup ne '') {
1011 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1012 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1013 Koha::AuthorisedValue->new({
1014 category => 'REPORT_SUBGROUP',
1015 authorised_value => $subgroup,
1016 lib => $subgroupdesc,