Bug 22417: Fix borrowernumber values
[koha.git] / reports / issues_stats.pl
blob8f86fdb113fa81e0ac8d192ad02f03a00e182338
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
22 use CGI qw ( -utf8 );
23 use Date::Manip;
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;
34 use Koha::AuthorisedValues;
35 use Koha::DateUtils;
36 use Koha::ItemTypes;
37 use Koha::Patron::Attribute::Types;
39 =head1 NAME
41 reports/issues_stats.pl
43 =head1 DESCRIPTION
45 Plugin that shows circulation stats
47 =cut
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");
68 my $attribute_filters;
69 my $vars = $input->Vars;
70 foreach(keys %$vars) {
71 if(/^Filter_borrower_attributes\.(.*)/) {
72 $attribute_filters->{$1} = $vars->{$_};
77 my ($template, $borrowernumber, $cookie) = get_template_and_user({
78 template_name => $fullreportname,
79 query => $input,
80 type => "intranet",
81 flagsrequired => {reports => '*'},
82 debug => 0,
83 });
84 our $sep = $input->param("sep") // ';';
85 $sep = "\t" if ($sep eq 'tabulation');
86 $template->param(do_it => $do_it,
89 our $itemtypes = Koha::ItemTypes->search_with_localization->unblessed;
91 our @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
93 our $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
94 our $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
96 our $Bsort1 = GetAuthorisedValues("Bsort1");
97 our $Bsort2 = GetAuthorisedValues("Bsort2");
98 my ($hassort1,$hassort2);
99 $hassort1=1 if $Bsort1;
100 $hassort2=1 if $Bsort2;
102 if ($do_it) {
103 # Displaying results
104 my $results = calculate( $line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters, $attribute_filters);
105 if ( $output eq "screen" ) {
107 # Printing results to screen
108 $template->param( mainloop => $results );
109 output_html_with_http_headers $input, $cookie, $template->output;
110 } else {
112 # Printing to a csv file
113 print $input->header(
114 -type => 'application/vnd.sun.xml.calc',
115 -encoding => 'utf-8',
116 -attachment => "$basename.csv",
117 -filename => "$basename.csv"
119 my $cols = @$results[0]->{loopcol};
120 my $lines = @$results[0]->{looprow};
122 # header top-right
123 print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
125 # Other header
126 foreach my $col (@$cols) {
127 print $col->{coltitle} . $sep;
129 print "Total\n";
131 # Table
132 foreach my $line (@$lines) {
133 my $x = $line->{loopcell};
134 print $line->{rowtitle} . $sep;
135 print map { $_->{value} . $sep } @$x;
136 print $line->{totalrow}, "\n";
139 # footer
140 print "TOTAL";
141 $cols = @$results[0]->{loopfooter};
142 print map {$sep.$_->{totalcol}} @$cols;
143 print $sep.@$results[0]->{total};
145 exit;
149 my $dbh = C4::Context->dbh;
151 # location list
152 my @locations;
153 foreach (sort keys %$locations) {
154 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
157 my @ccodes;
158 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
159 push @ccodes, { code => $_, description => $ccodes->{$_} };
162 my $CGIextChoice = ( 'CSV' ); # FIXME translation
163 my $CGIsepChoice=GetDelimiterChoices;
165 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
166 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
167 my %attribute_types_by_class;
168 while ( my ( $attribute_type ) = $attribute_types->next ) {
169 $attribute_type = $attribute_type->unblessed;
170 if ($attribute_type->{authorised_value_category}) {
171 my $authorised_values = C4::Koha::GetAuthorisedValues(
172 $attribute_type->{authorised_value_category});
174 foreach my $authorised_value (@$authorised_values) {
175 push @{ $attribute_type->{authorised_values} }, $authorised_value;
178 push @{ $attribute_types_by_class{$attribute_type->{class}} }, $attribute_type;
181 $template->param(
182 categoryloop => \@patron_categories,
183 itemtypes => $itemtypes,
184 locationloop => \@locations,
185 ccodeloop => \@ccodes,
186 hassort1 => $hassort1,
187 hassort2 => $hassort2,
188 Bsort1 => $Bsort1,
189 Bsort2 => $Bsort2,
190 CGIextChoice => $CGIextChoice,
191 CGIsepChoice => $CGIsepChoice,
192 attribute_types_by_class => \%attribute_types_by_class,
194 output_html_with_http_headers $input, $cookie, $template->output;
196 sub calculate {
197 my ( $line, $column, $dsp, $type, $daysel, $monthsel, $process, $filters, $attribute_filters ) = @_;
198 my @loopfooter;
199 my @loopcol;
200 my @loopline;
201 my @looprow;
202 my %globalline;
203 my $grantotal = 0;
205 # extract parameters
206 my $dbh = C4::Context->dbh;
208 my ($line_attribute_type, $column_attribute_type);
209 if($line =~ /^borrower_attributes\.(.*)/) {
210 $line_attribute_type = $1;
211 $line = "borrower_attributes.attribute";
213 if($column =~ /^borrower_attributes\.(.*)/) {
214 $column_attribute_type = $1;
215 $column = "borrower_attributes.attribute";
218 # Filters
219 # Checking filters
221 my @loopfilter;
222 for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
223 my %cell;
224 ( @$filters[$i] ) or next;
225 if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) {
226 $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
228 # format the dates filters, otherwise just fill as is
229 if ($i>=2) {
230 $cell{filter} = @$filters[$i];
231 } else {
232 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
233 if ( @$filters[$i] );
235 $cell{crit} = $i;
237 push @loopfilter, \%cell;
239 foreach (keys %$attribute_filters) {
240 next unless $attribute_filters->{$_};
241 push @loopfilter, { crit => "$_ =", filter => $attribute_filters->{$_} };
243 push @loopfilter, { crit => "Event", filter => $type };
244 push @loopfilter, { crit => "Display by", filter => $dsp } if ($dsp);
245 push @loopfilter, { crit => "Select Day", filter => $daysel } if ($daysel);
246 push @loopfilter, { crit => "Select Month", filter => $monthsel } if ($monthsel);
248 my @linefilter;
249 $debug and warn "filtres " . join "|", @$filters;
250 my ( $colsource, $linesource ) = ('', '');
251 $linefilter[1] = @$filters[1] if ( $line =~ /datetime/ );
252 $linefilter[0] =
253 ( $line =~ /datetime/ ) ? @$filters[0]
254 : ( $line =~ /category/ ) ? @$filters[2]
255 : ( $line =~ /itemtype/ ) ? @$filters[3]
256 : ( $line =~ /^branch/ ) ? @$filters[4]
257 : ( $line =~ /ccode/ ) ? @$filters[5]
258 : ( $line =~ /location/ ) ? @$filters[6]
259 : ( $line =~ /sort1/ ) ? @$filters[9]
260 : ( $line =~ /sort2/ ) ? @$filters[10]
261 : ( $line =~ /homebranch/) ? @$filters[11]
262 : ( $line =~ /holdingbranch/) ? @$filters[12]
263 : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13]
264 : ( $line_attribute_type ) ? $attribute_filters->{$line_attribute_type}
265 : undef;
267 if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
268 $linesource = 'items';
271 my @colfilter;
272 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
273 $colfilter[0] =
274 ( $column =~ /datetime/ ) ? @$filters[0]
275 : ( $column =~ /category/ ) ? @$filters[2]
276 : ( $column =~ /itemtype/ ) ? @$filters[3]
277 : ( $column =~ /^branch/ ) ? @$filters[4]
278 : ( $column =~ /ccode/ ) ? @$filters[5]
279 : ( $column =~ /location/ ) ? @$filters[6]
280 : ( $column =~ /sort1/ ) ? @$filters[9]
281 : ( $column =~ /sort1/ ) ? @$filters[10]
282 : ( $column =~ /homebranch/) ? @$filters[11]
283 : ( $column =~ /holdingbranch/) ? @$filters[12]
284 : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13]
285 : ( $column_attribute_type ) ? $attribute_filters->{$column_attribute_type}
286 : undef;
288 if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
289 $colsource = 'items';
292 # 1st, loop rows.
293 my $linefield;
294 if ( $line =~ /datetime/ ) {
296 # by Day, Month, Year or Hour (1,2,3,4 respectively)
297 $linefield =
298 ( $dsp == 1 ) ? " dayname($line)"
299 : ( $dsp == 2 ) ? "monthname($line)"
300 : ( $dsp == 3 ) ? " Year($line)"
301 : ( $dsp == 4 ) ? "extract(hour from $line)"
302 : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates
303 } else {
304 $linefield = $line;
306 my $lineorder =
307 ( $linefield =~ /dayname/ ) ? "weekday($line)"
308 : ( $linefield =~ /^month/ ) ? " month($line)"
309 : $linefield;
311 my $strsth;
312 if($line_attribute_type) {
313 $strsth = "SELECT attribute FROM borrower_attributes WHERE code = '$line_attribute_type' ";
314 } else {
315 $strsth = "SELECT distinctrow $linefield FROM statistics ";
317 # get stats on items if ccode or location, otherwise borrowers.
318 $strsth .=
319 ( $linesource eq 'items' )
320 ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
321 : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
322 $strsth .= " WHERE $line is not null AND $line != '' ";
325 if ( $line =~ /datetime/ ) {
326 if ( $linefilter[1] and ( $linefilter[0] ) ) {
327 $strsth .= " AND $line between ? AND ? ";
328 } elsif ( $linefilter[1] ) {
329 $strsth .= " AND $line <= ? ";
330 } elsif ( $linefilter[0] ) {
331 $strsth .= " AND $line >= ? ";
333 $strsth .= " AND type ='" . $type . "' " if $type;
334 $strsth .= " AND dayname(datetime) ='" . $daysel . "' " if $daysel;
335 $strsth .= " AND monthname(datetime) ='" . $monthsel . "' " if $monthsel;
336 } elsif ( $linefilter[0] ) {
337 $linefilter[0] =~ s/\*/%/g;
338 $strsth .= " AND $line LIKE ? ";
340 $strsth .= " group by $linefield order by $lineorder ";
341 $debug and warn $strsth;
342 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth };
343 my $sth = $dbh->prepare($strsth);
344 if ( (@linefilter) and ($linefilter[0]) and ($linefilter[1]) ) {
345 $sth->execute( $linefilter[0], $linefilter[1] . " 23:59:59" );
346 } elsif ( $linefilter[1] ) {
347 $sth->execute( $linefilter[1] . " 23:59:59" );
348 } elsif ( $linefilter[0] ) {
349 $sth->execute( $linefilter[0] );
350 } else {
351 $sth->execute;
354 my $itemtypes_map = { map { $_->{itemtype} => $_ } @{ $itemtypes } };
355 while ( my ($celvalue) = $sth->fetchrow ) {
356 my %cell = ( rowtitle => $celvalue, totalrow => 0 ); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
357 $cell{rowtitle_display} =
358 ( $line =~ /ccode/ ) ? $ccodes->{$celvalue}
359 : ( $line =~ /location/ ) ? $locations->{$celvalue}
360 : ( $line =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
361 : $celvalue; # default fallback
362 if ( $line =~ /sort1/ ) {
363 foreach (@$Bsort1) {
364 ( $celvalue eq $_->{authorised_value} ) or next;
365 $cell{rowtitle_display} = $_->{lib} and last;
367 } elsif ( $line =~ /sort2/ ) {
368 foreach (@$Bsort2) {
369 ( $celvalue eq $_->{authorised_value} ) or next;
370 $cell{rowtitle_display} = $_->{lib} and last;
372 } elsif ($line =~ /category/) {
373 foreach my $patron_category ( @patron_categories ) {
374 ($celvalue eq $patron_category->categorycode) or next;
375 $cell{rowtitle_display} = $patron_category->description and last;
378 push @loopline, \%cell;
381 # 2nd, loop cols.
382 my $colfield;
383 my $colorder;
384 if ( $column =~ /datetime/ ) {
386 #Display by Day, Month or Year (1,2,3 respectively)
387 $colfield =
388 ( $dsp == 1 ) ? " dayname($column)"
389 : ( $dsp == 2 ) ? "monthname($column)"
390 : ( $dsp == 3 ) ? " Year($column)"
391 : ( $dsp == 4 ) ? "extract(hour from $column)"
392 : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates
393 } else {
394 $colfield = $column;
396 $colorder =
397 ( $colfield =~ /dayname/ ) ? "weekday($column)"
398 : ( $colfield =~ /^month/ ) ? " month($column)"
399 : $colfield;
400 my $strsth2;
401 if($column_attribute_type) {
402 $strsth2 = "SELECT attribute FROM borrower_attributes WHERE code = '$column_attribute_type' ";
403 } else {
404 $strsth2 = "SELECT distinctrow $colfield FROM statistics ";
406 # get stats on items if ccode or location, otherwise borrowers.
407 $strsth2 .=
408 ( $colsource eq 'items' )
409 ? "LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
410 : "LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
411 $strsth2 .= " WHERE $column IS NOT NULL AND $column != '' ";
414 if ( $column =~ /datetime/ ) {
415 if ( ( $colfilter[1] ) and ( $colfilter[0] ) ) {
416 $strsth2 .= " AND $column BETWEEN ? AND ? ";
417 } elsif ( $colfilter[1] ) {
418 $strsth2 .= " AND $column <= ? ";
419 } elsif ( $colfilter[0] ) {
420 $strsth2 .= " AND $column >= ? ";
422 $strsth2 .= " AND type ='". $type ."' " if $type;
423 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
424 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
425 } elsif ($colfilter[0]) {
426 $colfilter[0] =~ s/\*/%/g;
427 $strsth2 .= " AND $column LIKE ? " ;
430 $strsth2 .= " group by $colfield order by $colorder ";
431 $debug and warn $strsth2;
432 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth2 };
433 my $sth2 = $dbh->prepare($strsth2);
434 if ( (@colfilter) and ($colfilter[0]) and ($colfilter[1]) ) {
435 $sth2->execute( $colfilter[0], $colfilter[1] . " 23:59:59" );
436 } elsif ( $colfilter[1] ) {
437 $sth2->execute( $colfilter[1] . " 23:59:59" );
438 } elsif ( $colfilter[0] ) {
439 $sth2->execute( $colfilter[0] );
440 } else {
441 $sth2->execute;
444 while ( my ($celvalue) = $sth2->fetchrow ) {
445 my %cell = ( coltitle => $celvalue ); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
446 $cell{coltitle_display} =
447 ( $column =~ /ccode/ ) ? $ccodes->{$celvalue}
448 : ( $column =~ /location/ ) ? $locations->{$celvalue}
449 : ( $column =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
450 : $celvalue; # default fallback
451 if ( $column =~ /sort1/ ) {
452 foreach (@$Bsort1) {
453 ( $celvalue eq $_->{authorised_value} ) or next;
454 $cell{coltitle_display} = $_->{lib} and last;
456 } elsif ( $column =~ /sort2/ ) {
457 foreach (@$Bsort2) {
458 ( $celvalue eq $_->{authorised_value} ) or next;
459 $cell{coltitle_display} = $_->{lib} and last;
461 } elsif ($column =~ /category/) {
462 foreach my $patron_category ( @patron_categories ) {
463 ($celvalue eq $patron_category->categorycode) or next;
464 $cell{coltitle_display} = $patron_category->description and last;
467 push @loopcol, \%cell;
470 #Initialization of cell values.....
471 my %table;
472 foreach my $row (@loopline) {
473 foreach my $col (@loopcol) {
474 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
475 table_set(\%table, $row->{rowtitle}, $col->{coltitle}, 0);
477 table_set(\%table, $row->{rowtitle}, 'totalrow', 0);
480 # preparing calculation
481 my $strcalc = "SELECT ";
482 if($line_attribute_type) {
483 $strcalc .= "TRIM(attribute_$line_attribute_type.attribute) AS line_attribute, ";
484 } else {
485 $strcalc .= "TRIM($linefield), ";
487 if($column_attribute_type) {
488 $strcalc .= "TRIM(attribute_$column_attribute_type.attribute) AS column_attribute, ";
489 } else {
490 $strcalc .= "TRIM($colfield), ";
492 $strcalc .=
493 ( $process == 1 ) ? " COUNT(*) "
494 : ( $process == 2 ) ? "(COUNT(DISTINCT borrowers.borrowernumber))"
495 : ( $process == 3 ) ? "(COUNT(DISTINCT statistics.itemnumber))"
496 : ( $process == 5 ) ? "(COUNT(DISTINCT items.biblionumber))"
497 : '';
498 if ( $process == 4 ) {
499 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
500 $rqbookcount->execute;
501 my ($bookcount) = $rqbookcount->fetchrow;
502 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount ";
504 $strcalc .= "
505 FROM statistics
506 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
508 foreach (keys %$attribute_filters) {
510 ($line_attribute_type and $line_attribute_type eq $_)
511 or $column_attribute_type and $column_attribute_type eq $_
512 or $attribute_filters->{$_}
514 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$_ ON (statistics.borrowernumber = attribute_$_.borrowernumber AND attribute_$_.code = '$_') ";
517 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
518 if ( $linefield =~ /^items\./
519 or $colfield =~ /^items\./
520 or $process == 5
521 or ( $colsource eq 'items' ) || @$filters[5] || @$filters[6] || @$filters[7] || @$filters[8] || @$filters[9] || @$filters[10] || @$filters[11] || @$filters[12] || @$filters[13] );
523 $strcalc .= "WHERE 1=1 ";
524 @$filters = map { my $f = $_; defined($f) and $f =~ s/\*/%/g; $f } @$filters;
525 $strcalc .= " AND statistics.datetime >= '" . @$filters[0] . "'" if ( @$filters[0] );
526 $strcalc .= " AND statistics.datetime <= '" . @$filters[1] . " 23:59:59'" if ( @$filters[1] );
527 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] . "'" if ( @$filters[2] );
528 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] . "'" if ( @$filters[3] );
529 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] . "'" if ( @$filters[4] );
530 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] . "'" if ( @$filters[5] );
531 $strcalc .= " AND items.location LIKE '" . @$filters[6] . "'" if ( @$filters[6] );
532 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] . "'" if ( @$filters[7] );
533 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] . "'" if ( @$filters[8] );
534 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] . "'" if ( @$filters[9] );
535 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10] . "'" if ( @$filters[10] );
536 $strcalc .= " AND items.homebranch LIKE '" . @$filters[11] . "'" if ( @$filters[11] );
537 $strcalc .= " AND items.holdingbranch LIKE '" . @$filters[12] . "'" if ( @$filters[12] );
538 $strcalc .= " AND borrowers.branchcode LIKE '" . @$filters[13] . "'" if ( @$filters[13] );
539 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel . "'" if ($daysel);
540 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel . "'" if ($monthsel);
541 $strcalc .= " AND statistics.type LIKE '" . $type . "'" if ($type);
542 foreach (keys %$attribute_filters) {
543 if($attribute_filters->{$_}) {
544 $strcalc .= " AND attribute_$_.attribute LIKE '" . $attribute_filters->{$_} . "'";
548 $strcalc .= " GROUP BY ";
549 if($line_attribute_type) {
550 $strcalc .= " line_attribute, ";
551 } else {
552 $strcalc .= " $linefield, ";
554 if($column_attribute_type) {
555 $strcalc .= " column_attribute ";
556 } else {
557 $strcalc .= " $colfield ";
560 $strcalc .= " ORDER BY ";
561 if($line_attribute_type) {
562 $strcalc .= " line_attribute, ";
563 } else {
564 $strcalc .= " $lineorder, ";
566 if($column_attribute_type) {
567 $strcalc .= " column_attribute ";
568 } else {
569 $strcalc .= " $colorder ";
572 ($debug) and warn $strcalc;
573 my $dbcalc = $dbh->prepare($strcalc);
574 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strcalc };
575 $dbcalc->execute;
576 my ( $emptycol, $emptyrow );
577 while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
578 ($debug) and warn "filling table $row / $col / $value ";
579 unless ( defined $col ) {
580 $emptycol = 1;
582 unless ( defined $row ) {
583 $emptyrow = 1;
585 table_inc(\%table, $row, $col, $value);
586 table_inc(\%table, $row, 'totalrow', $value);
587 $grantotal += $value;
589 push @loopcol, { coltitle => "NULL", coltitle_display => 'NULL' } if ($emptycol);
590 push @loopline, { rowtitle => "NULL", rowtitle_display => 'NULL' } if ($emptyrow);
592 foreach my $row (@loopline) {
593 my @loopcell;
595 #@loopcol ensures the order for columns is common with column titles
596 # and the number matches the number of columns
597 foreach my $col (@loopcol) {
598 my $value = table_get(\%table, $row->{rowtitle}, $col->{coltitle});
599 push @loopcell, { value => $value };
601 push @looprow,
602 { 'rowtitle_display' => $row->{rowtitle_display},
603 'rowtitle' => $row->{rowtitle},
604 'loopcell' => \@loopcell,
605 'totalrow' => table_get(\%table, $row->{rowtitle}, 'totalrow'),
608 for my $col (@loopcol) {
609 my $total = 0;
610 foreach my $row (@looprow) {
611 $total += table_get(\%table, $row->{rowtitle}, $col->{coltitle}) || 0;
612 $debug and warn "value added " . table_get(\%table, $row->{rowtitle}, $col->{coltitle}) . "for line " . $row->{rowtitle};
614 push @loopfooter, { 'totalcol' => $total };
617 # the header of the table
618 $globalline{loopfilter} = \@loopfilter;
620 # the core of the table
621 $globalline{looprow} = \@looprow;
622 $globalline{loopcol} = \@loopcol;
624 # # the foot (totals by borrower type)
625 $globalline{loopfooter} = \@loopfooter;
626 $globalline{total} = $grantotal;
627 $globalline{line} = $line_attribute_type ? $line_attribute_type : $line;
628 $globalline{column} = $column_attribute_type ? $column_attribute_type : $column;
629 return [ ( \%globalline ) ];
632 sub null_to_zzempty {
633 my $string = shift;
635 if (!defined($string) or $string eq '' or uc($string) eq 'NULL') {
636 return 'zzEMPTY';
639 return $string;
642 sub table_set {
643 my ($table, $row, $col, $val) = @_;
645 $row = $row // '';
646 $col = $col // '';
647 $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } = $val;
650 sub table_get {
651 my ($table, $row, $col) = @_;
653 $row = $row // '';
654 $col = $col // '';
655 return $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) };
658 sub table_inc {
659 my ($table, $row, $col, $inc) = @_;
661 $row = $row // '';
662 $col = $col // '';
663 $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } += $inc;