Bug 7317: Handle backend absense more gracefuly
[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 @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 our $itemtypes = Koha::ItemTypes->search_with_localization;
156
157     # location list
158 my @locations;
159 foreach (sort keys %$locations) {
160         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
161 }
162     
163 my @ccodes;
164 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
165         push @ccodes, { code => $_, description => $ccodes->{$_} };
166 }
167
168 my $CGIextChoice = ( 'CSV' ); # FIXME translation
169 my $CGIsepChoice=GetDelimiterChoices;
170
171 my @attribute_types = C4::Members::AttributeTypes::GetAttributeTypes(1);
172 my %attribute_types_by_class;
173 foreach my $attribute_type (@attribute_types) {
174     if ($attribute_type->{authorised_value_category}) {
175         my $authorised_values = C4::Koha::GetAuthorisedValues(
176             $attribute_type->{authorised_value_category});
177
178         foreach my $authorised_value (@$authorised_values) {
179             push @{ $attribute_type->{authorised_values} }, $authorised_value;
180         }
181     }
182     push @{ $attribute_types_by_class{$attribute_type->{class}} }, $attribute_type;
183 }
184
185 $template->param(
186     categoryloop => \@patron_categories,
187     itemtypes    => $itemtypes,
188     locationloop => \@locations,
189     ccodeloop    => \@ccodes,
190     hassort1     => $hassort1,
191     hassort2     => $hassort2,
192     Bsort1       => $Bsort1,
193     Bsort2       => $Bsort2,
194     CGIextChoice => $CGIextChoice,
195     CGIsepChoice => $CGIsepChoice,
196     attribute_types_by_class => \%attribute_types_by_class,
197 );
198 output_html_with_http_headers $input, $cookie, $template->output;
199
200 sub calculate {
201     my ( $line, $column, $dsp, $type, $daysel, $monthsel, $process, $filters, $attribute_filters ) = @_;
202     my @loopfooter;
203     my @loopcol;
204     my @loopline;
205     my @looprow;
206     my %globalline;
207     my $grantotal = 0;
208
209     # extract parameters
210     my $dbh = C4::Context->dbh;
211
212     my ($line_attribute_type, $column_attribute_type);
213     if($line =~ /^borrower_attributes\.(.*)/) {
214         $line_attribute_type = $1;
215         $line = "borrower_attributes.attribute";
216     }
217     if($column =~ /^borrower_attributes\.(.*)/) {
218         $column_attribute_type = $1;
219         $column = "borrower_attributes.attribute";
220     }
221
222     # Filters
223     # Checking filters
224     #
225     my @loopfilter;
226     for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
227         my %cell;
228         ( @$filters[$i] ) or next;
229         if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) {
230             $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
231         }
232             # format the dates filters, otherwise just fill as is
233         if ($i>=2) {
234             $cell{filter} = @$filters[$i];
235         } else {
236             $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
237               if ( @$filters[$i] );
238         }
239         $cell{crit} = $i;
240
241         push @loopfilter, \%cell;
242     }
243     foreach (keys %$attribute_filters) {
244         next unless $attribute_filters->{$_};
245         push @loopfilter, { crit => "$_ =", filter => $attribute_filters->{$_} };
246     }
247     push @loopfilter, { crit => "Event",        filter => $type };
248     push @loopfilter, { crit => "Display by",   filter => $dsp } if ($dsp);
249     push @loopfilter, { crit => "Select Day",   filter => $daysel } if ($daysel);
250     push @loopfilter, { crit => "Select Month", filter => $monthsel } if ($monthsel);
251
252     my @linefilter;
253     $debug and warn "filtres " . join "|", @$filters;
254     my ( $colsource, $linesource ) = ('', '');
255     $linefilter[1] = @$filters[1] if ( $line =~ /datetime/ );
256     $linefilter[0] =
257         ( $line =~ /datetime/ )     ? @$filters[0]
258       : ( $line =~ /category/ )     ? @$filters[2]
259       : ( $line =~ /itemtype/ )     ? @$filters[3]
260       : ( $line =~ /^branch/ )      ? @$filters[4]
261       : ( $line =~ /ccode/ )        ? @$filters[5]
262       : ( $line =~ /location/ )     ? @$filters[6]
263       : ( $line =~ /sort1/ )        ? @$filters[9]
264       : ( $line =~ /sort2/ )        ? @$filters[10]
265       : ( $line =~ /homebranch/)    ? @$filters[11]
266       : ( $line =~ /holdingbranch/) ? @$filters[12]
267       : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13]
268       : ( $line_attribute_type )    ? $attribute_filters->{$line_attribute_type}
269       :                               undef;
270
271     if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
272                 $linesource = 'items';
273         }
274
275         my @colfilter;
276         $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
277         $colfilter[0] = 
278         ( $column =~ /datetime/ ) ? @$filters[0]
279       : ( $column =~ /category/ ) ? @$filters[2]
280       : ( $column =~ /itemtype/ ) ? @$filters[3]
281       : ( $column =~ /^branch/ )   ? @$filters[4]
282       : ( $column =~ /ccode/ )    ? @$filters[5]
283       : ( $column =~ /location/ ) ? @$filters[6]
284       : ( $column =~ /sort1/ )    ? @$filters[9]
285       : ( $column =~ /sort1/ )    ? @$filters[10]
286       : ( $column =~ /homebranch/)    ? @$filters[11]
287       : ( $column =~ /holdingbranch/) ? @$filters[12]
288       : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13]
289       : ( $column_attribute_type )    ? $attribute_filters->{$column_attribute_type}
290       :                                 undef;
291
292     if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
293         $colsource = 'items';
294     }
295
296     # 1st, loop rows.
297     my $linefield;
298     if ( $line =~ /datetime/ ) {
299
300         # by Day, Month, Year or Hour (1,2,3,4 respectively)
301         $linefield =
302             ( $dsp == 1 ) ? "  dayname($line)"
303           : ( $dsp == 2 ) ? "monthname($line)"
304           : ( $dsp == 3 ) ? "     Year($line)"
305           : ( $dsp == 4 ) ? "extract(hour from $line)"
306           :                 'date_format(`datetime`,"%Y-%m-%d")';    # Probably should be left alone or passed through Koha::Dates
307     } else {
308         $linefield = $line;
309     }
310     my $lineorder =
311         ( $linefield =~ /dayname/ ) ? "weekday($line)"
312       : ( $linefield =~ /^month/ )  ? "  month($line)"
313       :                               $linefield;
314
315     my $strsth;
316     if($line_attribute_type) {
317         $strsth = "SELECT attribute FROM borrower_attributes WHERE code = '$line_attribute_type' ";
318     } else {
319         $strsth = "SELECT distinctrow $linefield FROM statistics ";
320
321         # get stats on items if ccode or location, otherwise borrowers.
322         $strsth .=
323           ( $linesource eq 'items' )
324           ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
325           : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
326         $strsth .= " WHERE $line is not null AND $line != '' ";
327     }
328
329     if ( $line =~ /datetime/ ) {
330         if ( $linefilter[1] and ( $linefilter[0] ) ) {
331             $strsth .= " AND $line between ? AND ? ";
332         } elsif ( $linefilter[1] ) {
333             $strsth .= " AND $line <= ? ";
334         } elsif ( $linefilter[0] ) {
335             $strsth .= " AND $line >= ? ";
336         }
337         $strsth .= " AND type ='" . $type . "' "                    if $type;
338         $strsth .= " AND   dayname(datetime) ='" . $daysel . "' "   if $daysel;
339         $strsth .= " AND monthname(datetime) ='" . $monthsel . "' " if $monthsel;
340     } elsif ( $linefilter[0] ) {
341         $linefilter[0] =~ s/\*/%/g;
342         $strsth .= " AND $line LIKE ? ";
343     }
344     $strsth .= " group by $linefield order by $lineorder ";
345     $debug and warn $strsth;
346     push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth };
347     my $sth = $dbh->prepare($strsth);
348     if ( (@linefilter) and ($linefilter[0]) and ($linefilter[1]) ) {
349         $sth->execute( $linefilter[0], $linefilter[1] . " 23:59:59" );
350     } elsif ( $linefilter[1] ) {
351         $sth->execute( $linefilter[1] . " 23:59:59" );
352     } elsif ( $linefilter[0] ) {
353         $sth->execute( $linefilter[0] );
354     } else {
355         $sth->execute;
356     }
357
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->{$celvalue}->{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->{$celvalue}->{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;