Bug 24591: Add developer script to preview a letter
[koha.git] / reports / issues_stats.pl
blobfac2b5883e15c8f24121fce8cf09f61e3532ebdd
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 authnotrequired => 0,
82 flagsrequired => {reports => '*'},
83 debug => 0,
84 });
85 our $sep = $input->param("sep") // ';';
86 $sep = "\t" if ($sep eq 'tabulation');
87 $template->param(do_it => $do_it,
90 our $itemtypes = Koha::ItemTypes->search_with_localization->unblessed;
92 our @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
94 our $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
95 our $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
97 our $Bsort1 = GetAuthorisedValues("Bsort1");
98 our $Bsort2 = GetAuthorisedValues("Bsort2");
99 my ($hassort1,$hassort2);
100 $hassort1=1 if $Bsort1;
101 $hassort2=1 if $Bsort2;
103 if ($do_it) {
104 # Displaying results
105 my $results = calculate( $line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters, $attribute_filters);
106 if ( $output eq "screen" ) {
108 # Printing results to screen
109 $template->param( mainloop => $results );
110 output_html_with_http_headers $input, $cookie, $template->output;
111 } else {
113 # Printing to a csv file
114 print $input->header(
115 -type => 'application/vnd.sun.xml.calc',
116 -encoding => 'utf-8',
117 -attachment => "$basename.csv",
118 -filename => "$basename.csv"
120 my $cols = @$results[0]->{loopcol};
121 my $lines = @$results[0]->{looprow};
123 # header top-right
124 print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
126 # Other header
127 foreach my $col (@$cols) {
128 print $col->{coltitle} . $sep;
130 print "Total\n";
132 # Table
133 foreach my $line (@$lines) {
134 my $x = $line->{loopcell};
135 print $line->{rowtitle} . $sep;
136 print map { $_->{value} . $sep } @$x;
137 print $line->{totalrow}, "\n";
140 # footer
141 print "TOTAL";
142 $cols = @$results[0]->{loopfooter};
143 print map {$sep.$_->{totalcol}} @$cols;
144 print $sep.@$results[0]->{total};
146 exit;
150 my $dbh = C4::Context->dbh;
152 # location list
153 my @locations;
154 foreach (sort keys %$locations) {
155 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
158 my @ccodes;
159 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
160 push @ccodes, { code => $_, description => $ccodes->{$_} };
163 my $CGIextChoice = ( 'CSV' ); # FIXME translation
164 my $CGIsepChoice=GetDelimiterChoices;
166 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
167 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
168 my %attribute_types_by_class;
169 while ( my ( $attribute_type ) = $attribute_types->next ) {
170 $attribute_type = $attribute_type->unblessed;
171 if ($attribute_type->{authorised_value_category}) {
172 my $authorised_values = C4::Koha::GetAuthorisedValues(
173 $attribute_type->{authorised_value_category});
175 foreach my $authorised_value (@$authorised_values) {
176 push @{ $attribute_type->{authorised_values} }, $authorised_value;
179 push @{ $attribute_types_by_class{$attribute_type->{class}} }, $attribute_type;
182 $template->param(
183 categoryloop => \@patron_categories,
184 itemtypes => $itemtypes,
185 locationloop => \@locations,
186 ccodeloop => \@ccodes,
187 hassort1 => $hassort1,
188 hassort2 => $hassort2,
189 Bsort1 => $Bsort1,
190 Bsort2 => $Bsort2,
191 CGIextChoice => $CGIextChoice,
192 CGIsepChoice => $CGIsepChoice,
193 attribute_types_by_class => \%attribute_types_by_class,
195 output_html_with_http_headers $input, $cookie, $template->output;
197 sub calculate {
198 my ( $line, $column, $dsp, $type, $daysel, $monthsel, $process, $filters, $attribute_filters ) = @_;
199 my @loopfooter;
200 my @loopcol;
201 my @loopline;
202 my @looprow;
203 my %globalline;
204 my $grantotal = 0;
206 # extract parameters
207 my $dbh = C4::Context->dbh;
209 my ($line_attribute_type, $column_attribute_type);
210 if($line =~ /^borrower_attributes\.(.*)/) {
211 $line_attribute_type = $1;
212 $line = "borrower_attributes.attribute";
214 if($column =~ /^borrower_attributes\.(.*)/) {
215 $column_attribute_type = $1;
216 $column = "borrower_attributes.attribute";
219 # Filters
220 # Checking filters
222 my @loopfilter;
223 for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
224 my %cell;
225 ( @$filters[$i] ) or next;
226 if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) {
227 $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
229 # format the dates filters, otherwise just fill as is
230 if ($i>=2) {
231 $cell{filter} = @$filters[$i];
232 } else {
233 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
234 if ( @$filters[$i] );
236 $cell{crit} = $i;
238 push @loopfilter, \%cell;
240 foreach (keys %$attribute_filters) {
241 next unless $attribute_filters->{$_};
242 push @loopfilter, { crit => "$_ =", filter => $attribute_filters->{$_} };
244 push @loopfilter, { crit => "Event", filter => $type };
245 push @loopfilter, { crit => "Display by", filter => $dsp } if ($dsp);
246 push @loopfilter, { crit => "Select Day", filter => $daysel } if ($daysel);
247 push @loopfilter, { crit => "Select Month", filter => $monthsel } if ($monthsel);
249 my @linefilter;
250 $debug and warn "filtres " . join "|", @$filters;
251 my ( $colsource, $linesource ) = ('', '');
252 $linefilter[1] = @$filters[1] if ( $line =~ /datetime/ );
253 $linefilter[0] =
254 ( $line =~ /datetime/ ) ? @$filters[0]
255 : ( $line =~ /category/ ) ? @$filters[2]
256 : ( $line =~ /itemtype/ ) ? @$filters[3]
257 : ( $line =~ /^branch/ ) ? @$filters[4]
258 : ( $line =~ /ccode/ ) ? @$filters[5]
259 : ( $line =~ /location/ ) ? @$filters[6]
260 : ( $line =~ /sort1/ ) ? @$filters[9]
261 : ( $line =~ /sort2/ ) ? @$filters[10]
262 : ( $line =~ /homebranch/) ? @$filters[11]
263 : ( $line =~ /holdingbranch/) ? @$filters[12]
264 : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13]
265 : ( $line_attribute_type ) ? $attribute_filters->{$line_attribute_type}
266 : undef;
268 if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
269 $linesource = 'items';
272 my @colfilter;
273 $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
274 $colfilter[0] =
275 ( $column =~ /datetime/ ) ? @$filters[0]
276 : ( $column =~ /category/ ) ? @$filters[2]
277 : ( $column =~ /itemtype/ ) ? @$filters[3]
278 : ( $column =~ /^branch/ ) ? @$filters[4]
279 : ( $column =~ /ccode/ ) ? @$filters[5]
280 : ( $column =~ /location/ ) ? @$filters[6]
281 : ( $column =~ /sort1/ ) ? @$filters[9]
282 : ( $column =~ /sort1/ ) ? @$filters[10]
283 : ( $column =~ /homebranch/) ? @$filters[11]
284 : ( $column =~ /holdingbranch/) ? @$filters[12]
285 : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13]
286 : ( $column_attribute_type ) ? $attribute_filters->{$column_attribute_type}
287 : undef;
289 if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
290 $colsource = 'items';
293 # 1st, loop rows.
294 my $linefield;
295 if ( $line =~ /datetime/ ) {
297 # by Day, Month, Year or Hour (1,2,3,4 respectively)
298 $linefield =
299 ( $dsp == 1 ) ? " dayname($line)"
300 : ( $dsp == 2 ) ? "monthname($line)"
301 : ( $dsp == 3 ) ? " Year($line)"
302 : ( $dsp == 4 ) ? "extract(hour from $line)"
303 : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates
304 } else {
305 $linefield = $line;
307 my $lineorder =
308 ( $linefield =~ /dayname/ ) ? "weekday($line)"
309 : ( $linefield =~ /^month/ ) ? " month($line)"
310 : $linefield;
312 my $strsth;
313 if($line_attribute_type) {
314 $strsth = "SELECT attribute FROM borrower_attributes WHERE code = '$line_attribute_type' ";
315 } else {
316 $strsth = "SELECT distinctrow $linefield FROM statistics ";
318 # get stats on items if ccode or location, otherwise borrowers.
319 $strsth .=
320 ( $linesource eq 'items' )
321 ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
322 : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
323 $strsth .= " WHERE $line is not null AND $line != '' ";
326 if ( $line =~ /datetime/ ) {
327 if ( $linefilter[1] and ( $linefilter[0] ) ) {
328 $strsth .= " AND $line between ? AND ? ";
329 } elsif ( $linefilter[1] ) {
330 $strsth .= " AND $line <= ? ";
331 } elsif ( $linefilter[0] ) {
332 $strsth .= " AND $line >= ? ";
334 $strsth .= " AND type ='" . $type . "' " if $type;
335 $strsth .= " AND dayname(datetime) ='" . $daysel . "' " if $daysel;
336 $strsth .= " AND monthname(datetime) ='" . $monthsel . "' " if $monthsel;
337 } elsif ( $linefilter[0] ) {
338 $linefilter[0] =~ s/\*/%/g;
339 $strsth .= " AND $line LIKE ? ";
341 $strsth .= " group by $linefield order by $lineorder ";
342 $debug and warn $strsth;
343 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth };
344 my $sth = $dbh->prepare($strsth);
345 if ( (@linefilter) and ($linefilter[0]) and ($linefilter[1]) ) {
346 $sth->execute( $linefilter[0], $linefilter[1] . " 23:59:59" );
347 } elsif ( $linefilter[1] ) {
348 $sth->execute( $linefilter[1] . " 23:59:59" );
349 } elsif ( $linefilter[0] ) {
350 $sth->execute( $linefilter[0] );
351 } else {
352 $sth->execute;
355 my $itemtypes_map = { map { $_->{itemtype} => $_ } @{ $itemtypes } };
356 while ( my ($celvalue) = $sth->fetchrow ) {
357 my %cell = ( rowtitle => $celvalue, totalrow => 0 ); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display
358 $cell{rowtitle_display} =
359 ( $line =~ /ccode/ ) ? $ccodes->{$celvalue}
360 : ( $line =~ /location/ ) ? $locations->{$celvalue}
361 : ( $line =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
362 : $celvalue; # default fallback
363 if ( $line =~ /sort1/ ) {
364 foreach (@$Bsort1) {
365 ( $celvalue eq $_->{authorised_value} ) or next;
366 $cell{rowtitle_display} = $_->{lib} and last;
368 } elsif ( $line =~ /sort2/ ) {
369 foreach (@$Bsort2) {
370 ( $celvalue eq $_->{authorised_value} ) or next;
371 $cell{rowtitle_display} = $_->{lib} and last;
373 } elsif ($line =~ /category/) {
374 foreach my $patron_category ( @patron_categories ) {
375 ($celvalue eq $patron_category->categorycode) or next;
376 $cell{rowtitle_display} = $patron_category->description and last;
379 push @loopline, \%cell;
382 # 2nd, loop cols.
383 my $colfield;
384 my $colorder;
385 if ( $column =~ /datetime/ ) {
387 #Display by Day, Month or Year (1,2,3 respectively)
388 $colfield =
389 ( $dsp == 1 ) ? " dayname($column)"
390 : ( $dsp == 2 ) ? "monthname($column)"
391 : ( $dsp == 3 ) ? " Year($column)"
392 : ( $dsp == 4 ) ? "extract(hour from $column)"
393 : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates
394 } else {
395 $colfield = $column;
397 $colorder =
398 ( $colfield =~ /dayname/ ) ? "weekday($column)"
399 : ( $colfield =~ /^month/ ) ? " month($column)"
400 : $colfield;
401 my $strsth2;
402 if($column_attribute_type) {
403 $strsth2 = "SELECT attribute FROM borrower_attributes WHERE code = '$column_attribute_type' ";
404 } else {
405 $strsth2 = "SELECT distinctrow $colfield FROM statistics ";
407 # get stats on items if ccode or location, otherwise borrowers.
408 $strsth2 .=
409 ( $colsource eq 'items' )
410 ? "LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) "
411 : "LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) ";
412 $strsth2 .= " WHERE $column IS NOT NULL AND $column != '' ";
415 if ( $column =~ /datetime/ ) {
416 if ( ( $colfilter[1] ) and ( $colfilter[0] ) ) {
417 $strsth2 .= " AND $column BETWEEN ? AND ? ";
418 } elsif ( $colfilter[1] ) {
419 $strsth2 .= " AND $column <= ? ";
420 } elsif ( $colfilter[0] ) {
421 $strsth2 .= " AND $column >= ? ";
423 $strsth2 .= " AND type ='". $type ."' " if $type;
424 $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel;
425 $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel;
426 } elsif ($colfilter[0]) {
427 $colfilter[0] =~ s/\*/%/g;
428 $strsth2 .= " AND $column LIKE ? " ;
431 $strsth2 .= " group by $colfield order by $colorder ";
432 $debug and warn $strsth2;
433 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth2 };
434 my $sth2 = $dbh->prepare($strsth2);
435 if ( (@colfilter) and ($colfilter[0]) and ($colfilter[1]) ) {
436 $sth2->execute( $colfilter[0], $colfilter[1] . " 23:59:59" );
437 } elsif ( $colfilter[1] ) {
438 $sth2->execute( $colfilter[1] . " 23:59:59" );
439 } elsif ( $colfilter[0] ) {
440 $sth2->execute( $colfilter[0] );
441 } else {
442 $sth2->execute;
445 while ( my ($celvalue) = $sth2->fetchrow ) {
446 my %cell = ( coltitle => $celvalue ); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display
447 $cell{coltitle_display} =
448 ( $column =~ /ccode/ ) ? $ccodes->{$celvalue}
449 : ( $column =~ /location/ ) ? $locations->{$celvalue}
450 : ( $column =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description}
451 : $celvalue; # default fallback
452 if ( $column =~ /sort1/ ) {
453 foreach (@$Bsort1) {
454 ( $celvalue eq $_->{authorised_value} ) or next;
455 $cell{coltitle_display} = $_->{lib} and last;
457 } elsif ( $column =~ /sort2/ ) {
458 foreach (@$Bsort2) {
459 ( $celvalue eq $_->{authorised_value} ) or next;
460 $cell{coltitle_display} = $_->{lib} and last;
462 } elsif ($column =~ /category/) {
463 foreach my $patron_category ( @patron_categories ) {
464 ($celvalue eq $patron_category->categorycode) or next;
465 $cell{coltitle_display} = $patron_category->description and last;
468 push @loopcol, \%cell;
471 #Initialization of cell values.....
472 my %table;
473 foreach my $row (@loopline) {
474 foreach my $col (@loopcol) {
475 $debug and warn " init table : $row->{rowtitle} ( $row->{rowtitle_display} ) / $col->{coltitle} ( $col->{coltitle_display} ) ";
476 table_set(\%table, $row->{rowtitle}, $col->{coltitle}, 0);
478 table_set(\%table, $row->{rowtitle}, 'totalrow', 0);
481 # preparing calculation
482 my $strcalc = "SELECT ";
483 if($line_attribute_type) {
484 $strcalc .= "TRIM(attribute_$line_attribute_type.attribute) AS line_attribute, ";
485 } else {
486 $strcalc .= "TRIM($linefield), ";
488 if($column_attribute_type) {
489 $strcalc .= "TRIM(attribute_$column_attribute_type.attribute) AS column_attribute, ";
490 } else {
491 $strcalc .= "TRIM($colfield), ";
493 $strcalc .=
494 ( $process == 1 ) ? " COUNT(*) "
495 : ( $process == 2 ) ? "(COUNT(DISTINCT borrowers.borrowernumber))"
496 : ( $process == 3 ) ? "(COUNT(DISTINCT statistics.itemnumber))"
497 : ( $process == 5 ) ? "(COUNT(DISTINCT items.biblionumber))"
498 : '';
499 if ( $process == 4 ) {
500 my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
501 $rqbookcount->execute;
502 my ($bookcount) = $rqbookcount->fetchrow;
503 $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount ";
505 $strcalc .= "
506 FROM statistics
507 LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber
509 foreach (keys %$attribute_filters) {
511 ($line_attribute_type and $line_attribute_type eq $_)
512 or $column_attribute_type and $column_attribute_type eq $_
513 or $attribute_filters->{$_}
515 $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$_ ON (statistics.borrowernumber = attribute_$_.borrowernumber AND attribute_$_.code = '$_') ";
518 $strcalc .= "LEFT JOIN items ON statistics.itemnumber=items.itemnumber "
519 if ( $linefield =~ /^items\./
520 or $colfield =~ /^items\./
521 or $process == 5
522 or ( $colsource eq 'items' ) || @$filters[5] || @$filters[6] || @$filters[7] || @$filters[8] || @$filters[9] || @$filters[10] || @$filters[11] || @$filters[12] || @$filters[13] );
524 $strcalc .= "WHERE 1=1 ";
525 @$filters = map { my $f = $_; defined($f) and $f =~ s/\*/%/g; $f } @$filters;
526 $strcalc .= " AND statistics.datetime >= '" . @$filters[0] . "'" if ( @$filters[0] );
527 $strcalc .= " AND statistics.datetime <= '" . @$filters[1] . " 23:59:59'" if ( @$filters[1] );
528 $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] . "'" if ( @$filters[2] );
529 $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] . "'" if ( @$filters[3] );
530 $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] . "'" if ( @$filters[4] );
531 $strcalc .= " AND items.ccode LIKE '" . @$filters[5] . "'" if ( @$filters[5] );
532 $strcalc .= " AND items.location LIKE '" . @$filters[6] . "'" if ( @$filters[6] );
533 $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] . "'" if ( @$filters[7] );
534 $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] . "'" if ( @$filters[8] );
535 $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] . "'" if ( @$filters[9] );
536 $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10] . "'" if ( @$filters[10] );
537 $strcalc .= " AND items.homebranch LIKE '" . @$filters[11] . "'" if ( @$filters[11] );
538 $strcalc .= " AND items.holdingbranch LIKE '" . @$filters[12] . "'" if ( @$filters[12] );
539 $strcalc .= " AND borrowers.branchcode LIKE '" . @$filters[13] . "'" if ( @$filters[13] );
540 $strcalc .= " AND dayname(datetime) LIKE '" . $daysel . "'" if ($daysel);
541 $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel . "'" if ($monthsel);
542 $strcalc .= " AND statistics.type LIKE '" . $type . "'" if ($type);
543 foreach (keys %$attribute_filters) {
544 if($attribute_filters->{$_}) {
545 $strcalc .= " AND attribute_$_.attribute LIKE '" . $attribute_filters->{$_} . "'";
549 $strcalc .= " GROUP BY ";
550 if($line_attribute_type) {
551 $strcalc .= " line_attribute, ";
552 } else {
553 $strcalc .= " $linefield, ";
555 if($column_attribute_type) {
556 $strcalc .= " column_attribute ";
557 } else {
558 $strcalc .= " $colfield ";
561 $strcalc .= " ORDER BY ";
562 if($line_attribute_type) {
563 $strcalc .= " line_attribute, ";
564 } else {
565 $strcalc .= " $lineorder, ";
567 if($column_attribute_type) {
568 $strcalc .= " column_attribute ";
569 } else {
570 $strcalc .= " $colorder ";
573 ($debug) and warn $strcalc;
574 my $dbcalc = $dbh->prepare($strcalc);
575 push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strcalc };
576 $dbcalc->execute;
577 my ( $emptycol, $emptyrow );
578 while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
579 ($debug) and warn "filling table $row / $col / $value ";
580 unless ( defined $col ) {
581 $emptycol = 1;
583 unless ( defined $row ) {
584 $emptyrow = 1;
586 table_inc(\%table, $row, $col, $value);
587 table_inc(\%table, $row, 'totalrow', $value);
588 $grantotal += $value;
590 push @loopcol, { coltitle => "NULL", coltitle_display => 'NULL' } if ($emptycol);
591 push @loopline, { rowtitle => "NULL", rowtitle_display => 'NULL' } if ($emptyrow);
593 foreach my $row (@loopline) {
594 my @loopcell;
596 #@loopcol ensures the order for columns is common with column titles
597 # and the number matches the number of columns
598 foreach my $col (@loopcol) {
599 my $value = table_get(\%table, $row->{rowtitle}, $col->{coltitle});
600 push @loopcell, { value => $value };
602 push @looprow,
603 { 'rowtitle_display' => $row->{rowtitle_display},
604 'rowtitle' => $row->{rowtitle},
605 'loopcell' => \@loopcell,
606 'totalrow' => table_get(\%table, $row->{rowtitle}, 'totalrow'),
609 for my $col (@loopcol) {
610 my $total = 0;
611 foreach my $row (@looprow) {
612 $total += table_get(\%table, $row->{rowtitle}, $col->{coltitle}) || 0;
613 $debug and warn "value added " . table_get(\%table, $row->{rowtitle}, $col->{coltitle}) . "for line " . $row->{rowtitle};
615 push @loopfooter, { 'totalcol' => $total };
618 # the header of the table
619 $globalline{loopfilter} = \@loopfilter;
621 # the core of the table
622 $globalline{looprow} = \@looprow;
623 $globalline{loopcol} = \@loopcol;
625 # # the foot (totals by borrower type)
626 $globalline{loopfooter} = \@loopfooter;
627 $globalline{total} = $grantotal;
628 $globalline{line} = $line_attribute_type ? $line_attribute_type : $line;
629 $globalline{column} = $column_attribute_type ? $column_attribute_type : $column;
630 return [ ( \%globalline ) ];
633 sub null_to_zzempty {
634 my $string = shift;
636 if (!defined($string) or $string eq '' or uc($string) eq 'NULL') {
637 return 'zzEMPTY';
640 return $string;
643 sub table_set {
644 my ($table, $row, $col, $val) = @_;
646 $row = $row // '';
647 $col = $col // '';
648 $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } = $val;
651 sub table_get {
652 my ($table, $row, $col) = @_;
654 $row = $row // '';
655 $col = $col // '';
656 return $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) };
659 sub table_inc {
660 my ($table, $row, $col, $inc) = @_;
662 $row = $row // '';
663 $col = $col // '';
664 $table->{ null_to_zzempty($row) }->{ null_to_zzempty($col) } += $inc;