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