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