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