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