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