Bug 30718: Use flatpickr's altInput
[koha.git] / reports / issues_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23
24 use C4::Auth qw( get_template_and_user );
25 use C4::Context;
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Output qw( output_html_with_http_headers );
28 use C4::Reports qw( GetDelimiterChoices );
29
30 use Koha::AuthorisedValues;
31 use Koha::ItemTypes;
32 use Koha::Patron::Attribute::Types;
33
34 =head1 NAME
35
36 reports/issues_stats.pl
37
38 =head1 DESCRIPTION
39
40 Plugin that shows circulation stats
41
42 =cut
43
44 my $input = CGI->new;
45 my $fullreportname = "reports/issues_stats.tt";
46 my $do_it    = $input->param('do_it');
47 my $line     = $input->param("Line");
48 my $column   = $input->param("Column");
49 my @filters  = $input->multi_param("Filter");
50 my $podsp    = $input->param("DisplayBy");
51 my $type     = $input->param("PeriodTypeSel");
52 my $daysel   = $input->param("PeriodDaySel");
53 my $monthsel = $input->param("PeriodMonthSel");
54 my $calc     = $input->param("Cellvalue");
55 my $output   = $input->param("output");
56 my $basename = $input->param("basename");
57
58 my $attribute_filters;
59 my $vars = $input->Vars;
60 foreach(keys %$vars) {
61     if(/^Filter_borrower_attributes\.(.*)/) {
62         $attribute_filters->{$1} = $vars->{$_};
63     }
64 }
65
66
67 my ($template, $borrowernumber, $cookie) = get_template_and_user({
68         template_name => $fullreportname,
69         query => $input,
70         type => "intranet",
71         flagsrequired => {reports => '*'},
72 });
73 our $sep     = $input->param("sep") // ';';
74 $sep = "\t" if ($sep eq 'tabulation');
75 $template->param(do_it => $do_it,
76 );
77
78 our $itemtypes = Koha::ItemTypes->search_with_localization->unblessed;
79
80 our @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list;
81
82 our $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
83 our $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
84
85 our $Bsort1 = GetAuthorisedValues("Bsort1");
86 our $Bsort2 = GetAuthorisedValues("Bsort2");
87 my ($hassort1,$hassort2);
88 $hassort1=1 if $Bsort1;
89 $hassort2=1 if $Bsort2;
90
91 if ($do_it) {
92     # Displaying results
93     my $results = calculate( $line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters, $attribute_filters);
94     if ( $output eq "screen" ) {
95
96         # Printing results to screen
97         $template->param( mainloop => $results );
98         output_html_with_http_headers $input, $cookie, $template->output;
99     } else {
100
101         # Printing to a csv file
102         print $input->header(
103             -type       => 'application/vnd.sun.xml.calc',
104             -encoding   => 'utf-8',
105             -attachment => "$basename.csv",
106             -filename   => "$basename.csv"
107         );
108         my $cols  = @$results[0]->{loopcol};
109         my $lines = @$results[0]->{looprow};
110
111         # header top-right
112         print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
113
114         # Other header
115         foreach my $col (@$cols) {
116             print $col->{coltitle} . $sep;
117         }
118         print "Total\n";
119
120         # Table
121         foreach my $line (@$lines) {
122             my $x = $line->{loopcell};
123             print $line->{rowtitle} . $sep;
124             print map { $_->{value} . $sep } @$x;
125             print $line->{totalrow}, "\n";
126         }
127
128         # footer
129         print "TOTAL";
130         $cols = @$results[0]->{loopfooter};
131         print map {$sep.$_->{totalcol}} @$cols;
132         print $sep.@$results[0]->{total};
133     }
134     exit;
135 }
136
137
138 my $dbh = C4::Context->dbh;
139
140     # location list
141 my @locations;
142 foreach (sort keys %$locations) {
143         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
144 }
145     
146 my @ccodes;
147 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
148         push @ccodes, { code => $_, description => $ccodes->{$_} };
149 }
150
151 my $CGIextChoice = ( 'CSV' ); # FIXME translation
152 my $CGIsepChoice=GetDelimiterChoices;
153
154 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
155 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
156 my %attribute_types_by_class;
157 while ( my ( $attribute_type ) = $attribute_types->next ) {
158     $attribute_type = $attribute_type->unblessed;
159     if ($attribute_type->{authorised_value_category}) {
160         my $authorised_values = C4::Koha::GetAuthorisedValues(
161             $attribute_type->{authorised_value_category});
162
163         foreach my $authorised_value (@$authorised_values) {
164             push @{ $attribute_type->{authorised_values} }, $authorised_value;
165         }
166     }
167     push @{ $attribute_types_by_class{$attribute_type->{class}} }, $attribute_type;
168 }
169
170 $template->param(
171     categoryloop => \@patron_categories,
172     itemtypes    => $itemtypes,
173     locationloop => \@locations,
174     ccodeloop    => \@ccodes,
175     hassort1     => $hassort1,
176     hassort2     => $hassort2,
177     Bsort1       => $Bsort1,
178     Bsort2       => $Bsort2,
179     CGIextChoice => $CGIextChoice,
180     CGIsepChoice => $CGIsepChoice,
181     attribute_types_by_class => \%attribute_types_by_class,
182 );
183 output_html_with_http_headers $input, $cookie, $template->output;
184
185 sub calculate {
186     my ( $line, $column, $dsp, $type, $daysel, $monthsel, $process, $filters, $attribute_filters ) = @_;
187     my @loopfooter;
188     my @loopcol;
189     my @loopline;
190     my @looprow;
191     my %globalline;
192     my $grantotal = 0;
193
194     # extract parameters
195     my $dbh = C4::Context->dbh;
196
197     my ($line_attribute_type, $column_attribute_type);
198     if($line =~ /^borrower_attributes\.(.*)/) {
199         $line_attribute_type = $1;
200         $line = "borrower_attributes.attribute";
201     }
202     if($column =~ /^borrower_attributes\.(.*)/) {
203         $column_attribute_type = $1;
204         $column = "borrower_attributes.attribute";
205     }
206
207     # Filters
208     # Checking filters
209     #
210     my @loopfilter;
211     for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
212         my %cell;
213         ( @$filters[$i] ) or next;
214         if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) {
215             $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
216         }
217             # format the dates filters, otherwise just fill as is
218         $cell{filter} = @$filters[$i];
219         $cell{crit} = $i;
220
221         push @loopfilter, \%cell;
222     }
223     foreach (keys %$attribute_filters) {
224         next unless $attribute_filters->{$_};
225         push @loopfilter, { crit => "$_ =", filter => $attribute_filters->{$_} };
226     }
227     push @loopfilter, { crit => "Event",        filter => $type };
228     push @loopfilter, { crit => "Display by",   filter => $dsp } if ($dsp);
229     push @loopfilter, { crit => "Select Day",   filter => $daysel } if ($daysel);
230     push @loopfilter, { crit => "Select Month", filter => $monthsel } if ($monthsel);
231
232     my @linefilter;
233     my ( $colsource, $linesource ) = ('', '');
234     $linefilter[1] = @$filters[1] if ( $line =~ /datetime/ );
235     $linefilter[0] =
236         ( $line =~ /datetime/ )     ? @$filters[0]
237       : ( $line =~ /category/ )     ? @$filters[2]
238       : ( $line =~ /itemtype/ )     ? @$filters[3]
239       : ( $line =~ /^branch/ )      ? @$filters[4]
240       : ( $line =~ /ccode/ )        ? @$filters[5]
241       : ( $line =~ /location/ )     ? @$filters[6]
242       : ( $line =~ /sort1/ )        ? @$filters[9]
243       : ( $line =~ /sort2/ )        ? @$filters[10]
244       : ( $line =~ /homebranch/)    ? @$filters[11]
245       : ( $line =~ /holdingbranch/) ? @$filters[12]
246       : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13]
247       : ( $line_attribute_type )    ? $attribute_filters->{$line_attribute_type}
248       :                               undef;
249
250     if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
251                 $linesource = 'items';
252         }
253
254         my @colfilter;
255         $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
256         $colfilter[0] = 
257         ( $column =~ /datetime/ ) ? @$filters[0]
258       : ( $column =~ /category/ ) ? @$filters[2]
259       : ( $column =~ /itemtype/ ) ? @$filters[3]
260       : ( $column =~ /^branch/ )   ? @$filters[4]
261       : ( $column =~ /ccode/ )    ? @$filters[5]
262       : ( $column =~ /location/ ) ? @$filters[6]
263       : ( $column =~ /sort1/ )    ? @$filters[9]
264       : ( $column =~ /sort1/ )    ? @$filters[10]
265       : ( $column =~ /homebranch/)    ? @$filters[11]
266       : ( $column =~ /holdingbranch/) ? @$filters[12]
267       : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13]
268       : ( $column_attribute_type )    ? $attribute_filters->{$column_attribute_type}
269       :                                 undef;
270
271     if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
272         $colsource = 'items';
273     }
274
275     # 1st, loop rows.
276     my $linefield;
277     if ( $line =~ /datetime/ ) {
278
279         # by Day, Month, Year or Hour (1,2,3,4 respectively)
280         $linefield =
281             ( $dsp == 1 ) ? "  dayname($line)"
282           : ( $dsp == 2 ) ? "monthname($line)"
283           : ( $dsp == 3 ) ? "     Year($line)"
284           : ( $dsp == 4 ) ? "extract(hour from $line)"
285           :                 'date_format(`datetime`,"%Y-%m-%d")';    # Probably should be left alone or passed through Koha::Dates
286     } else {
287         $linefield = $line;
288     }
289     my $lineorder =
290         ( $linefield =~ /dayname/ ) ? "weekday($line)"
291       : ( $linefield =~ /^month/ )  ? "  month($line)"
292       :                               $linefield;
293
294     my $strsth;
295     if($line_attribute_type) {
296         $strsth = "SELECT attribute FROM borrower_attributes WHERE code = '$line_attribute_type' ";
297     } else {
298         $strsth = "SELECT distinctrow $linefield FROM statistics ";
299
300         # get stats on items if ccode or location, otherwise borrowers.
301         $strsth .=
302           ( $linesource eq 'items' )
303           ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
304           : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
305         $strsth .= " WHERE $line IS NOT NULL ";
306         $strsth .= " AND $line != '' " if $line ne "datetime";
307     }
308
309     if ( $line =~ /datetime/ ) {
310         if ( $linefilter[1] and ( $linefilter[0] ) ) {
311             $strsth .= " AND $line between ? AND ? ";
312         } elsif ( $linefilter[1] ) {
313             $strsth .= " AND $line <= ? ";
314         } elsif ( $linefilter[0] ) {
315             $strsth .= " AND $line >= ? ";
316         }
317         $strsth .= " AND type ='" . $type . "' "                    if $type;
318         $strsth .= " AND   dayname(datetime) ='" . $daysel . "' "   if $daysel;
319         $strsth .= " AND monthname(datetime) ='" . $monthsel . "' " if $monthsel;
320     } elsif ( $linefilter[0] ) {
321         $linefilter[0] =~ s/\*/%/g;
322         $strsth .= " AND $line LIKE ? ";
323     }
324     $strsth .= " group by $linefield order by $lineorder ";
325     push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth };
326     my $sth = $dbh->prepare($strsth);
327     if ( (@linefilter) and ($linefilter[0]) and ($linefilter[1]) ) {
328         $sth->execute( $linefilter[0], $linefilter[1] . " 23:59:59" );
329     } elsif ( $linefilter[1] ) {
330         $sth->execute( $linefilter[1] . " 23:59:59" );
331     } elsif ( $linefilter[0] ) {
332         $sth->execute( $linefilter[0] );
333     } else {
334         $sth->execute;
335     }
336
337     my $itemtypes_map = { map { $_->{itemtype} => $_ } @{ $itemtypes } };
338     while ( my ($celvalue) = $sth->fetchrow ) {
339         my %cell = ( rowtitle => $celvalue, totalrow => 0 );    # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
340         $cell{rowtitle_display} =
341             ( $line =~ /ccode/ )    ? $ccodes->{$celvalue}
342           : ( $line =~ /location/ ) ? $locations->{$celvalue}
343           : ( $line =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
344           :                           $celvalue;                               # default fallback
345         if ( $line =~ /sort1/ ) {
346             foreach (@$Bsort1) {
347                 ( $celvalue eq $_->{authorised_value} ) or next;
348                 $cell{rowtitle_display} = $_->{lib} and last;
349             }
350         } elsif ( $line =~ /sort2/ ) {
351             foreach (@$Bsort2) {
352                 ( $celvalue eq $_->{authorised_value} ) or next;
353                 $cell{rowtitle_display} = $_->{lib} and last;
354             }
355         } elsif ($line =~ /category/) {
356             foreach my $patron_category ( @patron_categories ) {
357                 ($celvalue eq $patron_category->categorycode) or next;
358                 $cell{rowtitle_display} = $patron_category->description and last;
359             }
360         }
361         push @loopline, \%cell;
362     }
363
364     # 2nd, loop cols.
365     my $colfield;
366     my $colorder;
367     if ( $column =~ /datetime/ ) {
368
369         #Display by Day, Month or Year (1,2,3 respectively)
370         $colfield =
371             ( $dsp == 1 ) ? "  dayname($column)"
372           : ( $dsp == 2 ) ? "monthname($column)"
373           : ( $dsp == 3 ) ? "     Year($column)"
374           : ( $dsp == 4 ) ? "extract(hour from $column)"
375           :                 'date_format(`datetime`,"%Y-%m-%d")';    # Probably should be left alone or passed through Koha::Dates
376     } else {
377         $colfield = $column;
378     }
379     $colorder =
380         ( $colfield =~ /dayname/ ) ? "weekday($column)"
381       : ( $colfield =~ /^month/ )  ? "  month($column)"
382       :                              $colfield;
383     my $strsth2;
384     if($column_attribute_type) {
385         $strsth2 = "SELECT attribute FROM borrower_attributes WHERE code = '$column_attribute_type' ";
386     } else {
387         $strsth2 = "SELECT distinctrow $colfield FROM statistics ";
388
389         # get stats on items if ccode or location, otherwise borrowers.
390         $strsth2 .=
391           ( $colsource eq 'items' )
392           ? "LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
393           : "LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
394         $strsth2 .= " WHERE $column IS NOT NULL";
395         $strsth2 .= " AND $column != '' " if $column ne "datetime";
396     }
397
398     if ( $column =~ /datetime/ ) {
399         if ( ( $colfilter[1] ) and ( $colfilter[0] ) ) {
400             $strsth2 .= " AND $column BETWEEN ? AND ? ";
401         } elsif ( $colfilter[1] ) {
402             $strsth2 .= " AND $column <= ? ";
403         } elsif ( $colfilter[0] ) {
404             $strsth2 .= " AND $column >= ? ";
405         }
406         $strsth2 .= " AND                type ='". $type     ."' " if $type;
407         $strsth2 .= " AND   dayname(datetime) ='". $daysel   ."' " if $daysel;
408         $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
409     } elsif ($colfilter[0]) {
410         $colfilter[0] =~ s/\*/%/g;
411         $strsth2 .= " AND $column LIKE ? " ;
412     }
413
414     $strsth2 .= " group by $colfield order by $colorder ";
415     push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth2 };
416     my $sth2 = $dbh->prepare($strsth2);
417     if ( (@colfilter) and ($colfilter[0]) and ($colfilter[1]) ) {
418         $sth2->execute( $colfilter[0], $colfilter[1] . " 23:59:59" );
419     } elsif ( $colfilter[1] ) {
420         $sth2->execute( $colfilter[1] . " 23:59:59" );
421     } elsif ( $colfilter[0] ) {
422         $sth2->execute( $colfilter[0] );
423     } else {
424         $sth2->execute;
425     }
426
427     while ( my ($celvalue) = $sth2->fetchrow ) {
428         my %cell = ( coltitle => $celvalue );    # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
429         $cell{coltitle_display} =
430             ( $column =~ /ccode/ )    ? $ccodes->{$celvalue}
431           : ( $column =~ /location/ ) ? $locations->{$celvalue}
432           : ( $column =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
433           :                             $celvalue;                               # default fallback
434         if ( $column =~ /sort1/ ) {
435             foreach (@$Bsort1) {
436                 ( $celvalue eq $_->{authorised_value} ) or next;
437                 $cell{coltitle_display} = $_->{lib} and last;
438             }
439         } elsif ( $column =~ /sort2/ ) {
440             foreach (@$Bsort2) {
441                 ( $celvalue eq $_->{authorised_value} ) or next;
442                 $cell{coltitle_display} = $_->{lib} and last;
443             }
444         } elsif ($column =~ /category/) {
445             foreach my $patron_category ( @patron_categories ) {
446                 ($celvalue eq $patron_category->categorycode) or next;
447                 $cell{coltitle_display} = $patron_category->description and last;
448             }
449         }
450         push @loopcol, \%cell;
451     }
452
453     #Initialization of cell values.....
454     my %table;
455     foreach my $row (@loopline) {
456         foreach my $col (@loopcol) {
457             table_set(\%table, $row->{rowtitle}, $col->{coltitle}, 0);
458         }
459         table_set(\%table, $row->{rowtitle}, 'totalrow', 0);
460     }
461
462     # preparing calculation
463     my $strcalc = "SELECT ";
464     if($line_attribute_type) {
465         $strcalc .= "TRIM(attribute_$line_attribute_type.attribute) AS line_attribute, ";
466     } else {
467         $strcalc .= "TRIM($linefield), ";
468     }
469     if($column_attribute_type) {
470         $strcalc .= "TRIM(attribute_$column_attribute_type.attribute) AS column_attribute, ";
471     } else {
472         $strcalc .= "TRIM($colfield), ";
473     }
474     $strcalc .=
475         ( $process == 1 ) ? " COUNT(*) "
476       : ( $process == 2 ) ? "(COUNT(DISTINCT borrowers.borrowernumber))"
477       : ( $process == 3 ) ? "(COUNT(DISTINCT statistics.itemnumber))"
478       : ( $process == 5 ) ? "(COUNT(DISTINCT items.biblionumber))"
479       :                     '';
480     if ( $process == 4 ) {
481         my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
482         $rqbookcount->execute;
483         my ($bookcount) = $rqbookcount->fetchrow;
484         $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount ";
485     }
486     $strcalc .= "
487         FROM statistics
488         LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
489     ";
490     foreach (keys %$attribute_filters) {
491         if(
492             ($line_attribute_type and $line_attribute_type eq $_)
493             or $column_attribute_type and $column_attribute_type eq $_
494             or $attribute_filters->{$_}
495         ) {
496             $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$_ ON (statistics.borrowernumber = attribute_$_.borrowernumber AND attribute_$_.code = '$_') ";
497         }
498     }
499     $strcalc .= "LEFT JOIN (SELECT * FROM items UNION SELECT * FROM deleteditems) items ON statistics.itemnumber=items.itemnumber "
500       if ( $linefield =~ /^items\./
501         or $colfield =~ /^items\./
502         or $process == 5
503         or ( $colsource eq 'items' ) || @$filters[5] || @$filters[6] || @$filters[7] || @$filters[8] || @$filters[9] || @$filters[10] || @$filters[11] || @$filters[12] || @$filters[13] );
504
505     $strcalc .= "WHERE 1=1 ";
506     @$filters = map { my $f = $_; defined($f) and $f =~ s/\*/%/g; $f } @$filters;
507     $strcalc .= " AND statistics.datetime >= '" . @$filters[0] . "'"       if ( @$filters[0] );
508     $strcalc .= " AND statistics.datetime <= '" . @$filters[1] . " 23:59:59'"       if ( @$filters[1] );
509     $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] . "'" if ( @$filters[2] );
510     $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] . "'"    if ( @$filters[3] );
511     $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] . "'"      if ( @$filters[4] );
512     $strcalc .= " AND items.ccode LIKE '" . @$filters[5] . "'"            if ( @$filters[5] );
513     $strcalc .= " AND items.location LIKE '" . @$filters[6] . "'"         if ( @$filters[6] );
514     $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] . "'"      if ( @$filters[7] );
515     $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] . "'"       if ( @$filters[8] );
516     $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] . "'"        if ( @$filters[9] );
517     $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10] . "'"       if ( @$filters[10] );
518     $strcalc .= " AND items.homebranch LIKE '" . @$filters[11] . "'"      if ( @$filters[11] );
519     $strcalc .= " AND items.holdingbranch LIKE '" . @$filters[12] . "'"   if ( @$filters[12] );
520     $strcalc .= " AND borrowers.branchcode LIKE '" . @$filters[13] . "'"  if ( @$filters[13] );
521     $strcalc .= " AND dayname(datetime) LIKE '" . $daysel . "'"           if ($daysel);
522     $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel . "'"       if ($monthsel);
523     $strcalc .= " AND statistics.type LIKE '" . $type . "'"               if ($type);
524     foreach (keys %$attribute_filters) {
525         if($attribute_filters->{$_}) {
526             $strcalc .= " AND attribute_$_.attribute LIKE '" . $attribute_filters->{$_} . "'";
527         }
528     }
529
530     $strcalc .= " GROUP BY ";
531     if($line_attribute_type) {
532         $strcalc .= " line_attribute, ";
533     } else {
534         $strcalc .= " $linefield, ";
535     }
536     if($column_attribute_type) {
537         $strcalc .= " column_attribute ";
538     } else {
539         $strcalc .= " $colfield ";
540     }
541
542     $strcalc .= " ORDER BY ";
543     if($line_attribute_type) {
544         $strcalc .= " line_attribute, ";
545     } else {
546         $strcalc .= " $lineorder, ";
547     }
548     if($column_attribute_type) {
549         $strcalc .= " column_attribute ";
550     } else {
551         $strcalc .= " $colorder ";
552     }
553
554     my $dbcalc = $dbh->prepare($strcalc);
555     push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strcalc };
556     $dbcalc->execute;
557     my ( $emptycol, $emptyrow );
558     while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
559         unless ( defined $col ) {
560             $emptycol = 1;
561         }
562         unless ( defined $row ) {
563             $emptyrow = 1;
564         }
565         table_inc(\%table, $row, $col, $value);
566         table_inc(\%table, $row, 'totalrow', $value);
567         $grantotal               += $value;
568     }
569     push @loopcol,  { coltitle => "NULL", coltitle_display => 'NULL' } if ($emptycol);
570     push @loopline, { rowtitle => "NULL", rowtitle_display => 'NULL' } if ($emptyrow);
571
572     foreach my $row (@loopline) {
573         my @loopcell;
574
575         #@loopcol ensures the order for columns is common with column titles
576         # and the number matches the number of columns
577         foreach my $col (@loopcol) {
578             my $value = table_get(\%table, $row->{rowtitle}, $col->{coltitle});
579             push @loopcell, { value => $value };
580         }
581         push @looprow,
582           { 'rowtitle_display' => $row->{rowtitle_display},
583             'rowtitle'         => $row->{rowtitle},
584             'loopcell'         => \@loopcell,
585             'totalrow'         => table_get(\%table, $row->{rowtitle}, 'totalrow'),
586           };
587     }
588     for my $col (@loopcol) {
589         my $total = 0;
590         foreach my $row (@looprow) {
591             $total += table_get(\%table, $row->{rowtitle}, $col->{coltitle}) || 0;
592         }
593         push @loopfooter, { 'totalcol' => $total };
594     }
595
596     # the header of the table
597     $globalline{loopfilter} = \@loopfilter;
598
599     # the core of the table
600     $globalline{looprow} = \@looprow;
601     $globalline{loopcol} = \@loopcol;
602
603     #   # the foot (totals by borrower type)
604     $globalline{loopfooter} = \@loopfooter;
605     $globalline{total}      = $grantotal;
606     $globalline{line}       = $line_attribute_type ? $line_attribute_type : $line;
607     $globalline{column}     = $column_attribute_type ? $column_attribute_type : $column;
608     return [ ( \%globalline ) ];
609 }
610
611 sub null_to_zzempty {
612     my $string = shift;
613
614     if (!defined($string) or $string eq '' or uc($string) eq 'NULL') {
615         return 'zzEMPTY';
616     }
617
618     return $string;
619 }
620
621 sub table_set {
622     my ($table, $row, $col, $val) = @_;
623
624     $row = $row // '';
625     $col = $col // '';
626     $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } = $val;
627 }
628
629 sub table_get {
630     my ($table, $row, $col) = @_;
631
632     $row = $row // '';
633     $col = $col // '';
634     return $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) };
635 }
636
637 sub table_inc {
638     my ($table, $row, $col, $inc) = @_;
639
640     $row = $row // '';
641     $col = $col // '';
642     $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } += $inc;
643 }
644
645 1;