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