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
;
45 Script to control the guided report creation
50 my $usecache = C4
::Context
->ismemcached;
52 my $phase = $input->param('phase') // '';
54 if ( $phase eq 'Build new' or $phase eq 'Delete Saved' ) {
55 $flagsrequired = 'create_reports';
57 elsif ( $phase eq 'Use saved' ) {
58 $flagsrequired = 'execute_reports';
63 my ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
65 template_name
=> "reports/guided_reports_start.tt",
69 flagsrequired
=> { reports
=> $flagsrequired },
73 my $session = $cookie ? get_session
($cookie->value) : undef;
76 if ( $input->param("filter_set") ) {
78 $filter->{$_} = $input->param("filter_$_") foreach qw
/date author keyword group subgroup/;
79 $session->param('report_filter', $filter) if $session;
80 $template->param( 'filter_set' => 1 );
82 elsif ($session and not $input->param('clear_filters')) {
83 $filter = $session->param('report_filter');
89 $template->param( 'start' => 1 );
92 elsif ( $phase eq 'Build new' ) {
94 $template->param( 'build1' => 1 );
96 'areas' => get_report_areas
(),
97 'usecache' => $usecache,
98 'cache_expiry' => 300,
101 } elsif ( $phase eq 'Use saved' ) {
104 # get list of reports and display them
105 my $group = $input->param('group');
106 my $subgroup = $input->param('subgroup');
107 $filter->{group
} = $group;
108 $filter->{subgroup
} = $subgroup;
111 'savedreports' => get_saved_reports
($filter),
112 'usecache' => $usecache,
113 'groups_with_subgroups'=> groups_with_subgroups
($group, $subgroup),
118 elsif ( $phase eq 'Delete Multiple') {
119 my @ids = $input->param('ids');
120 delete_report
( @ids );
121 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
125 elsif ( $phase eq 'Delete Saved') {
127 # delete a report from the saved reports list
128 my $ids = $input->param('reports');
130 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
134 elsif ( $phase eq 'Show SQL'){
136 my $id = $input->param('reports');
137 my $report = get_saved_report
($id);
140 'reportname' => $report->{report_name
},
141 'notes' => $report->{notes
},
142 'sql' => $report->{savedsql
},
147 elsif ( $phase eq 'Edit SQL'){
148 my $id = $input->param('reports');
149 my $report = get_saved_report
($id);
150 my $group = $report->{report_group
};
151 my $subgroup = $report->{report_subgroup
};
153 'sql' => $report->{savedsql
},
154 'reportname' => $report->{report_name
},
155 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
156 'notes' => $report->{notes
},
158 'cache_expiry' => $report->{cache_expiry
},
159 'public' => $report->{public
},
160 'usecache' => $usecache,
165 elsif ( $phase eq 'Update SQL'){
166 my $id = $input->param('id');
167 my $sql = $input->param('sql');
168 my $reportname = $input->param('reportname');
169 my $group = $input->param('group');
170 my $subgroup = $input->param('subgroup');
171 my $notes = $input->param('notes');
172 my $cache_expiry = $input->param('cache_expiry');
173 my $cache_expiry_units = $input->param('cache_expiry_units');
174 my $public = $input->param('public');
175 my $save_anyway = $input->param('save_anyway');
179 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
180 if( $cache_expiry_units ){
181 if( $cache_expiry_units eq "minutes" ){
183 } elsif( $cache_expiry_units eq "hours" ){
184 $cache_expiry *= 3600; # 60 * 60
185 } elsif( $cache_expiry_units eq "days" ){
186 $cache_expiry *= 86400; # 60 * 60 * 24
189 # 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
190 if( $cache_expiry >= 2592000 ){
191 push @errors, {cache_expiry
=> $cache_expiry};
194 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
196 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
197 push @errors, {sqlerr
=> $1};
199 elsif ($sql !~ /^(SELECT)/i) {
200 push @errors, {queryerr
=> "No SELECT"};
205 'errors' => \
@errors,
210 # Check defined SQL parameters for authorised value validity
211 my $problematic_authvals = ValidateSQLParameters
($sql);
213 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
214 # There's at least one problematic parameter, report to the
215 # GUI and provide all user input for further actions
219 'reportname' => $reportname,
221 'subgroup' => $subgroup,
224 'problematic_authvals' => $problematic_authvals,
225 'warn_authval_problem' => 1,
230 # No params problem found or asked to save anyway
235 subgroup
=> $subgroup,
238 cache_expiry
=> $cache_expiry,
241 'save_successful' => 1,
242 'reportname' => $reportname,
245 logaction
( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4
::Context
->preference("ReportsLog");
249 cache_expiry
=> $cache_expiry,
250 cache_expiry_units
=> $cache_expiry_units,
256 elsif ($phase eq 'retrieve results') {
257 my $id = $input->param('id');
258 my ($results,$name,$notes) = format_results
($id);
262 'results' => $results,
268 elsif ( $phase eq 'Report on this Area' ) {
269 my $cache_expiry_units = $input->param('cache_expiry_units'),
270 my $cache_expiry = $input->param('cache_expiry');
272 # we need to handle converting units
273 if( $cache_expiry_units eq "minutes" ){
275 } elsif( $cache_expiry_units eq "hours" ){
276 $cache_expiry *= 3600; # 60 * 60
277 } elsif( $cache_expiry_units eq "days" ){
278 $cache_expiry *= 86400; # 60 * 60 * 24
280 # 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
281 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
282 # report error to user
286 'areas' => get_report_areas
(),
287 'cache_expiry' => $cache_expiry,
288 'usecache' => $usecache,
289 'public' => $input->param('public'),
292 # they have choosen a new report and the area to report on
295 'area' => $input->param('area'),
296 'types' => get_report_types
(),
297 'cache_expiry' => $cache_expiry,
298 'public' => $input->param('public'),
303 elsif ( $phase eq 'Choose this type' ) {
304 # they have chosen type and area
305 # get area and type and pass them to the template
306 my $area = $input->param('area');
307 my $type = $input->param('types');
312 columns
=> get_columns
($area,$input),
313 'cache_expiry' => $input->param('cache_expiry'),
314 'public' => $input->param('public'),
318 elsif ( $phase eq 'Choose these columns' ) {
319 # we now know type, area, and columns
320 # next step is the constraints
321 my $area = $input->param('area');
322 my $type = $input->param('type');
323 my @columns = $input->param('columns');
324 my $column = join( ',', @columns );
331 definitions
=> get_from_dictionary
($area),
332 criteria
=> get_criteria
($area,$input),
333 'public' => $input->param('public'),
337 cache_expiry
=> $input->param('cache_expiry'),
338 cache_expiry_units
=> $input->param('cache_expiry_units'),
344 elsif ( $phase eq 'Choose these criteria' ) {
345 my $area = $input->param('area');
346 my $type = $input->param('type');
347 my $column = $input->param('column');
348 my @definitions = $input->param('definition');
349 my $definition = join (',',@definitions);
350 my @criteria = $input->param('criteria_column');
352 foreach my $crit (@criteria) {
353 my $value = $input->param( $crit . "_value" );
355 # If value is not defined, then it may be range values
356 if (!defined $value) {
358 my $fromvalue = $input->param( "from_" . $crit . "_value" );
359 my $tovalue = $input->param( "to_" . $crit . "_value" );
361 # If the range values are dates
363 $fromvalue_dt = eval { dt_from_string
( $fromvalue ); } if ( $fromvalue );
365 $tovalue_dt = eval { dt_from_string
( $tovalue ); } if ($tovalue);
366 if ( $fromvalue_dt && $tovalue_dt ) {
367 $fromvalue = output_pref
( { dt
=> dt_from_string
( $fromvalue_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
368 $tovalue = output_pref
( { dt
=> dt_from_string
( $tovalue_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
371 if ($fromvalue && $tovalue) {
372 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
379 $value_dt = eval { dt_from_string
( $value ); } if ( $value );
381 $value = output_pref
( { dt
=> dt_from_string
( $value_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
383 # don't escape runtime parameters, they'll be at runtime
384 if ($value =~ /<<.*>>/) {
385 $query_criteria .= " AND $crit=$value";
387 $query_criteria .= " AND $crit='$value'";
396 'definition' => $definition,
397 'criteriastring' => $query_criteria,
398 'public' => $input->param('public'),
402 cache_expiry
=> $input->param('cache_expiry'),
403 cache_expiry_units
=> $input->param('cache_expiry_units'),
408 my @columns = split( ',', $column );
411 # build structue for use by tmpl_loop to choose columns to order by
412 # need to do something about the order of the order :)
413 # we also want to use the %columns hash to get the plain english names
414 foreach my $col (@columns) {
415 my %total = (name
=> $col);
416 my @selects = map {+{ value
=> $_ }} (qw(sum min max avg count));
417 $total{'select'} = \
@selects;
418 push @total_by, \
%total;
421 $template->param( 'total_by' => \
@total_by );
424 elsif ( $phase eq 'Choose these operations' ) {
425 my $area = $input->param('area');
426 my $type = $input->param('type');
427 my $column = $input->param('column');
428 my $criteria = $input->param('criteria');
429 my $definition = $input->param('definition');
430 my @total_by = $input->param('total_by');
432 foreach my $total (@total_by) {
433 my $value = $input->param( $total . "_tvalue" );
434 $totals .= "$value($total),";
442 'criteriastring' => $criteria,
444 'definition' => $definition,
445 'cache_expiry' => $input->param('cache_expiry'),
446 'public' => $input->param('public'),
450 my @columns = split( ',', $column );
453 # build structue for use by tmpl_loop to choose columns to order by
454 # need to do something about the order of the order :)
455 foreach my $col (@columns) {
456 my %order = (name
=> $col);
457 my @selects = map {+{ value
=> $_ }} (qw(asc desc));
458 $order{'select'} = \
@selects;
459 push @order_by, \
%order;
462 $template->param( 'order_by' => \
@order_by );
465 elsif ( $phase eq 'Build report' ) {
467 # now we have all the info we need and can build the sql
468 my $area = $input->param('area');
469 my $type = $input->param('type');
470 my $column = $input->param('column');
471 my $crit = $input->param('criteria');
472 my $totals = $input->param('totals');
473 my $definition = $input->param('definition');
474 my $query_criteria=$crit;
475 # split the columns up by ,
476 my @columns = split( ',', $column );
477 my @order_by = $input->param('order_by');
480 foreach my $order (@order_by) {
481 my $value = $input->param( $order . "_ovalue" );
482 if ($query_orderby) {
483 $query_orderby .= ",$order $value";
486 $query_orderby = " ORDER BY $order $value";
492 build_query
( \
@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
498 'cache_expiry' => $input->param('cache_expiry'),
499 'public' => $input->param('public'),
503 elsif ( $phase eq 'Save' ) {
504 # Save the report that has just been built
505 my $area = $input->param('area');
506 my $sql = $input->param('sql');
507 my $type = $input->param('type');
513 'cache_expiry' => $input->param('cache_expiry'),
514 'public' => $input->param('public'),
515 'groups_with_subgroups' => groups_with_subgroups
($area), # in case we have a report group that matches area
519 elsif ( $phase eq 'Save Report' ) {
520 # save the sql pasted in by a user
521 my $area = $input->param('area');
522 my $group = $input->param('group');
523 my $subgroup = $input->param('subgroup');
524 my $sql = $input->param('sql');
525 my $name = $input->param('reportname');
526 my $type = $input->param('types');
527 my $notes = $input->param('notes');
528 my $cache_expiry = $input->param('cache_expiry');
529 my $cache_expiry_units = $input->param('cache_expiry_units');
530 my $public = $input->param('public');
531 my $save_anyway = $input->param('save_anyway');
534 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
535 if( $cache_expiry_units ){
536 if( $cache_expiry_units eq "minutes" ){
538 } elsif( $cache_expiry_units eq "hours" ){
539 $cache_expiry *= 3600; # 60 * 60
540 } elsif( $cache_expiry_units eq "days" ){
541 $cache_expiry *= 86400; # 60 * 60 * 24
544 # 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
545 if( $cache_expiry && $cache_expiry >= 2592000 ){
546 push @errors, {cache_expiry
=> $cache_expiry};
549 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
551 ## FIXME this is AFTER entering a name to save the report under
552 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
553 push @errors, {sqlerr
=> $1};
555 elsif ($sql !~ /^(SELECT)/i) {
556 push @errors, {queryerr
=> "No SELECT"};
561 'errors' => \
@errors,
563 'reportname'=> $name,
566 'cache_expiry' => $cache_expiry,
570 # Check defined SQL parameters for authorised value validity
571 my $problematic_authvals = ValidateSQLParameters
($sql);
573 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
574 # There's at least one problematic parameter, report to the
575 # GUI and provide all user input for further actions
579 'subgroup' => $subgroup,
581 'reportname' => $name,
585 'problematic_authvals' => $problematic_authvals,
586 'warn_authval_problem' => 1,
591 cache_expiry
=> $cache_expiry,
592 cache_expiry_units
=> $cache_expiry_units,
596 # No params problem found or asked to save anyway
597 my $id = save_report
( {
598 borrowernumber
=> $borrowernumber,
603 subgroup
=> $subgroup,
606 cache_expiry
=> $cache_expiry,
609 logaction
( "REPORTS", "ADD", $id, "$name | $sql" ) if C4
::Context
->preference("ReportsLog");
611 'save_successful' => 1,
612 'reportname' => $name,
619 elsif ($phase eq 'Run this report'){
620 # execute a saved report
621 my $limit = $input->param('limit') || 20;
623 my $report_id = $input->param('reports');
624 my @sql_params = $input->param('sql_params');
626 if ($input->param('page')) {
627 $offset = ($input->param('page') - 1) * $limit;
632 'report_id' => $report_id,
635 my ( $sql, $type, $name, $notes );
636 if (my $report = get_saved_report
($report_id)) {
637 $sql = $report->{savedsql
};
638 $name = $report->{report_name
};
639 $notes = $report->{notes
};
642 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
643 if ($sql =~ /<</ && !@sql_params) {
644 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
645 my @split = split /<<|>>/,$sql;
648 for(my $i=0;$i<($#split/2);$i++) {
649 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
652 if ( not defined $authorised_value ) {
653 # no authorised value input, provide a text box
655 } elsif ( $authorised_value eq "date" ) {
656 # require a date, provide a date picker
659 # defined $authorised_value, and not 'date'
660 my $dbh=C4
::Context
->dbh;
661 my @authorised_values;
663 # builds list, depending on authorised value...
664 if ( $authorised_value eq "branches" ) {
665 my $branches = GetBranchesLoop
();
666 foreach my $thisbranch (@
$branches) {
667 push @authorised_values, $thisbranch->{value
};
668 $authorised_lib{$thisbranch->{value
}} = $thisbranch->{branchname
};
671 elsif ( $authorised_value eq "itemtypes" ) {
672 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
674 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
675 push @authorised_values, $itemtype;
676 $authorised_lib{$itemtype} = $description;
679 elsif ( $authorised_value eq "biblio_framework" ) {
680 my $frameworks = GetFrameworksLoop
();
681 my $default_source = '';
682 push @authorised_values,$default_source;
683 $authorised_lib{$default_source} = 'Default';
684 foreach my $framework (@
$frameworks) {
685 push @authorised_values, $framework->{value
};
686 $authorised_lib{$framework->{value
}} = $framework->{description
};
689 elsif ( $authorised_value eq "cn_source" ) {
690 my $class_sources = GetClassSources
();
691 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
692 foreach my $class_source (sort keys %$class_sources) {
693 next unless $class_sources->{$class_source}->{'used'} or
694 ($class_source eq $default_source);
695 push @authorised_values, $class_source;
696 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
699 elsif ( $authorised_value eq "categorycode" ) {
700 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
702 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
703 push @authorised_values, $categorycode;
704 $authorised_lib{$categorycode} = $description;
707 #---- "true" authorised value
710 if ( Koha
::AuthorisedValues
->search({ category
=> $authorised_value })->count ) {
712 SELECT authorised_value,lib
713 FROM authorised_values
717 my $authorised_values_sth = $dbh->prepare($query);
718 $authorised_values_sth->execute( $authorised_value);
720 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
721 push @authorised_values, $value;
722 $authorised_lib{$value} = $lib;
723 # For item location, we show the code and the libelle
724 $authorised_lib{$value} = $lib;
727 # not exists $authorised_value_categories{$authorised_value})
728 push @authval_errors, {'entry' => $text,
729 'auth_val' => $authorised_value };
730 # tell the template there's an error
731 $template->param( auth_val_error
=> 1 );
732 # skip scrolling list creation and params push
739 name
=> "sql_params",
740 id
=> "sql_params_".$labelid,
741 values => \
@authorised_values,
742 labels
=> \
%authorised_lib,
746 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
748 $template->param('sql' => $sql,
750 'sql_params' => \
@tmpl_parameters,
751 'auth_val_errors' => \
@authval_errors,
753 'reports' => $report_id,
756 # OK, we have parameters, or there are none, we run the report
757 # if there were parameters, replace before running
758 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
759 my @split = split /<<|>>/,$sql;
761 for(my $i=0;$i<$#split/2;$i++) {
762 my $quoted = $sql_params[$i];
763 # if there are special regexp chars, we must \ them
764 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
765 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
766 $quoted = output_pref
({ dt
=> dt_from_string
($quoted), dateformat
=> 'iso', dateonly
=> 1 }) if $quoted;
768 $quoted = C4
::Context
->dbh->quote($quoted);
769 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
771 my ($sth, $errors) = execute_query
($sql, $offset, $limit);
772 my $total = nb_rows
($sql) || 0;
774 die "execute_query failed to return sth for report $report_id: $sql";
776 my $headers = header_cell_loop
($sth);
777 $template->param(header_row
=> $headers);
778 while (my $row = $sth->fetchrow_arrayref()) {
779 my @cells = map { +{ cell
=> $_ } } @
$row;
780 push @rows, { cells
=> \
@cells };
784 my $totpages = int($total/$limit) + (($total % $limit) > 0 ?
1 : 0);
785 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
787 $url = join('&sql_params=', $url, map { URI
::Escape
::uri_escape_utf8
($_) } @sql_params);
796 'errors' => defined($errors) ?
[ $errors ] : undef,
797 'pagination_bar' => pagination_bar
($url, $totpages, $input->param('page')),
798 'unlimited_total' => $total,
799 'sql_params' => \
@sql_params,
804 push @errors, { no_sql_for_id
=> $report_id };
808 elsif ($phase eq 'Export'){
810 # export results to tab separated text or CSV
811 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
812 my $format = $input->param('format');
813 my $reportname = $input->param('reportname');
814 my $reportfilename = $reportname ?
"$reportname-reportresults.$format" : "reportresults.$format" ;
815 my ($sth, $q_errors) = execute_query
($sql);
816 unless ($q_errors and @
$q_errors) {
817 my ( $type, $content );
818 if ($format eq 'tab') {
819 $type = 'application/octet-stream';
820 $content .= join("\t", header_cell_values
($sth)) . "\n";
821 $content = Encode
::decode
('UTF-8', $content);
822 while (my $row = $sth->fetchrow_arrayref()) {
823 $content .= join("\t", @
$row) . "\n";
826 my $delimiter = C4
::Context
->preference('delimiter') || ',';
827 if ( $format eq 'csv' ) {
828 $type = 'application/csv';
829 my $csv = Text
::CSV
::Encoded
->new({ encoding_out
=> 'UTF-8', sep_char
=> $delimiter});
830 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text
::CSV
::Encoded
->error_diag();
831 if ($csv->combine(header_cell_values
($sth))) {
832 $content .= Encode
::decode
('UTF-8', $csv->string()) . "\n";
834 push @
$q_errors, { combine
=> 'HEADER ROW: ' . $csv->error_diag() } ;
836 while (my $row = $sth->fetchrow_arrayref()) {
837 if ($csv->combine(@
$row)) {
838 $content .= $csv->string() . "\n";
840 push @
$q_errors, { combine
=> $csv->error_diag() } ;
844 elsif ( $format eq 'ods' ) {
845 $type = 'application/vnd.oasis.opendocument.spreadsheet';
846 my $ods_fh = File
::Temp
->new( UNLINK
=> 0 );
847 my $ods_filepath = $ods_fh->filename;
849 use OpenOffice
::OODoc
;
850 my $tmpdir = dirname
$ods_filepath;
851 odfWorkingDirectory
( $tmpdir );
852 my $container = odfContainer
( $ods_filepath, create
=> 'spreadsheet' );
853 my $doc = odfDocument
(
854 container
=> $container,
857 my $table = $doc->getTable(0);
858 my @headers = header_cell_values
( $sth );
859 my $rows = $sth->fetchall_arrayref();
860 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
863 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
865 my $row = $doc->getRow( $table, 0 );
867 for my $header ( @headers ) {
868 $doc->cellValue( $row, $j, $header );
873 $row = $doc->getRow( $table, $i );
874 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
875 my $value = Encode
::encode
( 'UTF8', $rows->[$i - 1][$j] );
876 $doc->cellValue( $row, $j, $value );
882 open $ods_fh, '<', $ods_filepath;
883 $content .= $_ while <$ods_fh>;
884 unlink $ods_filepath;
887 print $input->header(
889 -attachment
=> $reportfilename
893 foreach my $err (@
$q_errors, @errors) {
894 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
895 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
901 'name' => 'Error exporting report!',
903 'errors' => $q_errors,
907 elsif ( $phase eq 'Create report from SQL' ) {
909 my ($group, $subgroup);
910 # allow the user to paste in sql
911 if ( $input->param('sql') ) {
912 $group = $input->param('report_group');
913 $subgroup = $input->param('report_subgroup');
915 'sql' => $input->param('sql') // '',
916 'reportname' => $input->param('reportname') // '',
917 'notes' => $input->param('notes') // '',
922 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
924 'cache_expiry' => 300,
925 'usecache' => $usecache,
929 elsif ($phase eq 'Create Compound Report'){
930 $template->param( 'savedreports' => get_saved_reports
(),
935 elsif ($phase eq 'Save Compound'){
936 my $master = $input->param('master');
937 my $subreport = $input->param('subreport');
938 my ($mastertables,$subtables) = create_compound
($master,$subreport);
939 $template->param( 'save_compound' => 1,
940 master
=>$mastertables,
945 # pass $sth, get back an array of names for the column headers
946 sub header_cell_values
{
947 my $sth = shift or return ();
948 return '' unless ($sth->{NAME
});
949 return @
{$sth->{NAME
}};
952 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
953 sub header_cell_loop
{
954 my @headers = map { +{ cell
=> decode
('UTF-8',$_) } } header_cell_values
(shift);
959 $template->{VARS
}->{'build' . $_} and last;
961 $template->param( 'referer' => $input->referer(),
964 output_html_with_http_headers
$input, $cookie, $template->output;
966 sub groups_with_subgroups
{
967 my ($group, $subgroup) = @_;
969 my $groups_with_subgroups = get_report_groups
();
971 my @sorted_keys = sort {
972 $groups_with_subgroups->{$a}->{name
} cmp $groups_with_subgroups->{$b}->{name
}
973 } keys %$groups_with_subgroups;
974 foreach my $g_id (@sorted_keys) {
975 my $v = $groups_with_subgroups->{$g_id};
977 if (my $sg = $v->{subgroups
}) {
978 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
981 name
=> $sg->{$sg_id},
982 selected
=> ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
989 selected
=> ($group && $g_id eq $group),
990 subgroups
=> \
@subgroups,
996 sub create_non_existing_group_and_subgroup
{
997 my ($input, $group, $subgroup) = @_;
999 if (defined $group and $group ne '') {
1000 my $report_groups = C4
::Reports
::Guided
::get_report_groups
;
1001 if (not exists $report_groups->{$group}) {
1002 my $groupdesc = $input->param('groupdesc') // $group;
1003 Koha
::AuthorisedValue
->new({
1004 category
=> 'REPORT_GROUP',
1005 authorised_value
=> $group,
1009 if (defined $subgroup and $subgroup ne '') {
1010 if (not exists $report_groups->{$group}->{subgroups
}->{$subgroup}) {
1011 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1012 Koha
::AuthorisedValue
->new({
1013 category
=> 'REPORT_SUBGROUP',
1014 authorised_value
=> $subgroup,
1015 lib
=> $subgroupdesc,