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