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