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