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