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' ) {
57 $flagsrequired = 'create_reports';
59 elsif ( $phase eq 'Use saved' ) {
60 $flagsrequired = 'execute_reports';
62 elsif ( $phase eq 'Delete Saved' ) {
63 $flagsrequired = 'delete_reports';
69 my ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
71 template_name
=> "reports/guided_reports_start.tt",
75 flagsrequired
=> { reports
=> $flagsrequired },
79 my $session = $cookie ? get_session
($cookie->value) : undef;
82 if ( $input->param("filter_set") or $input->param('clear_filters') ) {
84 $filter->{$_} = $input->param("filter_$_") foreach qw
/date author keyword group subgroup/;
85 $session->param('report_filter', $filter) if $session;
86 $template->param( 'filter_set' => 1 );
88 elsif ($session and not $input->param('clear_filters')) {
89 $filter = $session->param('report_filter');
95 $template->param( 'start' => 1 );
98 elsif ( $phase eq 'Build new' ) {
100 $template->param( 'build1' => 1 );
102 'areas' => get_report_areas
(),
103 'usecache' => $usecache,
104 'cache_expiry' => 300,
107 } elsif ( $phase eq 'Use saved' ) {
110 # get list of reports and display them
111 my $group = $input->param('group');
112 my $subgroup = $input->param('subgroup');
113 $filter->{group
} = $group;
114 $filter->{subgroup
} = $subgroup;
115 my $reports = get_saved_reports
($filter);
116 for my $report ( @
$reports ) {
117 $report->{results
} = C4
::Reports
::Guided
::get_results
( $report->{id
} );
121 'savedreports' => $reports,
122 'usecache' => $usecache,
123 'groups_with_subgroups'=> groups_with_subgroups
($group, $subgroup),
128 elsif ( $phase eq 'Delete Multiple') {
129 my @ids = $input->multi_param('ids');
130 delete_report
( @ids );
131 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
135 elsif ( $phase eq 'Delete Saved') {
137 # delete a report from the saved reports list
138 my $ids = $input->param('reports');
140 print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?phase=Use%20saved");
144 elsif ( $phase eq 'Show SQL'){
146 my $id = $input->param('reports');
147 my $report = get_saved_report
($id);
150 'reportname' => $report->{report_name
},
151 'notes' => $report->{notes
},
152 'sql' => $report->{savedsql
},
157 elsif ( $phase eq 'Edit SQL'){
158 my $id = $input->param('reports');
159 my $report = get_saved_report
($id);
160 my $group = $report->{report_group
};
161 my $subgroup = $report->{report_subgroup
};
163 'sql' => $report->{savedsql
},
164 'reportname' => $report->{report_name
},
165 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
166 'notes' => $report->{notes
},
168 'cache_expiry' => $report->{cache_expiry
},
169 'public' => $report->{public
},
170 'usecache' => $usecache,
175 elsif ( $phase eq 'Update SQL'){
176 my $id = $input->param('id');
177 my $sql = $input->param('sql');
178 my $reportname = $input->param('reportname');
179 my $group = $input->param('group');
180 my $subgroup = $input->param('subgroup');
181 my $notes = $input->param('notes');
182 my $cache_expiry = $input->param('cache_expiry');
183 my $cache_expiry_units = $input->param('cache_expiry_units');
184 my $public = $input->param('public');
185 my $save_anyway = $input->param('save_anyway');
189 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
190 if( $cache_expiry_units ){
191 if( $cache_expiry_units eq "minutes" ){
193 } elsif( $cache_expiry_units eq "hours" ){
194 $cache_expiry *= 3600; # 60 * 60
195 } elsif( $cache_expiry_units eq "days" ){
196 $cache_expiry *= 86400; # 60 * 60 * 24
199 # 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
200 if( $cache_expiry >= 2592000 ){
201 push @errors, {cache_expiry
=> $cache_expiry};
204 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
206 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
207 push @errors, {sqlerr
=> $1};
209 elsif ($sql !~ /^(SELECT)/i) {
210 push @errors, {queryerr
=> "No SELECT"};
215 'errors' => \
@errors,
220 # Check defined SQL parameters for authorised value validity
221 my $problematic_authvals = ValidateSQLParameters
($sql);
223 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
224 # There's at least one problematic parameter, report to the
225 # GUI and provide all user input for further actions
229 'reportname' => $reportname,
231 'subgroup' => $subgroup,
234 'problematic_authvals' => $problematic_authvals,
235 'warn_authval_problem' => 1,
240 # No params problem found or asked to save anyway
245 subgroup
=> $subgroup,
248 cache_expiry
=> $cache_expiry,
251 'save_successful' => 1,
252 'reportname' => $reportname,
255 logaction
( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4
::Context
->preference("ReportsLog");
259 cache_expiry
=> $cache_expiry,
260 cache_expiry_units
=> $cache_expiry_units,
266 elsif ($phase eq 'retrieve results') {
267 my $id = $input->param('id');
268 my $result = format_results
( $id );
270 report_name
=> $result->{report_name
},
271 notes
=> $result->{notes
},
272 saved_results
=> $result->{results
},
273 date_run
=> $result->{date_run
},
277 elsif ( $phase eq 'Report on this Area' ) {
278 my $cache_expiry_units = $input->param('cache_expiry_units'),
279 my $cache_expiry = $input->param('cache_expiry');
281 # we need to handle converting units
282 if( $cache_expiry_units eq "minutes" ){
284 } elsif( $cache_expiry_units eq "hours" ){
285 $cache_expiry *= 3600; # 60 * 60
286 } elsif( $cache_expiry_units eq "days" ){
287 $cache_expiry *= 86400; # 60 * 60 * 24
289 # 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
290 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
291 # report error to user
295 'areas' => get_report_areas
(),
296 'cache_expiry' => $cache_expiry,
297 'usecache' => $usecache,
298 'public' => scalar $input->param('public'),
301 # they have choosen a new report and the area to report on
304 'area' => scalar $input->param('area'),
305 'types' => get_report_types
(),
306 'cache_expiry' => $cache_expiry,
307 'public' => scalar $input->param('public'),
312 elsif ( $phase eq 'Choose this type' ) {
313 # they have chosen type and area
314 # get area and type and pass them to the template
315 my $area = $input->param('area');
316 my $type = $input->param('types');
321 columns
=> get_columns
($area,$input),
322 'cache_expiry' => scalar $input->param('cache_expiry'),
323 'public' => scalar $input->param('public'),
327 elsif ( $phase eq 'Choose these columns' ) {
328 # we now know type, area, and columns
329 # next step is the constraints
330 my $area = $input->param('area');
331 my $type = $input->param('type');
332 my @columns = $input->multi_param('columns');
333 my $column = join( ',', @columns );
340 definitions
=> get_from_dictionary
($area),
341 criteria
=> get_criteria
($area,$input),
342 'public' => scalar $input->param('public'),
346 cache_expiry
=> scalar $input->param('cache_expiry'),
347 cache_expiry_units
=> scalar $input->param('cache_expiry_units'),
353 elsif ( $phase eq 'Choose these criteria' ) {
354 my $area = $input->param('area');
355 my $type = $input->param('type');
356 my $column = $input->param('column');
357 my @definitions = $input->multi_param('definition');
358 my $definition = join (',',@definitions);
359 my @criteria = $input->multi_param('criteria_column');
361 foreach my $crit (@criteria) {
362 my $value = $input->param( $crit . "_value" );
364 # If value is not defined, then it may be range values
365 if (!defined $value) {
367 my $fromvalue = $input->param( "from_" . $crit . "_value" );
368 my $tovalue = $input->param( "to_" . $crit . "_value" );
370 # If the range values are dates
372 $fromvalue_dt = eval { dt_from_string
( $fromvalue ); } if ( $fromvalue );
374 $tovalue_dt = eval { dt_from_string
( $tovalue ); } if ($tovalue);
375 if ( $fromvalue_dt && $tovalue_dt ) {
376 $fromvalue = output_pref
( { dt
=> dt_from_string
( $fromvalue_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
377 $tovalue = output_pref
( { dt
=> dt_from_string
( $tovalue_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
380 if ($fromvalue && $tovalue) {
381 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
388 $value_dt = eval { dt_from_string
( $value ); } if ( $value );
390 $value = output_pref
( { dt
=> dt_from_string
( $value_dt ), dateonly
=> 1, dateformat
=> 'iso' } );
392 # don't escape runtime parameters, they'll be at runtime
393 if ($value =~ /<<.*>>/) {
394 $query_criteria .= " AND $crit=$value";
396 $query_criteria .= " AND $crit='$value'";
405 'definition' => $definition,
406 'criteriastring' => $query_criteria,
407 'public' => scalar $input->param('public'),
411 cache_expiry
=> scalar $input->param('cache_expiry'),
412 cache_expiry_units
=> scalar $input->param('cache_expiry_units'),
417 my @columns = split( ',', $column );
420 # build structue for use by tmpl_loop to choose columns to order by
421 # need to do something about the order of the order :)
422 # we also want to use the %columns hash to get the plain english names
423 foreach my $col (@columns) {
424 my %total = (name
=> $col);
425 my @selects = map {+{ value
=> $_ }} (qw(sum min max avg count));
426 $total{'select'} = \
@selects;
427 push @total_by, \
%total;
430 $template->param( 'total_by' => \
@total_by );
433 elsif ( $phase eq 'Choose these operations' ) {
434 my $area = $input->param('area');
435 my $type = $input->param('type');
436 my $column = $input->param('column');
437 my $criteria = $input->param('criteria');
438 my $definition = $input->param('definition');
439 my @total_by = $input->multi_param('total_by');
441 foreach my $total (@total_by) {
442 my $value = $input->param( $total . "_tvalue" );
443 $totals .= "$value($total),";
451 'criteriastring' => $criteria,
453 'definition' => $definition,
454 'cache_expiry' => scalar $input->param('cache_expiry'),
455 'public' => scalar $input->param('public'),
459 my @columns = split( ',', $column );
462 # build structue for use by tmpl_loop to choose columns to order by
463 # need to do something about the order of the order :)
464 foreach my $col (@columns) {
465 my %order = (name
=> $col);
466 my @selects = map {+{ value
=> $_ }} (qw(asc desc));
467 $order{'select'} = \
@selects;
468 push @order_by, \
%order;
471 $template->param( 'order_by' => \
@order_by );
474 elsif ( $phase eq 'Build report' ) {
476 # now we have all the info we need and can build the sql
477 my $area = $input->param('area');
478 my $type = $input->param('type');
479 my $column = $input->param('column');
480 my $crit = $input->param('criteria');
481 my $totals = $input->param('totals');
482 my $definition = $input->param('definition');
483 my $query_criteria=$crit;
484 # split the columns up by ,
485 my @columns = split( ',', $column );
486 my @order_by = $input->multi_param('order_by');
489 foreach my $order (@order_by) {
490 my $value = $input->param( $order . "_ovalue" );
491 if ($query_orderby) {
492 $query_orderby .= ",$order $value";
495 $query_orderby = " ORDER BY $order $value";
501 build_query
( \
@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
507 'cache_expiry' => scalar $input->param('cache_expiry'),
508 'public' => scalar $input->param('public'),
512 elsif ( $phase eq 'Save' ) {
513 # Save the report that has just been built
514 my $area = $input->param('area');
515 my $sql = $input->param('sql');
516 my $type = $input->param('type');
522 'cache_expiry' => scalar $input->param('cache_expiry'),
523 'public' => scalar $input->param('public'),
524 'groups_with_subgroups' => groups_with_subgroups
($area), # in case we have a report group that matches area
528 elsif ( $phase eq 'Save Report' ) {
529 # save the sql pasted in by a user
530 my $area = $input->param('area');
531 my $group = $input->param('group');
532 my $subgroup = $input->param('subgroup');
533 my $sql = $input->param('sql');
534 my $name = $input->param('reportname');
535 my $type = $input->param('types');
536 my $notes = $input->param('notes');
537 my $cache_expiry = $input->param('cache_expiry');
538 my $cache_expiry_units = $input->param('cache_expiry_units');
539 my $public = $input->param('public');
540 my $save_anyway = $input->param('save_anyway');
543 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
544 if( $cache_expiry_units ){
545 if( $cache_expiry_units eq "minutes" ){
547 } elsif( $cache_expiry_units eq "hours" ){
548 $cache_expiry *= 3600; # 60 * 60
549 } elsif( $cache_expiry_units eq "days" ){
550 $cache_expiry *= 86400; # 60 * 60 * 24
553 # 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
554 if( $cache_expiry && $cache_expiry >= 2592000 ){
555 push @errors, {cache_expiry
=> $cache_expiry};
558 create_non_existing_group_and_subgroup
($input, $group, $subgroup);
560 ## FIXME this is AFTER entering a name to save the report under
561 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
562 push @errors, {sqlerr
=> $1};
564 elsif ($sql !~ /^(SELECT)/i) {
565 push @errors, {queryerr
=> "No SELECT"};
570 'errors' => \
@errors,
572 'reportname'=> $name,
575 'cache_expiry' => $cache_expiry,
579 # Check defined SQL parameters for authorised value validity
580 my $problematic_authvals = ValidateSQLParameters
($sql);
582 if ( scalar @
$problematic_authvals > 0 && not $save_anyway ) {
583 # There's at least one problematic parameter, report to the
584 # GUI and provide all user input for further actions
588 'subgroup' => $subgroup,
590 'reportname' => $name,
594 'problematic_authvals' => $problematic_authvals,
595 'warn_authval_problem' => 1,
600 cache_expiry
=> $cache_expiry,
601 cache_expiry_units
=> $cache_expiry_units,
605 # No params problem found or asked to save anyway
606 my $id = save_report
( {
607 borrowernumber
=> $borrowernumber,
612 subgroup
=> $subgroup,
615 cache_expiry
=> $cache_expiry,
618 logaction
( "REPORTS", "ADD", $id, "$name | $sql" ) if C4
::Context
->preference("ReportsLog");
620 'save_successful' => 1,
621 'reportname' => $name,
628 elsif ($phase eq 'Run this report'){
629 # execute a saved report
630 my $limit = $input->param('limit') || 20;
632 my $report_id = $input->param('reports');
633 my @sql_params = $input->multi_param('sql_params');
635 if ($input->param('page')) {
636 $offset = ($input->param('page') - 1) * $limit;
641 'report_id' => $report_id,
644 my ( $sql, $original_sql, $type, $name, $notes );
645 if (my $report = get_saved_report
($report_id)) {
646 $sql = $original_sql = $report->{savedsql
};
647 $name = $report->{report_name
};
648 $notes = $report->{notes
};
651 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
652 if ($sql =~ /<</ && !@sql_params) {
653 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
654 my @split = split /<<|>>/,$sql;
657 for(my $i=0;$i<($#split/2);$i++) {
658 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
661 if ( not defined $authorised_value ) {
662 # no authorised value input, provide a text box
664 } elsif ( $authorised_value eq "date" ) {
665 # require a date, provide a date picker
668 # defined $authorised_value, and not 'date'
669 my $dbh=C4
::Context
->dbh;
670 my @authorised_values;
672 # builds list, depending on authorised value...
673 if ( $authorised_value eq "branches" ) {
674 my $libraries = Koha
::Libraries
->search( {}, { order_by
=> ['branchname'] } );
675 while ( my $library = $libraries->next ) {
676 push @authorised_values, $library->branchcode;
677 $authorised_lib{$library->branchcode} = $library->branchname;
680 elsif ( $authorised_value eq "itemtypes" ) {
681 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
683 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
684 push @authorised_values, $itemtype;
685 $authorised_lib{$itemtype} = $description;
688 elsif ( $authorised_value eq "biblio_framework" ) {
689 my $frameworks = GetFrameworksLoop
();
690 my $default_source = '';
691 push @authorised_values,$default_source;
692 $authorised_lib{$default_source} = 'Default';
693 foreach my $framework (@
$frameworks) {
694 push @authorised_values, $framework->{value
};
695 $authorised_lib{$framework->{value
}} = $framework->{description
};
698 elsif ( $authorised_value eq "cn_source" ) {
699 my $class_sources = GetClassSources
();
700 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
701 foreach my $class_source (sort keys %$class_sources) {
702 next unless $class_sources->{$class_source}->{'used'} or
703 ($class_source eq $default_source);
704 push @authorised_values, $class_source;
705 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
708 elsif ( $authorised_value eq "categorycode" ) {
709 my @patron_categories = Koha
::Patron
::Categories
->search({}, { order_by
=> ['description']});
710 %authorised_lib = map { $_->categorycode => $_->description } @patron_categories;
711 push @authorised_values, $_->categorycode for @patron_categories;
714 if ( Koha
::AuthorisedValues
->search({ category
=> $authorised_value })->count ) {
716 SELECT authorised_value,lib
717 FROM authorised_values
721 my $authorised_values_sth = $dbh->prepare($query);
722 $authorised_values_sth->execute( $authorised_value);
724 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
725 push @authorised_values, $value;
726 $authorised_lib{$value} = $lib;
727 # For item location, we show the code and the libelle
728 $authorised_lib{$value} = $lib;
731 # not exists $authorised_value_categories{$authorised_value})
732 push @authval_errors, {'entry' => $text,
733 'auth_val' => $authorised_value };
734 # tell the template there's an error
735 $template->param( auth_val_error
=> 1 );
736 # skip scrolling list creation and params push
743 name
=> "sql_params",
744 id
=> "sql_params_".$labelid,
745 values => \
@authorised_values,
746 labels
=> \
%authorised_lib,
750 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
752 $template->param('sql' => $sql,
754 'sql_params' => \
@tmpl_parameters,
755 'auth_val_errors' => \
@authval_errors,
757 'reports' => $report_id,
760 # OK, we have parameters, or there are none, we run the report
761 # if there were parameters, replace before running
762 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
763 my @split = split /<<|>>/,$sql;
765 for(my $i=0;$i<$#split/2;$i++) {
766 my $quoted = $sql_params[$i];
767 # if there are special regexp chars, we must \ them
768 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
769 if ($split[$i*2+1] =~ /\|\s*date\s*$/) {
770 $quoted = output_pref
({ dt
=> dt_from_string
($quoted), dateformat
=> 'iso', dateonly
=> 1 }) if $quoted;
772 $quoted = C4
::Context
->dbh->quote($quoted);
773 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
775 my ($sth, $errors) = execute_query
($sql, $offset, $limit);
776 my $total = nb_rows
($sql) || 0;
778 die "execute_query failed to return sth for report $report_id: $sql";
780 my $headers = header_cell_loop
($sth);
781 $template->param(header_row
=> $headers);
782 while (my $row = $sth->fetchrow_arrayref()) {
783 my @cells = map { +{ cell
=> $_ } } @
$row;
784 push @rows, { cells
=> \
@cells };
788 my $totpages = int($total/$limit) + (($total % $limit) > 0 ?
1 : 0);
789 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
791 $url = join('&sql_params=', $url, map { URI
::Escape
::uri_escape_utf8
($_) } @sql_params);
796 original_sql
=> $original_sql,
801 'errors' => defined($errors) ?
[ $errors ] : undef,
802 'pagination_bar' => pagination_bar
($url, $totpages, $input->param('page')),
803 'unlimited_total' => $total,
804 'sql_params' => \
@sql_params,
809 push @errors, { no_sql_for_id
=> $report_id };
813 elsif ($phase eq 'Export'){
815 # export results to tab separated text or CSV
816 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
817 my $format = $input->param('format');
818 my $reportname = $input->param('reportname');
819 my $reportfilename = $reportname ?
"$reportname-reportresults.$format" : "reportresults.$format" ;
820 my ($sth, $q_errors) = execute_query
($sql);
821 unless ($q_errors and @
$q_errors) {
822 my ( $type, $content );
823 if ($format eq 'tab') {
824 $type = 'application/octet-stream';
825 $content .= join("\t", header_cell_values
($sth)) . "\n";
826 $content = Encode
::decode
('UTF-8', $content);
827 while (my $row = $sth->fetchrow_arrayref()) {
828 $content .= join("\t", @
$row) . "\n";
831 my $delimiter = C4
::Context
->preference('delimiter') || ',';
832 if ( $format eq 'csv' ) {
833 $type = 'application/csv';
834 my $csv = Text
::CSV
::Encoded
->new({ encoding_out
=> 'UTF-8', sep_char
=> $delimiter});
835 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text
::CSV
::Encoded
->error_diag();
836 if ($csv->combine(header_cell_values
($sth))) {
837 $content .= Encode
::decode
('UTF-8', $csv->string()) . "\n";
839 push @
$q_errors, { combine
=> 'HEADER ROW: ' . $csv->error_diag() } ;
841 while (my $row = $sth->fetchrow_arrayref()) {
842 if ($csv->combine(@
$row)) {
843 $content .= $csv->string() . "\n";
845 push @
$q_errors, { combine
=> $csv->error_diag() } ;
849 elsif ( $format eq 'ods' ) {
850 $type = 'application/vnd.oasis.opendocument.spreadsheet';
851 my $ods_fh = File
::Temp
->new( UNLINK
=> 0 );
852 my $ods_filepath = $ods_fh->filename;
854 use OpenOffice
::OODoc
;
855 my $tmpdir = dirname
$ods_filepath;
856 odfWorkingDirectory
( $tmpdir );
857 my $container = odfContainer
( $ods_filepath, create
=> 'spreadsheet' );
858 my $doc = odfDocument
(
859 container
=> $container,
862 my $table = $doc->getTable(0);
863 my @headers = header_cell_values
( $sth );
864 my $rows = $sth->fetchall_arrayref();
865 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
868 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
870 my $row = $doc->getRow( $table, 0 );
872 for my $header ( @headers ) {
873 $doc->cellValue( $row, $j, $header );
878 $row = $doc->getRow( $table, $i );
879 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
880 my $value = Encode
::encode
( 'UTF8', $rows->[$i - 1][$j] );
881 $doc->cellValue( $row, $j, $value );
887 open $ods_fh, '<', $ods_filepath;
888 $content .= $_ while <$ods_fh>;
889 unlink $ods_filepath;
892 print $input->header(
894 -attachment
=> $reportfilename
898 foreach my $err (@
$q_errors, @errors) {
899 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
900 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
906 'name' => 'Error exporting report!',
908 'errors' => $q_errors,
912 elsif ( $phase eq 'Create report from SQL' ) {
914 my ($group, $subgroup);
915 # allow the user to paste in sql
916 if ( $input->param('sql') ) {
917 $group = $input->param('report_group');
918 $subgroup = $input->param('report_subgroup');
920 'sql' => scalar $input->param('sql') // '',
921 'reportname' => scalar $input->param('reportname') // '',
922 'notes' => scalar $input->param('notes') // '',
927 'groups_with_subgroups' => groups_with_subgroups
($group, $subgroup),
929 'cache_expiry' => 300,
930 'usecache' => $usecache,
934 elsif ($phase eq 'Create Compound Report'){
935 $template->param( 'savedreports' => get_saved_reports
(),
940 elsif ($phase eq 'Save Compound'){
941 my $master = $input->param('master');
942 my $subreport = $input->param('subreport');
943 my ($mastertables,$subtables) = create_compound
($master,$subreport);
944 $template->param( 'save_compound' => 1,
945 master
=>$mastertables,
950 # pass $sth, get back an array of names for the column headers
951 sub header_cell_values
{
952 my $sth = shift or return ();
953 return '' unless ($sth->{NAME
});
954 return @
{$sth->{NAME
}};
957 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
958 sub header_cell_loop
{
959 my @headers = map { +{ cell
=> decode
('UTF-8',$_) } } header_cell_values
(shift);
964 $template->{VARS
}->{'build' . $_} and last;
966 $template->param( 'referer' => $input->referer(),
969 output_html_with_http_headers
$input, $cookie, $template->output;
971 sub groups_with_subgroups
{
972 my ($group, $subgroup) = @_;
974 my $groups_with_subgroups = get_report_groups
();
976 my @sorted_keys = sort {
977 $groups_with_subgroups->{$a}->{name
} cmp $groups_with_subgroups->{$b}->{name
}
978 } keys %$groups_with_subgroups;
979 foreach my $g_id (@sorted_keys) {
980 my $v = $groups_with_subgroups->{$g_id};
982 if (my $sg = $v->{subgroups
}) {
983 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
986 name
=> $sg->{$sg_id},
987 selected
=> ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
994 selected
=> ($group && $g_id eq $group),
995 subgroups
=> \
@subgroups,
1001 sub create_non_existing_group_and_subgroup
{
1002 my ($input, $group, $subgroup) = @_;
1004 if (defined $group and $group ne '') {
1005 my $report_groups = C4
::Reports
::Guided
::get_report_groups
;
1006 if (not exists $report_groups->{$group}) {
1007 my $groupdesc = $input->param('groupdesc') // $group;
1008 Koha
::AuthorisedValue
->new({
1009 category
=> 'REPORT_GROUP',
1010 authorised_value
=> $group,
1014 if (defined $subgroup and $subgroup ne '') {
1015 if (not exists $report_groups->{$group}->{subgroups
}->{$subgroup}) {
1016 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
1017 Koha
::AuthorisedValue
->new({
1018 category
=> 'REPORT_SUBGROUP',
1019 authorised_value
=> $subgroup,
1020 lib
=> $subgroupdesc,