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