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/;
30 use C4::Dates qw/format_date/;
32 use C4::Branch; # XXX subfield_is_koha_internal_p
33 use C4::Koha qw/IsAuthorisedValueCategory GetFrameworksLoop/;
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 );
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,
238 'save_successful' => 1,
239 'reportname' => $reportname,
242 logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog");
246 cache_expiry => $cache_expiry,
247 cache_expiry_units => $cache_expiry_units,
253 elsif ($phase eq 'retrieve results') {
254 my $id = $input->param('id');
255 my ($results,$name,$notes) = format_results($id);
259 'results' => $results,
265 elsif ( $phase eq 'Report on this Area' ) {
266 my $cache_expiry_units = $input->param('cache_expiry_units'),
267 my $cache_expiry = $input->param('cache_expiry');
269 # we need to handle converting units
270 if( $cache_expiry_units eq "minutes" ){
272 } elsif( $cache_expiry_units eq "hours" ){
273 $cache_expiry *= 3600; # 60 * 60
274 } elsif( $cache_expiry_units eq "days" ){
275 $cache_expiry *= 86400; # 60 * 60 * 24
277 # 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
278 if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days
279 # report error to user
283 'areas' => get_report_areas(),
284 'cache_expiry' => $cache_expiry,
285 'usecache' => $usecache,
286 'public' => $input->param('public'),
289 # they have choosen a new report and the area to report on
292 'area' => $input->param('area'),
293 'types' => get_report_types(),
294 'cache_expiry' => $cache_expiry,
295 'public' => $input->param('public'),
300 elsif ( $phase eq 'Choose this type' ) {
301 # they have chosen type and area
302 # get area and type and pass them to the template
303 my $area = $input->param('area');
304 my $type = $input->param('types');
309 columns => get_columns($area,$input),
310 'cache_expiry' => $input->param('cache_expiry'),
311 'public' => $input->param('public'),
315 elsif ( $phase eq 'Choose these columns' ) {
316 # we now know type, area, and columns
317 # next step is the constraints
318 my $area = $input->param('area');
319 my $type = $input->param('type');
320 my @columns = $input->param('columns');
321 my $column = join( ',', @columns );
328 definitions => get_from_dictionary($area),
329 criteria => get_criteria($area,$input),
330 'public' => $input->param('public'),
334 cache_expiry => $input->param('cache_expiry'),
335 cache_expiry_units => $input->param('cache_expiry_units'),
341 elsif ( $phase eq 'Choose these criteria' ) {
342 my $area = $input->param('area');
343 my $type = $input->param('type');
344 my $column = $input->param('column');
345 my @definitions = $input->param('definition');
346 my $definition = join (',',@definitions);
347 my @criteria = $input->param('criteria_column');
349 foreach my $crit (@criteria) {
350 my $value = $input->param( $crit . "_value" );
352 # If value is not defined, then it may be range values
353 if (!defined $value) {
355 my $fromvalue = $input->param( "from_" . $crit . "_value" );
356 my $tovalue = $input->param( "to_" . $crit . "_value" );
358 # If the range values are dates
359 if ($fromvalue =~ C4::Dates->regexp('syspref') && $tovalue =~ C4::Dates->regexp('syspref')) {
360 $fromvalue = C4::Dates->new($fromvalue)->output("iso");
361 $tovalue = C4::Dates->new($tovalue)->output("iso");
364 if ($fromvalue && $tovalue) {
365 $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'";
371 if ($value =~ C4::Dates->regexp('syspref')) {
372 $value = C4::Dates->new($value)->output("iso");
374 # don't escape runtime parameters, they'll be at runtime
375 if ($value =~ /<<.*>>/) {
376 $query_criteria .= " AND $crit=$value";
378 $query_criteria .= " AND $crit='$value'";
387 'definition' => $definition,
388 'criteriastring' => $query_criteria,
389 'public' => $input->param('public'),
393 cache_expiry => $input->param('cache_expiry'),
394 cache_expiry_units => $input->param('cache_expiry_units'),
399 my @columns = split( ',', $column );
402 # build structue for use by tmpl_loop to choose columns to order by
403 # need to do something about the order of the order :)
404 # we also want to use the %columns hash to get the plain english names
405 foreach my $col (@columns) {
406 my %total = (name => $col);
407 my @selects = map {+{ value => $_ }} (qw(sum min max avg count));
408 $total{'select'} = \@selects;
409 push @total_by, \%total;
412 $template->param( 'total_by' => \@total_by );
415 elsif ( $phase eq 'Choose these operations' ) {
416 my $area = $input->param('area');
417 my $type = $input->param('type');
418 my $column = $input->param('column');
419 my $criteria = $input->param('criteria');
420 my $definition = $input->param('definition');
421 my @total_by = $input->param('total_by');
423 foreach my $total (@total_by) {
424 my $value = $input->param( $total . "_tvalue" );
425 $totals .= "$value($total),";
433 'criteriastring' => $criteria,
435 'definition' => $definition,
436 'cache_expiry' => $input->param('cache_expiry'),
437 'public' => $input->param('public'),
441 my @columns = split( ',', $column );
444 # build structue for use by tmpl_loop to choose columns to order by
445 # need to do something about the order of the order :)
446 foreach my $col (@columns) {
447 my %order = (name => $col);
448 my @selects = map {+{ value => $_ }} (qw(asc desc));
449 $order{'select'} = \@selects;
450 push @order_by, \%order;
453 $template->param( 'order_by' => \@order_by );
456 elsif ( $phase eq 'Build report' ) {
458 # now we have all the info we need and can build the sql
459 my $area = $input->param('area');
460 my $type = $input->param('type');
461 my $column = $input->param('column');
462 my $crit = $input->param('criteria');
463 my $totals = $input->param('totals');
464 my $definition = $input->param('definition');
465 my $query_criteria=$crit;
466 # split the columns up by ,
467 my @columns = split( ',', $column );
468 my @order_by = $input->param('order_by');
471 foreach my $order (@order_by) {
472 my $value = $input->param( $order . "_ovalue" );
473 if ($query_orderby) {
474 $query_orderby .= ",$order $value";
477 $query_orderby = " ORDER BY $order $value";
483 build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition );
489 'cache_expiry' => $input->param('cache_expiry'),
490 'public' => $input->param('public'),
494 elsif ( $phase eq 'Save' ) {
495 # Save the report that has just been built
496 my $area = $input->param('area');
497 my $sql = $input->param('sql');
498 my $type = $input->param('type');
504 'cache_expiry' => $input->param('cache_expiry'),
505 'public' => $input->param('public'),
506 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area
510 elsif ( $phase eq 'Save Report' ) {
511 # save the sql pasted in by a user
512 my $area = $input->param('area');
513 my $group = $input->param('group');
514 my $subgroup = $input->param('subgroup');
515 my $sql = $input->param('sql');
516 my $name = $input->param('reportname');
517 my $type = $input->param('types');
518 my $notes = $input->param('notes');
519 my $cache_expiry = $input->param('cache_expiry');
520 my $cache_expiry_units = $input->param('cache_expiry_units');
521 my $public = $input->param('public');
522 my $save_anyway = $input->param('save_anyway');
525 # if we have the units, then we came from creating a report from SQL and thus need to handle converting units
526 if( $cache_expiry_units ){
527 if( $cache_expiry_units eq "minutes" ){
529 } elsif( $cache_expiry_units eq "hours" ){
530 $cache_expiry *= 3600; # 60 * 60
531 } elsif( $cache_expiry_units eq "days" ){
532 $cache_expiry *= 86400; # 60 * 60 * 24
535 # 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
536 if( $cache_expiry && $cache_expiry >= 2592000 ){
537 push @errors, {cache_expiry => $cache_expiry};
540 create_non_existing_group_and_subgroup($input, $group, $subgroup);
542 ## FIXME this is AFTER entering a name to save the report under
543 if ($sql =~ /;?\W?(UPDATE|DELETE|DROP|INSERT|SHOW|CREATE)\W/i) {
544 push @errors, {sqlerr => $1};
546 elsif ($sql !~ /^(SELECT)/i) {
547 push @errors, {queryerr => "No SELECT"};
552 'errors' => \@errors,
554 'reportname'=> $name,
557 'cache_expiry' => $cache_expiry,
561 # Check defined SQL parameters for authorised value validity
562 my $problematic_authvals = ValidateSQLParameters($sql);
564 if ( scalar @$problematic_authvals > 0 && not $save_anyway ) {
565 # There's at least one problematic parameter, report to the
566 # GUI and provide all user input for further actions
570 'subgroup' => $subgroup,
572 'reportname' => $name,
576 'problematic_authvals' => $problematic_authvals,
577 'warn_authval_problem' => 1,
582 cache_expiry => $cache_expiry,
583 cache_expiry_units => $cache_expiry_units,
587 # No params problem found or asked to save anyway
588 my $id = save_report( {
589 borrowernumber => $borrowernumber,
594 subgroup => $subgroup,
597 cache_expiry => $cache_expiry,
600 logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog");
602 'save_successful' => 1,
603 'reportname' => $name,
610 elsif ($phase eq 'Run this report'){
611 # execute a saved report
612 my $limit = $input->param('limit') || 20;
614 my $report_id = $input->param('reports');
615 my @sql_params = $input->param('sql_params');
617 if ($input->param('page')) {
618 $offset = ($input->param('page') - 1) * $limit;
623 'report_id' => $report_id,
626 my ( $sql, $type, $name, $notes );
627 if (my $report = get_saved_report($report_id)) {
628 $sql = $report->{savedsql};
629 $name = $report->{report_name};
630 $notes = $report->{notes};
633 # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters
634 if ($sql =~ /<</ && !@sql_params) {
635 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
636 my @split = split /<<|>>/,$sql;
639 for(my $i=0;$i<($#split/2);$i++) {
640 my ($text,$authorised_value) = split /\|/,$split[$i*2+1];
643 if ( not defined $authorised_value ) {
644 # no authorised value input, provide a text box
646 } elsif ( $authorised_value eq "date" ) {
647 # require a date, provide a date picker
650 # defined $authorised_value, and not 'date'
651 my $dbh=C4::Context->dbh;
652 my @authorised_values;
654 # builds list, depending on authorised value...
655 if ( $authorised_value eq "branches" ) {
656 my $branches = GetBranchesLoop();
657 foreach my $thisbranch (@$branches) {
658 push @authorised_values, $thisbranch->{value};
659 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
662 elsif ( $authorised_value eq "itemtypes" ) {
663 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
665 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
666 push @authorised_values, $itemtype;
667 $authorised_lib{$itemtype} = $description;
670 elsif ( $authorised_value eq "biblio_framework" ) {
671 my $frameworks = GetFrameworksLoop();
672 my $default_source = '';
673 push @authorised_values,$default_source;
674 $authorised_lib{$default_source} = 'Default';
675 foreach my $framework (@$frameworks) {
676 push @authorised_values, $framework->{value};
677 $authorised_lib{$framework->{value}} = $framework->{description};
680 elsif ( $authorised_value eq "cn_source" ) {
681 my $class_sources = GetClassSources();
682 my $default_source = C4::Context->preference("DefaultClassificationSource");
683 foreach my $class_source (sort keys %$class_sources) {
684 next unless $class_sources->{$class_source}->{'used'} or
685 ($class_source eq $default_source);
686 push @authorised_values, $class_source;
687 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
690 elsif ( $authorised_value eq "categorycode" ) {
691 my $sth = $dbh->prepare("SELECT categorycode, description FROM categories ORDER BY description");
693 while ( my ( $categorycode, $description ) = $sth->fetchrow_array ) {
694 push @authorised_values, $categorycode;
695 $authorised_lib{$categorycode} = $description;
698 #---- "true" authorised value
701 if ( IsAuthorisedValueCategory($authorised_value) ) {
703 SELECT authorised_value,lib
704 FROM authorised_values
708 my $authorised_values_sth = $dbh->prepare($query);
709 $authorised_values_sth->execute( $authorised_value);
711 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
712 push @authorised_values, $value;
713 $authorised_lib{$value} = $lib;
714 # For item location, we show the code and the libelle
715 $authorised_lib{$value} = $lib;
718 # not exists $authorised_value_categories{$authorised_value})
719 push @authval_errors, {'entry' => $text,
720 'auth_val' => $authorised_value };
721 # tell the template there's an error
722 $template->param( auth_val_error => 1 );
723 # skip scrolling list creation and params push
730 name => "sql_params",
731 id => "sql_params_".$labelid,
732 values => \@authorised_values,
733 labels => \%authorised_lib,
737 push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid };
739 $template->param('sql' => $sql,
741 'sql_params' => \@tmpl_parameters,
742 'auth_val_errors' => \@authval_errors,
744 'reports' => $report_id,
747 # OK, we have parameters, or there are none, we run the report
748 # if there were parameters, replace before running
749 # split on ??. Each odd (2,4,6,...) entry should be a parameter to fill
750 my @split = split /<<|>>/,$sql;
752 for(my $i=0;$i<$#split/2;$i++) {
753 my $quoted = C4::Context->dbh->quote($sql_params[$i]);
754 # if there are special regexp chars, we must \ them
755 $split[$i*2+1] =~ s/(\||\?|\.|\*|\(|\)|\%)/\\$1/g;
756 $sql =~ s/<<$split[$i*2+1]>>/$quoted/;
758 my ($sth, $errors) = execute_query($sql, $offset, $limit);
759 my $total = nb_rows($sql) || 0;
761 die "execute_query failed to return sth for report $report_id: $sql";
763 my $headers= header_cell_loop($sth);
764 $template->param(header_row => $headers);
765 while (my $row = $sth->fetchrow_arrayref()) {
766 my @cells = map { +{ cell => $_ } } @$row;
767 push @rows, { cells => \@cells };
771 my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0);
772 my $url = "/cgi-bin/koha/reports/guided_reports.pl?reports=$report_id&phase=Run%20this%20report&limit=$limit";
774 $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params);
783 'errors' => defined($errors) ? [ $errors ] : undef,
784 'pagination_bar' => pagination_bar($url, $totpages, $input->param('page')),
785 'unlimited_total' => $total,
786 'sql_params' => \@sql_params,
791 push @errors, { no_sql_for_id => $report_id };
795 elsif ($phase eq 'Export'){
797 # export results to tab separated text or CSV
798 my $sql = $input->param('sql'); # FIXME: use sql from saved report ID#, not new user-supplied SQL!
799 my $format = $input->param('format');
800 my $reportname = $input->param('reportname');
801 my $reportfilename = $reportname ? "$reportname-reportresults.$format" : "reportresults.$format" ;
802 my ($sth, $q_errors) = execute_query($sql);
803 unless ($q_errors and @$q_errors) {
804 my ( $type, $content );
805 if ($format eq 'tab') {
806 $type = 'application/octet-stream';
807 $content .= join("\t", header_cell_values($sth)) . "\n";
808 while (my $row = $sth->fetchrow_arrayref()) {
809 $content .= join("\t", @$row) . "\n";
812 my $delimiter = C4::Context->preference('delimiter') || ',';
813 if ( $format eq 'csv' ) {
814 $type = 'application/csv';
815 my $csv = Text::CSV::Encoded->new({ encoding_out => 'utf8', sep_char => $delimiter});
816 $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag();
817 if ($csv->combine(header_cell_values($sth))) {
818 $content .= $csv->string(). "\n";
820 push @$q_errors, { combine => 'HEADER ROW: ' . $csv->error_diag() } ;
822 while (my $row = $sth->fetchrow_arrayref()) {
823 if ($csv->combine(@$row)) {
824 $content .= $csv->string() . "\n";
826 push @$q_errors, { combine => $csv->error_diag() } ;
830 elsif ( $format eq 'ods' ) {
831 $type = 'application/vnd.oasis.opendocument.spreadsheet';
832 my $ods_fh = File::Temp->new( UNLINK => 0 );
833 my $ods_filepath = $ods_fh->filename;
835 use OpenOffice::OODoc;
836 my $tmpdir = dirname $ods_filepath;
837 odfWorkingDirectory( $tmpdir );
838 my $container = odfContainer( $ods_filepath, create => 'spreadsheet' );
839 my $doc = odfDocument (
840 container => $container,
843 my $table = $doc->getTable(0);
844 my @headers = header_cell_values( $sth );
845 my $rows = $sth->fetchall_arrayref();
846 my ( $nb_rows, $nb_cols ) = ( 0, 0 );
849 $doc->expandTable( $table, $nb_rows + 1, $nb_cols );
851 my $row = $doc->getRow( $table, 0 );
853 for my $header ( @headers ) {
854 $doc->cellValue( $row, $j, $header );
859 $row = $doc->getRow( $table, $i );
860 for ( my $j = 0 ; $j < $nb_cols ; $j++ ) {
861 my $value = Encode::encode( 'UTF8', $rows->[$i - 1][$j] );
862 $doc->cellValue( $row, $j, $value );
868 open $ods_fh, '<', $ods_filepath;
869 $content .= $_ while <$ods_fh>;
870 unlink $ods_filepath;
873 print $input->header(
875 -attachment=> $reportfilename
879 foreach my $err (@$q_errors, @errors) {
880 print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n";
881 } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing.
887 'name' => 'Error exporting report!',
889 'errors' => $q_errors,
893 elsif ( $phase eq 'Create report from SQL' ) {
895 my ($group, $subgroup);
896 # allow the user to paste in sql
897 if ( $input->param('sql') ) {
898 $group = $input->param('report_group');
899 $subgroup = $input->param('report_subgroup');
901 'sql' => $input->param('sql') // '',
902 'reportname' => $input->param('reportname') // '',
903 'notes' => $input->param('notes') // '',
908 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup),
910 'cache_expiry' => 300,
911 'usecache' => $usecache,
915 elsif ($phase eq 'Create Compound Report'){
916 $template->param( 'savedreports' => get_saved_reports(),
921 elsif ($phase eq 'Save Compound'){
922 my $master = $input->param('master');
923 my $subreport = $input->param('subreport');
924 my ($mastertables,$subtables) = create_compound($master,$subreport);
925 $template->param( 'save_compound' => 1,
926 master=>$mastertables,
931 # pass $sth, get back an array of names for the column headers
932 sub header_cell_values {
933 my $sth = shift or return ();
934 return '' unless ($sth->{NAME});
935 return @{$sth->{NAME}};
938 # pass $sth, get back a TMPL_LOOP-able set of names for the column headers
939 sub header_cell_loop {
940 my @headers = map { +{ cell => $_ } } header_cell_values (shift);
945 $template->{VARS}->{'build' . $_} and $template->{VARS}->{'buildx' . $_} and last;
947 $template->param( 'referer' => $input->referer(),
950 output_html_with_http_headers $input, $cookie, $template->output;
952 sub groups_with_subgroups {
953 my ($group, $subgroup) = @_;
955 my $groups_with_subgroups = get_report_groups();
957 my @sorted_keys = sort {
958 $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name}
959 } keys %$groups_with_subgroups;
960 foreach my $g_id (@sorted_keys) {
961 my $v = $groups_with_subgroups->{$g_id};
963 if (my $sg = $v->{subgroups}) {
964 foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) {
967 name => $sg->{$sg_id},
968 selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ),
975 selected => ($group && $g_id eq $group),
976 subgroups => \@subgroups,
982 sub create_non_existing_group_and_subgroup {
983 my ($input, $group, $subgroup) = @_;
985 if (defined $group and $group ne '') {
986 my $report_groups = C4::Reports::Guided::get_report_groups;
987 if (not exists $report_groups->{$group}) {
988 my $groupdesc = $input->param('groupdesc') // $group;
989 C4::Koha::AddAuthorisedValue('REPORT_GROUP', $group, $groupdesc);
991 if (defined $subgroup and $subgroup ne '') {
992 if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) {
993 my $subgroupdesc = $input->param('subgroupdesc') // $subgroup;
994 C4::Koha::AddAuthorisedValue('REPORT_SUBGROUP', $subgroup, $subgroupdesc, $group);