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
::Branch
; # XXX subfield_is_koha_internal_p
32 use C4
::Koha qw
/IsAuthorisedValueCategory GetFrameworksLoop/;
35 use Koha
::DateUtils qw
/dt_from_string output_pref/;
43 Script to control the guided report creation
48 my $usecache = C4
::Context
->ismemcached;
50 my $phase = $input->param('phase');
52 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
53 $flagsrequired = 'create_reports';
55 elsif ( $phase eq 'Use saved' ) {
56 $flagsrequired = 'execute_reports';
61 my ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
63 template_name
=> "reports/guided_reports_start.tt",
67 flagsrequired
=> { reports
=> $flagsrequired },
71 my $session = $cookie ? get_session
($cookie->value) : undef;
74 if ( $input->param("filter_set") ) {
76 $filter->{$_} = $input->param("filter_$_") foreach qw
/date author keyword group subgroup/;
77 $session->param('report_filter', $filter) if $session;
78 $template->param( 'filter_set' => 1 );
80 elsif ($session and not $input->param('clear_filters')) {
81 $filter = $session->param('report_filter');
87 $template->param( 'start' => 1 );
90 elsif ( $phase eq 'Build new' ) {
92 $template->param( 'build1' => 1 );
94 'areas' => get_report_areas
(),
95 'usecache' => $usecache,
96 'cache_expiry' => 300,
99 } elsif ( $phase eq 'Use saved' ) {
102 # get list of reports and display them
103 my $group = $input->param('group');
104 my $subgroup = $input->param('subgroup');
105 $filter->{group
} = $group;
106 $filter->{subgroup
} = $subgroup;
109 'savedreports' => get_saved_reports
($filter),
110 'usecache' => $usecache,
111 'groups_with_subgroups'=> groups_with_subgroups
($group, $subgroup),
116 elsif ( $phase eq 'Delete Multiple') {
117 my @ids = $input->param('ids');
118 delete_report
( @ids );
119 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
123 elsif ( $phase eq 'Delete Saved') {
125 # delete a report from the saved reports list
126 my $ids = $input->param('reports');
128 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
132 elsif ( $phase eq 'Show SQL'){
134 my $id = $input->param('reports');
135 my $report = get_saved_report
($id);
138 'reportname' => $report->{report_name
},
139 'notes' => $report->{notes
},
140 'sql' => $report->{savedsql
},
145 elsif ( $phase eq 'Edit SQL'){
146 my $id = $input->param('reports');
147 my $report = get_saved_report
($id);
148 my $group = $report->{report_group
};
149 my $subgroup = $report->{report_subgroup
};
151 'sql' => $report->{savedsql
},
152 'reportname' => $report->{report_name
},
153 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
154 'notes' => $report->{notes
},
156 'cache_expiry' => $report->{cache_expiry
},
157 'public' => $report->{public
},
158 'usecache' => $usecache,
163 elsif ( $phase eq 'Update SQL'){
164 my $id = $input->param('id');
165 my $sql = $input->param('sql');
166 my $reportname = $input->param('reportname');
167 my $group = $input->param('group');
168 my $subgroup = $input->param('subgroup');
169 my $notes = $input->param('notes');
170 my $cache_expiry = $input->param('cache_expiry');
171 my $cache_expiry_units = $input->param('cache_expiry_units');
172 my $public = $input->param('public');
173 my $save_anyway = $input->param('save_anyway');
177 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
178 if( $cache_expiry_units ){
179 if( $cache_expiry_units eq "minutes" ){
181 } elsif( $cache_expiry_units eq "hours" ){
182 $cache_expiry *= 3600; # 60 * 60
183 } elsif( $cache_expiry_units eq "days" ){
184 $cache_expiry *= 86400; # 60 * 60 * 24
187 # 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
188 if( $cache_expiry >= 2592000 ){
189 push @errors, {cache_expiry
=> $cache_expiry};
192 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
194 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
195 push @errors, {sqlerr
=> $1};
197 elsif ($sql !~ /^(SELECT)/i) {
198 push @errors, {queryerr
=> "No SELECT"};
203 'errors' => \
@errors,
208 # Check defined SQL parameters for authorised value validity
209 my $problematic_authvals = ValidateSQLParameters
($sql);
211 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
212 # There's at least one problematic parameter, report to the
213 # GUI and provide all user input for further actions
217 'reportname' => $reportname,
219 'subgroup' => $subgroup,
222 'problematic_authvals' => $problematic_authvals,
223 'warn_authval_problem' => 1,
228 # No params problem found or asked to save anyway
233 subgroup
=> $subgroup,
236 cache_expiry
=> $cache_expiry,
239 'save_successful' => 1,
240 'reportname' => $reportname,
243 logaction
( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4
::Context
->preference("ReportsLog");
247 cache_expiry
=> $cache_expiry,
248 cache_expiry_units
=> $cache_expiry_units,
254 elsif ($phase eq 'retrieve results') {
255 my $id = $input->param('id');
256 my ($results,$name,$notes) = format_results
($id);
260 'results' => $results,
266 elsif ( $phase eq 'Report on this Area' ) {
267 my $cache_expiry_units = $input->param('cache_expiry_units'),
268 my $cache_expiry = $input->param('cache_expiry');
270 # we need to handle converting units
271 if( $cache_expiry_units eq "minutes" ){
273 } elsif( $cache_expiry_units eq "hours" ){
274 $cache_expiry *= 3600; # 60 * 60
275 } elsif( $cache_expiry_units eq "days" ){
276 $cache_expiry *= 86400; # 60 * 60 * 24
278 # 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
279 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
280 # report error to user
284 'areas' => get_report_areas
(),
285 'cache_expiry' => $cache_expiry,
286 'usecache' => $usecache,
287 'public' => $input->param('public'),
290 # they have choosen a new report and the area to report on
293 'area' => $input->param('area'),
294 'types' => get_report_types
(),
295 'cache_expiry' => $cache_expiry,
296 'public' => $input->param('public'),
301 elsif ( $phase eq 'Choose this type' ) {
302 # they have chosen type and area
303 # get area and type and pass them to the template
304 my $area = $input->param('area');
305 my $type = $input->param('types');
310 columns
=> get_columns
($area,$input),
311 'cache_expiry' => $input->param('cache_expiry'),
312 'public' => $input->param('public'),
316 elsif ( $phase eq 'Choose these columns' ) {
317 # we now know type, area, and columns
318 # next step is the constraints
319 my $area = $input->param('area');
320 my $type = $input->param('type');
321 my @columns = $input->param('columns');
322 my $column = join( ',', @columns );
329 definitions
=> get_from_dictionary
($area),
330 criteria
=> get_criteria
($area,$input),
331 'public' => $input->param('public'),
335 cache_expiry
=> $input->param('cache_expiry'),
336 cache_expiry_units
=> $input->param('cache_expiry_units'),
342 elsif ( $phase eq 'Choose these criteria' ) {
343 my $area = $input->param('area');
344 my $type = $input->param('type');
345 my $column = $input->param('column');
346 my @definitions = $input->param('definition');
347 my $definition = join (',',@definitions);
348 my @criteria = $input->param('criteria_column');
350 foreach my $crit (@criteria) {
351 my $value = $input->param( $crit . "_value" );
353 # If value is not defined, then it may be range values
354 if (!defined $value) {
356 my $fromvalue = $input->param( "from_" . $crit . "_value" );
357 my $tovalue = $input->param( "to_" . $crit . "_value" );
359 # If the range values are dates
360 if ($fromvalue =~ C4
::Dates
->regexp('syspref') && $tovalue =~ C4
::Dates
->regexp('syspref')) {
361 $fromvalue = C4
::Dates
->new($fromvalue)->output("iso");
362 $tovalue = C4
::Dates
->new($tovalue)->output("iso");
365 if ($fromvalue && $tovalue) {
366 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
372 if ($value =~ C4
::Dates
->regexp('syspref')) {
373 $value = C4
::Dates
->new($value)->output("iso");
375 # don't escape runtime parameters, they'll be at runtime
376 if ($value =~ /<<.*>>/) {
377 $query_criteria .= " AND $crit=$value";
379 $query_criteria .= " AND $crit='$value'";
388 'definition' => $definition,
389 'criteriastring' => $query_criteria,
390 'public' => $input->param('public'),
394 cache_expiry
=> $input->param('cache_expiry'),
395 cache_expiry_units
=> $input->param('cache_expiry_units'),
400 my @columns = split( ',', $column );
403 # build structue for use by tmpl_loop to choose columns to order by
404 # need to do something about the order of the order :)
405 # we also want to use the %columns hash to get the plain english names
406 foreach my $col (@columns) {
407 my %total = (name
=> $col);
408 my @selects = map {+{ value
=> $_ }} (qw(sum min max avg count));
409 $total{'select'} = \
@selects;
410 push @total_by, \
%total;
413 $template->param( 'total_by' => \
@total_by );
416 elsif ( $phase eq 'Choose these operations' ) {
417 my $area = $input->param('area');
418 my $type = $input->param('type');
419 my $column = $input->param('column');
420 my $criteria = $input->param('criteria');
421 my $definition = $input->param('definition');
422 my @total_by = $input->param('total_by');
424 foreach my $total (@total_by) {
425 my $value = $input->param( $total . "_tvalue" );
426 $totals .= "$value($total),";
434 'criteriastring' => $criteria,
436 'definition' => $definition,
437 'cache_expiry' => $input->param('cache_expiry'),
438 'public' => $input->param('public'),
442 my @columns = split( ',', $column );
445 # build structue for use by tmpl_loop to choose columns to order by
446 # need to do something about the order of the order :)
447 foreach my $col (@columns) {
448 my %order = (name
=> $col);
449 my @selects = map {+{ value
=> $_ }} (qw(asc desc));
450 $order{'select'} = \
@selects;
451 push @order_by, \
%order;
454 $template->param( 'order_by' => \
@order_by );
457 elsif ( $phase eq 'Build report' ) {
459 # now we have all the info we need and can build the sql
460 my $area = $input->param('area');
461 my $type = $input->param('type');
462 my $column = $input->param('column');
463 my $crit = $input->param('criteria');
464 my $totals = $input->param('totals');
465 my $definition = $input->param('definition');
466 my $query_criteria=$crit;
467 # split the columns up by ,
468 my @columns = split( ',', $column );
469 my @order_by = $input->param('order_by');
472 foreach my $order (@order_by) {
473 my $value = $input->param( $order . "_ovalue" );
474 if ($query_orderby) {
475 $query_orderby .= ",$order $value";
478 $query_orderby = " ORDER BY $order $value";
484 build_query
( \
@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
490 'cache_expiry' => $input->param('cache_expiry'),
491 'public' => $input->param('public'),
495 elsif ( $phase eq 'Save' ) {
496 # Save the report that has just been built
497 my $area = $input->param('area');
498 my $sql = $input->param('sql');
499 my $type = $input->param('type');
505 'cache_expiry' => $input->param('cache_expiry'),
506 'public' => $input->param('public'),
507 'groups_with_subgroups' => groups_with_subgroups
($area), # in case we have a report group that matches area
511 elsif ( $phase eq 'Save Report' ) {
512 # save the sql pasted in by a user
513 my $area = $input->param('area');
514 my $group = $input->param('group');
515 my $subgroup = $input->param('subgroup');
516 my $sql = $input->param('sql');
517 my $name = $input->param('reportname');
518 my $type = $input->param('types');
519 my $notes = $input->param('notes');
520 my $cache_expiry = $input->param('cache_expiry');
521 my $cache_expiry_units = $input->param('cache_expiry_units');
522 my $public = $input->param('public');
523 my $save_anyway = $input->param('save_anyway');
526 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
527 if( $cache_expiry_units ){
528 if( $cache_expiry_units eq "minutes" ){
530 } elsif( $cache_expiry_units eq "hours" ){
531 $cache_expiry *= 3600; # 60 * 60
532 } elsif( $cache_expiry_units eq "days" ){
533 $cache_expiry *= 86400; # 60 * 60 * 24
536 # 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
537 if( $cache_expiry && $cache_expiry >= 2592000 ){
538 push @errors, {cache_expiry
=> $cache_expiry};
541 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
543 ## FIXME this is AFTER entering a name to save the report under
544 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
545 push @errors, {sqlerr
=> $1};
547 elsif ($sql !~ /^(SELECT)/i) {
548 push @errors, {queryerr
=> "No SELECT"};
553 'errors' => \
@errors,
555 'reportname'=> $name,
558 'cache_expiry' => $cache_expiry,
562 # Check defined SQL parameters for authorised value validity
563 my $problematic_authvals = ValidateSQLParameters
($sql);
565 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
566 # There's at least one problematic parameter, report to the
567 # GUI and provide all user input for further actions
571 'subgroup' => $subgroup,
573 'reportname' => $name,
577 'problematic_authvals' => $problematic_authvals,
578 'warn_authval_problem' => 1,
583 cache_expiry
=> $cache_expiry,
584 cache_expiry_units
=> $cache_expiry_units,
588 # No params problem found or asked to save anyway
589 my $id = save_report
( {
590 borrowernumber
=> $borrowernumber,
595 subgroup
=> $subgroup,
598 cache_expiry
=> $cache_expiry,
601 logaction
( "REPORTS", "ADD", $id, "$name | $sql" ) if C4
::Context
->preference("ReportsLog");
603 'save_successful' => 1,
604 'reportname' => $name,
611 elsif ($phase eq 'Run this report'){
612 # execute a saved report
613 my $limit = $input->param('limit') || 20;
615 my $report_id = $input->param('reports');
616 my @sql_params = $input->param('sql_params');
618 if ($input->param('page')) {
619 $offset = ($input->param('page') - 1) * $limit;
624 'report_id' => $report_id,
627 my ( $sql, $type, $name, $notes );
628 if (my $report = get_saved_report
($report_id)) {
629 $sql = $report->{savedsql
};
630 $name = $report->{report_name
};
631 $notes = $report->{notes
};
634 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
635 if ($sql =~ /<</ && !@sql_params) {
636 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
637 my @split = split /<<|>>/,$sql;
640 for(my $i=0;$i<($#split/2);$i++) {
641 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
644 if ( not defined $authorised_value ) {
645 # no authorised value input, provide a text box
647 } elsif ( $authorised_value eq "date" ) {
648 # require a date, provide a date picker
651 # defined $authorised_value, and not 'date'
652 my $dbh=C4
::Context
->dbh;
653 my @authorised_values;
655 # builds list, depending on authorised value...
656 if ( $authorised_value eq "branches" ) {
657 my $branches = GetBranchesLoop
();
658 foreach my $thisbranch (@
$branches) {
659 push @authorised_values, $thisbranch->{value
};
660 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
663 elsif ( $authorised_value eq "itemtypes" ) {
664 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
666 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
667 push @authorised_values, $itemtype;
668 $authorised_lib{$itemtype} = $description;
671 elsif ( $authorised_value eq "biblio_framework" ) {
672 my $frameworks = GetFrameworksLoop
();
673 my $default_source = '';
674 push @authorised_values,$default_source;
675 $authorised_lib{$default_source} = 'Default';
676 foreach my $framework (@
$frameworks) {
677 push @authorised_values, $framework->{value
};
678 $authorised_lib{$framework->{value
}} = $framework->{description
};
681 elsif ( $authorised_value eq "cn_source" ) {
682 my $class_sources = GetClassSources
();
683 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
684 foreach my $class_source (sort keys %$class_sources) {
685 next unless $class_sources->{$class_source}->{'used'} or
686 ($class_source eq $default_source);
687 push @authorised_values, $class_source;
688 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
691 elsif ( $authorised_value eq "categorycode" ) {
692 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
694 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
695 push @authorised_values, $categorycode;
696 $authorised_lib{$categorycode} = $description;
699 #---- "true" authorised value
702 if ( IsAuthorisedValueCategory
($authorised_value) ) {
704 SELECT authorised_value,lib
705 FROM authorised_values
709 my $authorised_values_sth = $dbh->prepare($query);
710 $authorised_values_sth->execute( $authorised_value);
712 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
713 push @authorised_values, $value;
714 $authorised_lib{$value} = $lib;
715 # For item location, we show the code and the libelle
716 $authorised_lib{$value} = $lib;
719 # not exists $authorised_value_categories{$authorised_value})
720 push @authval_errors, {'entry' => $text,
721 'auth_val' => $authorised_value };
722 # tell the template there's an error
723 $template->param( auth_val_error
=> 1 );
724 # skip scrolling list creation and params push
731 name
=> "sql_params",
732 id
=> "sql_params_".$labelid,
733 values => \
@authorised_values,
734 labels
=> \
%authorised_lib,
738 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
740 $template->param('sql' => $sql,
742 'sql_params' => \
@tmpl_parameters,
743 'auth_val_errors' => \
@authval_errors,
745 'reports' => $report_id,
748 # OK, we have parameters, or there are none, we run the report
749 # if there were parameters, replace before running
750 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
751 my @split = split /<<|>>/,$sql;
753 for(my $i=0;$i<$#split/2;$i++) {
754 my $quoted = $sql_params[$i];
755 # if there are special regexp chars, we must \ them
756 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
757 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
758 $quoted = output_pref
({ dt
=> dt_from_string
($quoted), dateformat
=> 'iso', dateonly
=> 1 }) if $quoted;
760 $quoted = C4
::Context
->dbh->quote($quoted);
761 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
763 my ($sth, $errors) = execute_query
($sql, $offset, $limit);
764 my $total = nb_rows
($sql) || 0;
766 die "execute_query failed to return sth for report $report_id: $sql";
768 my $headers= header_cell_loop
($sth);
769 $template->param(header_row
=> $headers);
770 while (my $row = $sth->fetchrow_arrayref()) {
771 my @cells = map { +{ cell
=> $_ } } @
$row;
772 push @rows, { cells
=> \
@cells };
776 my $totpages = int($total/$limit) + (($total % $limit) > 0 ?
1 : 0);
777 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
779 $url = join('&sql_params=', $url, map { URI
::Escape
::uri_escape_utf8
($_) } @sql_params);
788 'errors' => defined($errors) ?
[ $errors ] : undef,
789 'pagination_bar' => pagination_bar
($url, $totpages, $input->param('page')),
790 'unlimited_total' => $total,
791 'sql_params' => \
@sql_params,
796 push @errors, { no_sql_for_id
=> $report_id };
800 elsif ($phase eq 'Export'){
802 # export results to tab separated text or CSV
803 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
804 my $format = $input->param('format');
805 my $reportname = $input->param('reportname');
806 my $reportfilename = $reportname ?
"$reportname-reportresults.$format" : "reportresults.$format" ;
807 my ($sth, $q_errors) = execute_query
($sql);
808 unless ($q_errors and @
$q_errors) {
809 my ( $type, $content );
810 if ($format eq 'tab') {
811 $type = 'application/octet-stream';
812 $content .= join("\t", header_cell_values
($sth)) . "\n";
813 while (my $row = $sth->fetchrow_arrayref()) {
814 $content .= join("\t", @
$row) . "\n";
817 my $delimiter = C4
::Context
->preference('delimiter') || ',';
818 if ( $format eq 'csv' ) {
819 $type = 'application/csv';
820 my $csv = Text
::CSV
::Encoded
->new({ encoding_out
=> 'utf8', sep_char
=> $delimiter});
821 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text
::CSV
::Encoded
->error_diag();
822 if ($csv->combine(header_cell_values
($sth))) {
823 $content .= $csv->string(). "\n";
825 push @
$q_errors, { combine
=> 'HEADER ROW: ' . $csv->error_diag() } ;
827 while (my $row = $sth->fetchrow_arrayref()) {
828 if ($csv->combine(@
$row)) {
829 $content .= $csv->string() . "\n";
831 push @
$q_errors, { combine
=> $csv->error_diag() } ;
835 elsif ( $format eq 'ods' ) {
836 $type = 'application/vnd.oasis.opendocument.spreadsheet';
837 my $ods_fh = File
::Temp
->new( UNLINK
=> 0 );
838 my $ods_filepath = $ods_fh->filename;
840 use OpenOffice
::OODoc
;
841 my $tmpdir = dirname
$ods_filepath;
842 odfWorkingDirectory
( $tmpdir );
843 my $container = odfContainer
( $ods_filepath, create
=> 'spreadsheet' );
844 my $doc = odfDocument
(
845 container
=> $container,
848 my $table = $doc->getTable(0);
849 my @headers = header_cell_values
( $sth );
850 my $rows = $sth->fetchall_arrayref();
851 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
854 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
856 my $row = $doc->getRow( $table, 0 );
858 for my $header ( @headers ) {
859 $doc->cellValue( $row, $j, $header );
864 $row = $doc->getRow( $table, $i );
865 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
866 my $value = Encode
::encode
( 'UTF8', $rows->[$i - 1][$j] );
867 $doc->cellValue( $row, $j, $value );
873 open $ods_fh, '<', $ods_filepath;
874 $content .= $_ while <$ods_fh>;
875 unlink $ods_filepath;
878 print $input->header(
880 -attachment
=> $reportfilename
884 foreach my $err (@
$q_errors, @errors) {
885 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
886 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
892 'name' => 'Error exporting report!',
894 'errors' => $q_errors,
898 elsif ( $phase eq 'Create report from SQL' ) {
900 my ($group, $subgroup);
901 # allow the user to paste in sql
902 if ( $input->param('sql') ) {
903 $group = $input->param('report_group');
904 $subgroup = $input->param('report_subgroup');
906 'sql' => $input->param('sql') // '',
907 'reportname' => $input->param('reportname') // '',
908 'notes' => $input->param('notes') // '',
913 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
915 'cache_expiry' => 300,
916 'usecache' => $usecache,
920 elsif ($phase eq 'Create Compound Report'){
921 $template->param( 'savedreports' => get_saved_reports
(),
926 elsif ($phase eq 'Save Compound'){
927 my $master = $input->param('master');
928 my $subreport = $input->param('subreport');
929 my ($mastertables,$subtables) = create_compound
($master,$subreport);
930 $template->param( 'save_compound' => 1,
931 master
=>$mastertables,
936 # pass $sth, get back an array of names for the column headers
937 sub header_cell_values
{
938 my $sth = shift or return ();
939 return '' unless ($sth->{NAME
});
940 return @
{$sth->{NAME
}};
943 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
944 sub header_cell_loop
{
945 my @headers = map { +{ cell
=> $_ } } header_cell_values
(shift);
950 $template->{VARS
}->{'build' . $_} and $template->{VARS
}->{'buildx' . $_} and last;
952 $template->param( 'referer' => $input->referer(),
955 output_html_with_http_headers
$input, $cookie, $template->output;
957 sub groups_with_subgroups
{
958 my ($group, $subgroup) = @_;
960 my $groups_with_subgroups = get_report_groups
();
962 my @sorted_keys = sort {
963 $groups_with_subgroups->{$a}->{name
} cmp $groups_with_subgroups->{$b}->{name
}
964 } keys %$groups_with_subgroups;
965 foreach my $g_id (@sorted_keys) {
966 my $v = $groups_with_subgroups->{$g_id};
968 if (my $sg = $v->{subgroups
}) {
969 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
972 name
=> $sg->{$sg_id},
973 selected
=> ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
980 selected
=> ($group && $g_id eq $group),
981 subgroups
=> \
@subgroups,
987 sub create_non_existing_group_and_subgroup
{
988 my ($input, $group, $subgroup) = @_;
990 if (defined $group and $group ne '') {
991 my $report_groups = C4
::Reports
::Guided
::get_report_groups
;
992 if (not exists $report_groups->{$group}) {
993 my $groupdesc = $input->param('groupdesc') // $group;
994 C4
::Koha
::AddAuthorisedValue
('REPORT_GROUP', $group, $groupdesc);
996 if (defined $subgroup and $subgroup ne '') {
997 if (not exists $report_groups->{$group}->{subgroups
}->{$subgroup}) {
998 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
999 C4
::Koha
::AddAuthorisedValue
('REPORT_SUBGROUP', $subgroup, $subgroupdesc, $group);