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/;
35 use Koha::DateUtils qw/dt_from_string output_pref/;
36 use Koha::AuthorisedValue;
37 use Koha::AuthorisedValues;
39 use Koha::Patron::Categories;
47 Script to control the guided report creation
52 my $usecache = Koha::Caches->get_instance->memcached_cache;
54 my $phase = $input->param('phase') // '';
56 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
57 $flagsrequired = 'create_reports';
59 elsif ( $phase eq 'Use saved' ) {
60 $flagsrequired = 'execute_reports';
65 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
67 template_name => "reports/guided_reports_start.tt",
71 flagsrequired => { reports => $flagsrequired },
75 my $session = $cookie ? get_session($cookie->value) : undef;
78 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
80 $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/;
81 $session->param('report_filter', $filter) if $session;
82 $template->param( 'filter_set' => 1 );
84 elsif ($session and not $input->param('clear_filters')) {
85 $filter = $session->param('report_filter');
91 $template->param( 'start' => 1 );
94 elsif ( $phase eq 'Build new' ) {
96 $template->param( 'build1' => 1 );
98 'areas' => get_report_areas(),
99 'usecache' => $usecache,
100 'cache_expiry' => 300,
103 } elsif ( $phase eq 'Use saved' ) {
106 # get list of reports and display them
107 my $group = $input->param('group');
108 my $subgroup = $input->param('subgroup');
109 $filter->{group} = $group;
110 $filter->{subgroup} = $subgroup;
113 'savedreports' => get_saved_reports($filter),
114 'usecache' => $usecache,
115 'groups_with_subgroups'=> groups_with_subgroups($group, $subgroup),
120 elsif ( $phase eq 'Delete Multiple') {
121 my @ids = $input->multi_param('ids');
122 delete_report( @ids );
123 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
127 elsif ( $phase eq 'Delete Saved') {
129 # delete a report from the saved reports list
130 my $ids = $input->param('reports');
132 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
136 elsif ( $phase eq 'Show SQL'){
138 my $id = $input->param('reports');
139 my $report = get_saved_report($id);
142 'reportname' => $report->{report_name},
143 'notes' => $report->{notes},
144 'sql' => $report->{savedsql},
149 elsif ( $phase eq 'Edit SQL'){
150 my $id = $input->param('reports');
151 my $report = get_saved_report($id);
152 my $group = $report->{report_group};
153 my $subgroup = $report->{report_subgroup};
155 'sql' => $report->{savedsql},
156 'reportname' => $report->{report_name},
157 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
158 'notes' => $report->{notes},
160 'cache_expiry' => $report->{cache_expiry},
161 'public' => $report->{public},
162 'usecache' => $usecache,
167 elsif ( $phase eq 'Update SQL'){
168 my $id = $input->param('id');
169 my $sql = $input->param('sql');
170 my $reportname = $input->param('reportname');
171 my $group = $input->param('group');
172 my $subgroup = $input->param('subgroup');
173 my $notes = $input->param('notes');
174 my $cache_expiry = $input->param('cache_expiry');
175 my $cache_expiry_units = $input->param('cache_expiry_units');
176 my $public = $input->param('public');
177 my $save_anyway = $input->param('save_anyway');
181 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
182 if( $cache_expiry_units ){
183 if( $cache_expiry_units eq "minutes" ){
185 } elsif( $cache_expiry_units eq "hours" ){
186 $cache_expiry *= 3600; # 60 * 60
187 } elsif( $cache_expiry_units eq "days" ){
188 $cache_expiry *= 86400; # 60 * 60 * 24
191 # 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
192 if( $cache_expiry >= 2592000 ){
193 push @errors, {cache_expiry => $cache_expiry};
196 create_non_existing_group_and_subgroup($input, $group, $subgroup);
198 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
199 push @errors, {sqlerr => $1};
201 elsif ($sql !~ /^(SELECT)/i) {
202 push @errors, {queryerr => "No SELECT"};
207 'errors' => \@errors,
212 # Check defined SQL parameters for authorised value validity
213 my $problematic_authvals = ValidateSQLParameters($sql);
215 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
216 # There's at least one problematic parameter, report to the
217 # GUI and provide all user input for further actions
221 'reportname' => $reportname,
223 'subgroup' => $subgroup,
226 'problematic_authvals' => $problematic_authvals,
227 'warn_authval_problem' => 1,
232 # No params problem found or asked to save anyway
237 subgroup => $subgroup,
240 cache_expiry => $cache_expiry,
243 'save_successful' => 1,
244 'reportname' => $reportname,
247 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
251 cache_expiry => $cache_expiry,
252 cache_expiry_units => $cache_expiry_units,
258 elsif ($phase eq 'retrieve results') {
259 my $id = $input->param('id');
260 my ($results,$name,$notes) = format_results($id);
264 'results' => $results,
270 elsif ( $phase eq 'Report on this Area' ) {
271 my $cache_expiry_units = $input->param('cache_expiry_units'),
272 my $cache_expiry = $input->param('cache_expiry');
274 # we need to handle converting units
275 if( $cache_expiry_units eq "minutes" ){
277 } elsif( $cache_expiry_units eq "hours" ){
278 $cache_expiry *= 3600; # 60 * 60
279 } elsif( $cache_expiry_units eq "days" ){
280 $cache_expiry *= 86400; # 60 * 60 * 24
282 # 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
283 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
284 # report error to user
288 'areas' => get_report_areas(),
289 'cache_expiry' => $cache_expiry,
290 'usecache' => $usecache,
291 'public' => scalar $input->param('public'),
294 # they have choosen a new report and the area to report on
297 'area' => scalar $input->param('area'),
298 'types' => get_report_types(),
299 'cache_expiry' => $cache_expiry,
300 'public' => scalar $input->param('public'),
305 elsif ( $phase eq 'Choose this type' ) {
306 # they have chosen type and area
307 # get area and type and pass them to the template
308 my $area = $input->param('area');
309 my $type = $input->param('types');
314 columns => get_columns($area,$input),
315 'cache_expiry' => scalar $input->param('cache_expiry'),
316 'public' => scalar $input->param('public'),
320 elsif ( $phase eq 'Choose these columns' ) {
321 # we now know type, area, and columns
322 # next step is the constraints
323 my $area = $input->param('area');
324 my $type = $input->param('type');
325 my @columns = $input->multi_param('columns');
326 my $column = join( ',', @columns );
333 definitions => get_from_dictionary($area),
334 criteria => get_criteria($area,$input),
335 'public' => scalar $input->param('public'),
339 cache_expiry => scalar $input->param('cache_expiry'),
340 cache_expiry_units => scalar $input->param('cache_expiry_units'),
346 elsif ( $phase eq 'Choose these criteria' ) {
347 my $area = $input->param('area');
348 my $type = $input->param('type');
349 my $column = $input->param('column');
350 my @definitions = $input->multi_param('definition');
351 my $definition = join (',',@definitions);
352 my @criteria = $input->multi_param('criteria_column');
354 foreach my $crit (@criteria) {
355 my $value = $input->param( $crit . "_value" );
357 # If value is not defined, then it may be range values
358 if (!defined $value) {
360 my $fromvalue = $input->param( "from_" . $crit . "_value" );
361 my $tovalue = $input->param( "to_" . $crit . "_value" );
363 # If the range values are dates
365 $fromvalue_dt = eval { dt_from_string( $fromvalue ); } if ( $fromvalue );
367 $tovalue_dt = eval { dt_from_string( $tovalue ); } if ($tovalue);
368 if ( $fromvalue_dt && $tovalue_dt ) {
369 $fromvalue = output_pref( { dt => dt_from_string( $fromvalue_dt ), dateonly => 1, dateformat => 'iso' } );
370 $tovalue = output_pref( { dt => dt_from_string( $tovalue_dt ), dateonly => 1, dateformat => 'iso' } );
373 if ($fromvalue && $tovalue) {
374 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
381 $value_dt = eval { dt_from_string( $value ); } if ( $value );
383 $value = output_pref( { dt => dt_from_string( $value_dt ), dateonly => 1, dateformat => 'iso' } );
385 # don't escape runtime parameters, they'll be at runtime
386 if ($value =~ /<<.*>>/) {
387 $query_criteria .= " AND $crit=$value";
389 $query_criteria .= " AND $crit='$value'";
398 'definition' => $definition,
399 'criteriastring' => $query_criteria,
400 'public' => scalar $input->param('public'),
404 cache_expiry => scalar $input->param('cache_expiry'),
405 cache_expiry_units => scalar $input->param('cache_expiry_units'),
410 my @columns = split( ',', $column );
413 # build structue for use by tmpl_loop to choose columns to order by
414 # need to do something about the order of the order :)
415 # we also want to use the %columns hash to get the plain english names
416 foreach my $col (@columns) {
417 my %total = (name => $col);
418 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
419 $total{'select'} = \@selects;
420 push @total_by, \%total;
423 $template->param( 'total_by' => \@total_by );
426 elsif ( $phase eq 'Choose these operations' ) {
427 my $area = $input->param('area');
428 my $type = $input->param('type');
429 my $column = $input->param('column');
430 my $criteria = $input->param('criteria');
431 my $definition = $input->param('definition');
432 my @total_by = $input->multi_param('total_by');
434 foreach my $total (@total_by) {
435 my $value = $input->param( $total . "_tvalue" );
436 $totals .= "$value($total),";
444 'criteriastring' => $criteria,
446 'definition' => $definition,
447 'cache_expiry' => scalar $input->param('cache_expiry'),
448 'public' => scalar $input->param('public'),
452 my @columns = split( ',', $column );
455 # build structue for use by tmpl_loop to choose columns to order by
456 # need to do something about the order of the order :)
457 foreach my $col (@columns) {
458 my %order = (name => $col);
459 my @selects = map {+{ value => $_ }} (qw(asc desc));
460 $order{'select'} = \@selects;
461 push @order_by, \%order;
464 $template->param( 'order_by' => \@order_by );
467 elsif ( $phase eq 'Build report' ) {
469 # now we have all the info we need and can build the sql
470 my $area = $input->param('area');
471 my $type = $input->param('type');
472 my $column = $input->param('column');
473 my $crit = $input->param('criteria');
474 my $totals = $input->param('totals');
475 my $definition = $input->param('definition');
476 my $query_criteria=$crit;
477 # split the columns up by ,
478 my @columns = split( ',', $column );
479 my @order_by = $input->multi_param('order_by');
482 foreach my $order (@order_by) {
483 my $value = $input->param( $order . "_ovalue" );
484 if ($query_orderby) {
485 $query_orderby .= ",$order $value";
488 $query_orderby = " ORDER BY $order $value";
494 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
500 'cache_expiry' => scalar $input->param('cache_expiry'),
501 'public' => scalar $input->param('public'),
505 elsif ( $phase eq 'Save' ) {
506 # Save the report that has just been built
507 my $area = $input->param('area');
508 my $sql = $input->param('sql');
509 my $type = $input->param('type');
515 'cache_expiry' => scalar $input->param('cache_expiry'),
516 'public' => scalar $input->param('public'),
517 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
521 elsif ( $phase eq 'Save Report' ) {
522 # save the sql pasted in by a user
523 my $area = $input->param('area');
524 my $group = $input->param('group');
525 my $subgroup = $input->param('subgroup');
526 my $sql = $input->param('sql');
527 my $name = $input->param('reportname');
528 my $type = $input->param('types');
529 my $notes = $input->param('notes');
530 my $cache_expiry = $input->param('cache_expiry');
531 my $cache_expiry_units = $input->param('cache_expiry_units');
532 my $public = $input->param('public');
533 my $save_anyway = $input->param('save_anyway');
536 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
537 if( $cache_expiry_units ){
538 if( $cache_expiry_units eq "minutes" ){
540 } elsif( $cache_expiry_units eq "hours" ){
541 $cache_expiry *= 3600; # 60 * 60
542 } elsif( $cache_expiry_units eq "days" ){
543 $cache_expiry *= 86400; # 60 * 60 * 24
546 # 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
547 if( $cache_expiry && $cache_expiry >= 2592000 ){
548 push @errors, {cache_expiry => $cache_expiry};
551 create_non_existing_group_and_subgroup($input, $group, $subgroup);
553 ## FIXME this is AFTER entering a name to save the report under
554 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
555 push @errors, {sqlerr => $1};
557 elsif ($sql !~ /^(SELECT)/i) {
558 push @errors, {queryerr => "No SELECT"};
563 'errors' => \@errors,
565 'reportname'=> $name,
568 'cache_expiry' => $cache_expiry,
572 # Check defined SQL parameters for authorised value validity
573 my $problematic_authvals = ValidateSQLParameters($sql);
575 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
576 # There's at least one problematic parameter, report to the
577 # GUI and provide all user input for further actions
581 'subgroup' => $subgroup,
583 'reportname' => $name,
587 'problematic_authvals' => $problematic_authvals,
588 'warn_authval_problem' => 1,
593 cache_expiry => $cache_expiry,
594 cache_expiry_units => $cache_expiry_units,
598 # No params problem found or asked to save anyway
599 my $id = save_report( {
600 borrowernumber => $borrowernumber,
605 subgroup => $subgroup,
608 cache_expiry => $cache_expiry,
611 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
613 'save_successful' => 1,
614 'reportname' => $name,
621 elsif ($phase eq 'Run this report'){
622 # execute a saved report
623 my $limit = $input->param('limit') || 20;
625 my $report_id = $input->param('reports');
626 my @sql_params = $input->multi_param('sql_params');
628 if ($input->param('page')) {
629 $offset = ($input->param('page') - 1) * $limit;
634 'report_id' => $report_id,
637 my ( $sql, $type, $name, $notes );
638 if (my $report = get_saved_report($report_id)) {
639 $sql = $report->{savedsql};
640 $name = $report->{report_name};
641 $notes = $report->{notes};
644 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
645 if ($sql =~ /<</ && !@sql_params) {
646 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
647 my @split = split /<<|>>/,$sql;
650 for(my $i=0;$i<($#split/2);$i++) {
651 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
654 if ( not defined $authorised_value ) {
655 # no authorised value input, provide a text box
657 } elsif ( $authorised_value eq "date" ) {
658 # require a date, provide a date picker
661 # defined $authorised_value, and not 'date'
662 my $dbh=C4::Context->dbh;
663 my @authorised_values;
665 # builds list, depending on authorised value...
666 if ( $authorised_value eq "branches" ) {
667 my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } );
668 while ( my $library = $libraries->next ) {
669 push @authorised_values, $library->branchcode;
670 $authorised_lib{$library->branchcode} = $library->branchname;
673 elsif ( $authorised_value eq "itemtypes" ) {
674 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
676 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
677 push @authorised_values, $itemtype;
678 $authorised_lib{$itemtype} = $description;
681 elsif ( $authorised_value eq "biblio_framework" ) {
682 my $frameworks = GetFrameworksLoop();
683 my $default_source = '';
684 push @authorised_values,$default_source;
685 $authorised_lib{$default_source} = 'Default';
686 foreach my $framework (@$frameworks) {
687 push @authorised_values, $framework->{value};
688 $authorised_lib{$framework->{value}} = $framework->{description};
691 elsif ( $authorised_value eq "cn_source" ) {
692 my $class_sources = GetClassSources();
693 my $default_source = C4::Context->preference("DefaultClassificationSource");
694 foreach my $class_source (sort keys %$class_sources) {
695 next unless $class_sources->{$class_source}->{'used'} or
696 ($class_source eq $default_source);
697 push @authorised_values, $class_source;
698 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
701 elsif ( $authorised_value eq "categorycode" ) {
702 my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']});
703 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
704 push @authorised_values, $_->categorycode for @patron_categories;
707 if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) {
709 SELECT authorised_value,lib
710 FROM authorised_values
714 my $authorised_values_sth = $dbh->prepare($query);
715 $authorised_values_sth->execute( $authorised_value);
717 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
718 push @authorised_values, $value;
719 $authorised_lib{$value} = $lib;
720 # For item location, we show the code and the libelle
721 $authorised_lib{$value} = $lib;
724 # not exists $authorised_value_categories{$authorised_value})
725 push @authval_errors, {'entry' => $text,
726 'auth_val' => $authorised_value };
727 # tell the template there's an error
728 $template->param( auth_val_error => 1 );
729 # skip scrolling list creation and params push
736 name => "sql_params",
737 id => "sql_params_".$labelid,
738 values => \@authorised_values,
739 labels => \%authorised_lib,
743 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
745 $template->param('sql' => $sql,
747 'sql_params' => \@tmpl_parameters,
748 'auth_val_errors' => \@authval_errors,
750 'reports' => $report_id,
753 # OK, we have parameters, or there are none, we run the report
754 # if there were parameters, replace before running
755 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
756 my @split = split /<<|>>/,$sql;
758 for(my $i=0;$i<$#split/2;$i++) {
759 my $quoted = $sql_params[$i];
760 # if there are special regexp chars, we must \ them
761 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
762 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
763 $quoted = output_pref({ dt => dt_from_string($quoted), dateformat => 'iso', dateonly => 1 }) if $quoted;
765 $quoted = C4::Context->dbh->quote($quoted);
766 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
768 my ($sth, $errors) = execute_query($sql, $offset, $limit);
769 my $total = nb_rows($sql) || 0;
771 die "execute_query failed to return sth for report $report_id: $sql";
773 my $headers = header_cell_loop($sth);
774 $template->param(header_row => $headers);
775 while (my $row = $sth->fetchrow_arrayref()) {
776 my @cells = map { +{ cell => $_ } } @$row;
777 push @rows, { cells => \@cells };
781 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
782 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
784 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
793 'errors' => defined($errors) ? [ $errors ] : undef,
794 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
795 'unlimited_total' => $total,
796 'sql_params' => \@sql_params,
801 push @errors, { no_sql_for_id => $report_id };
805 elsif ($phase eq 'Export'){
807 # export results to tab separated text or CSV
808 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
809 my $format = $input->param('format');
810 my $reportname = $input->param('reportname');
811 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
812 my ($sth, $q_errors) = execute_query($sql);
813 unless ($q_errors and @$q_errors) {
814 my ( $type, $content );
815 if ($format eq 'tab') {
816 $type = 'application/octet-stream';
817 $content .= join("\t", header_cell_values($sth)) . "\n";
818 $content = Encode::decode('UTF-8', $content);
819 while (my $row = $sth->fetchrow_arrayref()) {
820 $content .= join("\t", @$row) . "\n";
823 my $delimiter = C4::Context->preference('delimiter') || ',';
824 if ( $format eq 'csv' ) {
825 $type = 'application/csv';
826 my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter});
827 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
828 if ($csv->combine(header_cell_values($sth))) {
829 $content .= Encode::decode('UTF-8', $csv->string()) . "\n";
831 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
833 while (my $row = $sth->fetchrow_arrayref()) {
834 if ($csv->combine(@$row)) {
835 $content .= $csv->string() . "\n";
837 push @$q_errors, { combine => $csv->error_diag() } ;
841 elsif ( $format eq 'ods' ) {
842 $type = 'application/vnd.oasis.opendocument.spreadsheet';
843 my $ods_fh = File::Temp->new( UNLINK => 0 );
844 my $ods_filepath = $ods_fh->filename;
846 use OpenOffice::OODoc;
847 my $tmpdir = dirname $ods_filepath;
848 odfWorkingDirectory( $tmpdir );
849 my $container = odfContainer( $ods_filepath, create => 'spreadsheet' );
850 my $doc = odfDocument (
851 container => $container,
854 my $table = $doc->getTable(0);
855 my @headers = header_cell_values( $sth );
856 my $rows = $sth->fetchall_arrayref();
857 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
860 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
862 my $row = $doc->getRow( $table, 0 );
864 for my $header ( @headers ) {
865 $doc->cellValue( $row, $j, $header );
870 $row = $doc->getRow( $table, $i );
871 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
872 my $value = Encode::encode( 'UTF8', $rows->[$i - 1][$j] );
873 $doc->cellValue( $row, $j, $value );
879 open $ods_fh, '<', $ods_filepath;
880 $content .= $_ while <$ods_fh>;
881 unlink $ods_filepath;
884 print $input->header(
886 -attachment=> $reportfilename
890 foreach my $err (@$q_errors, @errors) {
891 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
892 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
898 'name' => 'Error exporting report!',
900 'errors' => $q_errors,
904 elsif ( $phase eq 'Create report from SQL' ) {
906 my ($group, $subgroup);
907 # allow the user to paste in sql
908 if ( $input->param('sql') ) {
909 $group = $input->param('report_group');
910 $subgroup = $input->param('report_subgroup');
912 'sql' => scalar $input->param('sql') // '',
913 'reportname' => scalar $input->param('reportname') // '',
914 'notes' => scalar $input->param('notes') // '',
919 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
921 'cache_expiry' => 300,
922 'usecache' => $usecache,
926 elsif ($phase eq 'Create Compound Report'){
927 $template->param( 'savedreports' => get_saved_reports(),
932 elsif ($phase eq 'Save Compound'){
933 my $master = $input->param('master');
934 my $subreport = $input->param('subreport');
935 my ($mastertables,$subtables) = create_compound($master,$subreport);
936 $template->param( 'save_compound' => 1,
937 master=>$mastertables,
942 # pass $sth, get back an array of names for the column headers
943 sub header_cell_values {
944 my $sth = shift or return ();
945 return '' unless ($sth->{NAME});
946 return @{$sth->{NAME}};
949 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
950 sub header_cell_loop {
951 my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift);
956 $template->{VARS}->{'build' . $_} and last;
958 $template->param( 'referer' => $input->referer(),
961 output_html_with_http_headers $input, $cookie, $template->output;
963 sub groups_with_subgroups {
964 my ($group, $subgroup) = @_;
966 my $groups_with_subgroups = get_report_groups();
968 my @sorted_keys = sort {
969 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
970 } keys %$groups_with_subgroups;
971 foreach my $g_id (@sorted_keys) {
972 my $v = $groups_with_subgroups->{$g_id};
974 if (my $sg = $v->{subgroups}) {
975 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
978 name => $sg->{$sg_id},
979 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
986 selected => ($group && $g_id eq $group),
987 subgroups => \@subgroups,
993 sub create_non_existing_group_and_subgroup {
994 my ($input, $group, $subgroup) = @_;
996 if (defined $group and $group ne '') {
997 my $report_groups = C4::Reports::Guided::get_report_groups;
998 if (not exists $report_groups->{$group}) {
999 my $groupdesc = $input->param('groupdesc') // $group;
1000 Koha::AuthorisedValue->new({
1001 category => 'REPORT_GROUP',
1002 authorised_value => $group,
1006 if (defined $subgroup and $subgroup ne '') {
1007 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
1008 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1009 Koha::AuthorisedValue->new({
1010 category => 'REPORT_SUBGROUP',
1011 authorised_value => $subgroup,
1012 lib => $subgroupdesc,