Merge branch 'bug_8942' into 3.12-master
[koha.git] / reports / issues_avg_stats.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use C4::Auth;
24 use CGI;
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Output;
28 use C4::Koha;
29 use C4::Circulation;
30 use C4::Reports;
31 use C4::Dates qw/format_date format_date_in_iso/;
32 use Date::Calc qw(Delta_Days);
33
34 =head1 NAME
35
36 plugin that shows a stats on borrowers
37
38 =head1 DESCRIPTION
39
40 =over 2
41
42 =cut
43
44 my $input = new CGI;
45 my $do_it=$input->param('do_it');
46 my $fullreportname = "reports/issues_avg_stats.tmpl";
47 my $line = $input->param("Line");
48 my $column = $input->param("Column");
49 my @filters = $input->param("Filter");
50 $filters[0]=format_date_in_iso($filters[0]);
51 $filters[1]=format_date_in_iso($filters[1]);
52 $filters[2]=format_date_in_iso($filters[2]);
53 $filters[3]=format_date_in_iso($filters[3]);
54 my $podsp = $input->param("IssueDisplay");
55 my $rodsp = $input->param("ReturnDisplay");
56 my $calc = $input->param("Cellvalue");
57 my $output = $input->param("output");
58 my $basename = $input->param("basename");
59 #warn "calcul : ".$calc;
60 my ($template, $borrowernumber, $cookie)
61     = get_template_and_user({template_name => $fullreportname,
62                 query => $input,
63                 type => "intranet",
64                 authnotrequired => 0,
65                 flagsrequired => {reports => '*'},
66                 debug => 1,
67                     });
68 our $sep     = $input->param("sep");
69 $sep = "\t" if ($sep eq 'tabulation');
70 $template->param(do_it => $do_it,
71     );
72 if ($do_it) {
73 # Displaying results
74     my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters);
75     if ($output eq "screen"){
76 # Printing results to screen
77         $template->param(mainloop => $results);
78         output_html_with_http_headers $input, $cookie, $template->output;
79         exit;
80     } else {
81 # Printing to a csv file
82         print $input->header(-type => 'application/vnd.sun.xml.calc',
83                                     -encoding    => 'utf-8',
84             -attachment=>"$basename.csv",
85             -filename=>"$basename.csv" );
86         my $cols = @$results[0]->{loopcol};
87         my $lines = @$results[0]->{looprow};
88 # header top-right
89         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
90 # Other header
91         foreach my $col ( @$cols ) {
92             print $col->{coltitle}.$sep;
93         }
94         print "Total\n";
95 # Table
96         foreach my $line ( @$lines ) {
97             my $x = $line->{loopcell};
98             print $line->{rowtitle}.$sep;
99             foreach my $cell (@$x) {
100                 print $cell->{value}.$sep;
101             }
102             print $line->{totalrow};
103             print "\n";
104         }
105 # footer
106         print "TOTAL";
107         $cols = @$results[0]->{loopfooter};
108         foreach my $col ( @$cols ) {
109             print $sep.$col->{totalcol};
110         }
111         print $sep.@$results[0]->{total};
112         exit;
113     }
114 # Displaying choices
115 } else {
116     my $dbh = C4::Context->dbh;
117     my @values;
118     my %labels;
119     my %select;
120     my $req;
121     $req = $dbh->prepare("select distinctrow categorycode,description from categories order by description");
122     $req->execute;
123     my @select;
124     push @select,"";
125     $select{""}="";
126     while (my ($value, $desc) =$req->fetchrow) {
127         push @select, $value;
128         $select{$value}=$desc;
129     }
130     my $CGIBorCat=CGI::scrolling_list( -name     => 'Filter',
131                 -id => 'borcat',
132                 -values   => \@select,
133                 -labels   => \%select,
134                 -size     => 1,
135                 -multiple => 0 );
136     
137     $req = $dbh->prepare( "select distinctrow itemtype,description from itemtypes order by description");
138     $req->execute;
139     undef @select;
140     undef %select;
141     push @select,"";
142     $select{""}="";
143     while (my ($value,$desc) =$req->fetchrow) {
144         push @select, $value;
145         $select{$value}=$desc;
146     }
147     my $CGIItemTypes=CGI::scrolling_list( -name     => 'Filter',
148                 -id => 'itemtypes',
149                 -values   => \@select,
150                 -labels    => \%select,
151                 -size     => 1,
152                 -multiple => 0 );
153     
154     $req = $dbh->prepare("select distinctrow sort1 from borrowers where sort1 is not null order by sort1");
155     $req->execute;
156     undef @select;
157     push @select,"";
158     my $hassort1;
159     while (my ($value) =$req->fetchrow) {
160         $hassort1 =1 if ($value);
161         push @select, $value;
162     }
163     my $branches=GetBranches();
164     my @select_branch;
165     my %select_branches;
166     push @select_branch,"";
167     $select_branches{""} = "";
168     foreach my $branch (keys %$branches) {
169         push @select_branch, $branch;
170         $select_branches{$branch} = $branches->{$branch}->{'branchname'};
171     }
172     my $CGIBranch=CGI::scrolling_list( -name     => 'Filter',
173                 -id => 'branch',
174                 -values   => \@select_branch,
175                 -labels   => \%select_branches,
176                 -size     => 1,
177                 -multiple => 0 );
178     
179     my $CGISort1=CGI::scrolling_list( -name     => 'Filter',
180                 -id => 'sort1',
181                 -values   => \@select,
182                 -size     => 1,
183                 -multiple => 0 );
184     
185     $req = $dbh->prepare("select distinctrow sort2 from borrowers where sort2 is not null order by sort2");
186     $req->execute;
187     undef @select;
188     push @select,"";
189     my $hassort2;
190     my $hglghtsort2;
191     while (my ($value) =$req->fetchrow) {
192         $hassort2 =1 if ($value);
193         $hglghtsort2= !($hassort1);
194         push @select, $value;
195     }
196     my $CGISort2=CGI::scrolling_list( -name     => 'Filter',
197                 -id => 'sort2',
198                 -values   => \@select,
199                 -size     => 1,
200                 -multiple => 0 );
201     
202     my $CGIextChoice=CGI::scrolling_list(
203                 -name     => 'MIME',
204                 -id       => 'MIME',
205                 -values   => ['CSV'], # FIXME translation
206                 -size     => 1,
207                 -multiple => 0 );
208     
209     my $CGIsepChoice=GetDelimiterChoices;
210     
211     $template->param(
212                     CGIBorCat => $CGIBorCat,
213                     CGIItemType => $CGIItemTypes,
214                     CGIBranch => $CGIBranch,
215                     hassort1=> $hassort1,
216                     hassort2=> $hassort2,
217                     HlghtSort2 => $hglghtsort2,
218                     CGISort1 => $CGISort1,
219                     CGISort2 => $CGISort2,
220                     CGIextChoice => $CGIextChoice,
221                     CGIsepChoice => $CGIsepChoice
222                     );
223 output_html_with_http_headers $input, $cookie, $template->output;
224 }
225
226
227
228
229 sub calculate {
230     my ($line, $column, $rodsp, $podsp, $process, $filters) = @_;
231     my @mainloop;
232     my @loopfooter;
233     my @loopcol;
234     my @loopline;
235     my @looprow;
236     my %globalline;
237     my $grantotal =0;
238 # extract parameters
239     my $dbh = C4::Context->dbh;
240
241 # Filters
242 # Checking filters
243 #
244     my @loopfilter;
245     for (my $i=0;$i<=6;$i++) {
246         my %cell;
247         if ( @$filters[$i] ) {
248             if (($i==1) and (@$filters[$i-1])) {
249                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
250             }
251             # format the dates filters, otherwise just fill as is
252             if ($i>=4) {
253                 $cell{filter} .= @$filters[$i];
254             } else {
255                 $cell{filter} .= format_date(@$filters[$i]);
256             }
257             $cell{crit} .="Issue From" if ($i==0);
258             $cell{crit} .="Issue To" if ($i==1);
259             $cell{crit} .="Issue Month" if ($i==2);
260             $cell{crit} .="Issue Day" if ($i==3);
261             $cell{crit} .="Return From" if ($i==4);
262             $cell{crit} .="Return To" if ($i==5);
263             $cell{crit} .="Return Month" if ($i==6);
264             $cell{crit} .="Return Day" if ($i==7);
265             $cell{crit} .="Borrower Cat" if ($i==8);
266             $cell{crit} .="Doc Type" if ($i==9);
267             $cell{crit} .="Branch" if ($i==10);
268             $cell{crit} .="Sort1" if ($i==11);
269             $cell{crit} .="Sort2" if ($i==12);
270             push @loopfilter, \%cell;
271         }
272     }
273     push @loopfilter,{crit=>"Issue Display",filter=>$rodsp} if ($rodsp);
274     push @loopfilter,{crit=>"Return Display",filter=>$podsp} if ($podsp);
275
276     
277     
278     my @linefilter;
279 #       warn "filtres ".@filters[0];
280 #       warn "filtres ".@filters[1];
281 #       warn "filtres ".@filters[2];
282 #       warn "filtres ".@filters[3];
283     $line = "old_issues.".$line if ($line=~/branchcode/) or ($line=~/timestamp/);
284     $line = "biblioitems.".$line if $line=~/itemtype/;
285     
286     $linefilter[0] = @$filters[0] if ($line =~ /timestamp/ )  ;
287     $linefilter[1] = @$filters[1] if ($line =~ /timestamp/ )  ;
288     $linefilter[2] = @$filters[2] if ($line =~ /timestamp/ )  ;
289     $linefilter[3] = @$filters[3] if ($line =~ /timestamp/ )  ;
290     $linefilter[0] = @$filters[4] if ($line =~ /returndate/ )  ;
291     $linefilter[1] = @$filters[5] if ($line =~ /returndate/ )  ;
292     $linefilter[2] = @$filters[6] if ($line =~ /returndate/ )  ;
293     $linefilter[3] = @$filters[7] if ($line =~ /returndate/ )  ;
294     $linefilter[0] = @$filters[8] if ($line =~ /category/ )  ;
295     $linefilter[0] = @$filters[9] if ($line =~ /itemtype/ )  ;
296     $linefilter[0] = @$filters[10] if ($line =~ /branch/ )  ;
297 #       $linefilter[0] = @$filters[11] if ($line =~ /sort2/ ) ;
298     $linefilter[0] = @$filters[11] if ($line =~ /sort1/ ) ;
299     $linefilter[0] = @$filters[12] if ($line =~ /sort2/ ) ;
300 #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
301
302     $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
303     $column = "biblioitems.".$column if $column=~/itemtype/;
304     my @colfilter ;
305     $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
306     $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
307     $colfilter[2] = @$filters[2] if ($column =~ /timestamp/ )  ;
308     $colfilter[3] = @$filters[3] if ($column =~ /timestamp/ )  ;
309     $colfilter[0] = @$filters[4] if ($column =~ /returndate/ )  ;
310     $colfilter[1] = @$filters[5] if ($column =~ /returndate/ )  ;
311     $colfilter[2] = @$filters[6] if ($column =~ /returndate/ )  ;
312     $colfilter[3] = @$filters[7] if ($column =~ /returndate/ )  ;
313     $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
314     $colfilter[0] = @$filters[9] if ($column =~ /itemtype/ )  ;
315     $colfilter[0] = @$filters[10] if ($column =~ /branch/ )  ;
316 #       $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
317     $colfilter[0] = @$filters[11] if ($column =~ /sort1/ ) ;
318     $colfilter[0] = @$filters[12] if ($column =~ /sort2/ ) ;
319 #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
320                                             
321 # 1st, loop rows.                             
322     my $linefield;
323     my $lineorder;                               
324     if ((($line =~/timestamp/) and ($podsp == 1)) or  (($line =~/returndate/) and ($rodsp == 1))) {
325         #Display by day
326         $linefield .="dayname($line)";  
327         $lineorder .="weekday($line)";  
328     } elsif ((($line =~/timestamp/) and ($podsp == 2)) or  (($line =~/returndate/) and ($rodsp == 2))) {
329         #Display by Month
330         $linefield .="monthname($line)";  
331         $lineorder .="month($line)";  
332     } elsif ((($line =~/timestamp/) and ($podsp == 3)) or  (($line =~/returndate/) and ($rodsp == 3))) {
333         #Display by Year
334         $linefield .="Year($line)";
335         $lineorder .= $line;  
336     } elsif (($line=~/timestamp/) or ($line=~/returndate/)){
337         $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")";
338         $lineorder .= $line;  
339     } else {
340         $linefield .= $line;
341         $lineorder .= $line;  
342     }  
343     
344     my $strsth;
345     $strsth .= "select distinctrow $linefield 
346                 FROM `old_issues` 
347                 LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
348                 LEFT JOIN items ON old_issues.itemnumber=items.itemnumber
349                 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) 
350                 LEFT JOIN issuingrules ON 
351                     (issuingrules.branchcode=old_issues.branchcode
352                     AND  issuingrules.itemtype=biblioitems.itemtype 
353                     AND  issuingrules.categorycode=borrowers.categorycode) 
354                 WHERE 1";
355     
356     if (($line=~/timestamp/) or ($line=~/returndate/)){
357         if ($linefilter[1] and ($linefilter[0])){
358             $strsth .= " AND $line BETWEEN '$linefilter[0]' AND '$linefilter[1]' " ;
359         } elsif ($linefilter[1]) {
360                 $strsth .= " AND $line < \'$linefilter[1]\' " ;
361         } elsif ($linefilter[0]) {
362             $strsth .= " AND $line > \'$linefilter[0]\' " ;
363         }
364         if ($linefilter[2]){
365             $strsth .= " AND dayname($line) = '$linefilter[2]' " ;
366         }
367         if ($linefilter[3]){
368             $strsth .= " AND monthname($line) = '$linefilter[3]' " ;
369         }
370     } elsif ($linefilter[0]) {
371         $linefilter[0] =~ s/\*/%/g;
372         $strsth .= " AND $line LIKE '$linefilter[0]' " ;
373     }
374     $strsth .=" GROUP BY $linefield";
375     $strsth .=" ORDER BY $lineorder";
376    
377     my $sth = $dbh->prepare( $strsth );
378     $sth->execute;
379
380     
381     while ( my ($celvalue) = $sth->fetchrow) {
382         my %cell;
383         if ($celvalue) {
384             $cell{rowtitle} = $celvalue;
385         } else {
386             $cell{rowtitle} = "";
387         }
388         $cell{totalrow} = 0;
389         push @loopline, \%cell;
390     }
391
392 # 2nd, loop cols.
393     my $colfield;
394     my $colorder;                               
395     if ((($column =~/timestamp/) and ($podsp == 1)) or  (($column =~/returndate/) and ($rodsp == 1))) {
396         #Display by day
397         $colfield .="dayname($column)";  
398         $colorder .="weekday($column)";
399     } elsif ((($column =~/timestamp/) and ($podsp == 2)) or  (($column =~/returndate/) and ($rodsp == 2))) {
400         #Display by Month
401         $colfield .="monthname($column)";  
402         $colorder .="month($column)";  
403     } elsif ((($column =~/timestamp/) and ($podsp == 3)) or  (($column =~/returndate/) and ($rodsp == 3))) {
404         #Display by Year
405         $colfield .="Year($column)";
406         $colorder .= $column;
407     } elsif (($column=~/timestamp/) or ($column=~/returndate/)){
408         $colfield .= 'date_format( '."'".$column."'". ', "%Y-%m-%d")';
409         $colorder .= $column;
410     } else {
411         $colfield .= $column;
412         $colorder .= $column;
413     }  
414     
415     my $strsth2;
416     $strsth2 .= "SELECT distinctrow $colfield 
417                   FROM `old_issues`
418                   LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber
419                   LEFT JOIN items  ON items.itemnumber=old_issues.itemnumber  
420                   LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) 
421                   LEFT JOIN issuingrules ON 
422                     (issuingrules.branchcode=old_issues.branchcode 
423                     AND  issuingrules.itemtype=biblioitems.itemtype 
424                     AND  issuingrules.categorycode=borrowers.categorycode) 
425                   WHERE 1";
426     
427     if (($column=~/timestamp/) or ($column=~/returndate/)){
428         if ($colfilter[1] and ($colfilter[0])){
429             $strsth2 .= " AND $column BETWEEN '$colfilter[0]' AND '$colfilter[1]' " ;
430         } elsif ($colfilter[1]) {
431                 $strsth2 .= " AND $column < '$colfilter[1]' " ;
432         } elsif ($colfilter[0]) {
433             $strsth2 .= " AND $column > '$colfilter[0]' " ;
434         }
435         if ($colfilter[2]){
436             $strsth2 .= " AND dayname($column) = '$colfilter[2]' " ;
437         }
438         if ($colfilter[3]){
439             $strsth2 .= " AND monthname($column) = '$colfilter[3]' " ;
440         }
441     } elsif ($colfilter[0]) {
442         $colfilter[0] =~ s/\*/%/g;
443         $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
444     }
445     $strsth2 .=" GROUP BY $colfield";
446     $strsth2 .=" ORDER BY $colorder";
447     
448     my $sth2 = $dbh->prepare( $strsth2 );
449     if (( @colfilter ) and ($colfilter[1])){
450         $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
451     } elsif ($colfilter[0]) {
452         $sth2->execute($colfilter[0]);
453     } else {
454         $sth2->execute;
455     }
456     
457
458     while (my ($celvalue) = $sth2->fetchrow) {
459         my %cell;
460         my %ft;
461 #               warn "coltitle :".$celvalue;
462         $cell{coltitle} = $celvalue;
463         $ft{totalcol} = 0;
464         push @loopcol, \%cell;
465     }
466 #       warn "fin des titres colonnes";
467
468     my $i=0;
469     my @totalcol;
470     my $hilighted=-1;
471     
472     #Initialization of cell values.....
473     my %table;
474     my %wgttable;
475     my %cnttable;
476     
477 #       warn "init table";
478     foreach my $row ( @loopline ) {
479         foreach my $col ( @loopcol ) {
480 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
481             $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
482         }
483         $table{$row->{rowtitle}}->{totalrow}=0;
484     }
485
486 # preparing calculation
487     my $strcalc ;
488     
489 # Processing average loanperiods
490     $strcalc .= "SELECT $linefield, $colfield, ";
491     $strcalc .= " issuedate, returndate, old_issues.timestamp, COUNT(*), date_due, old_issues.renewals, issuelength FROM `old_issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) LEFT JOIN issuingrules ON (issuingrules.branchcode=branchcode AND  issuingrules.itemtype=biblioitems.itemtype AND  issuingrules.categorycode=categorycode) WHERE old_issues.itemnumber=items.itemnumber AND old_issues.borrowernumber=borrowers.borrowernumber";
492
493     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
494     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
495     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
496     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
497     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
498     $strcalc .= " AND old_issues.returndate > '" . @$filters[4] ."'" if ( @$filters[4] );
499     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
500     $strcalc .= " AND old_issues.returndate < '" . @$filters[5] ."'" if ( @$filters[5] );
501     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
502     $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] ."'" if ( @$filters[8] );
503     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
504     $strcalc .= " AND biblioitems.itemtype like '" . @$filters[9] ."'" if ( @$filters[9] );
505     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
506     $strcalc .= " AND old_issues.branchcode like '" . @$filters[10] ."'" if ( @$filters[10] );
507     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
508     $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] ."'" if ( @$filters[11] );
509     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
510     $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] ."'" if ( @$filters[12] );
511     $strcalc .= " AND dayname(timestamp) like '" . @$filters[2]."'" if (@$filters[2]);
512     $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] ."'" if ( @$filters[3] );
513     $strcalc .= " AND dayname(returndate) like '" . @$filters[5]."'" if (@$filters[5]);
514     $strcalc .= " AND monthname(returndate) like '" . @$filters[6] ."'" if ( @$filters[6] );
515     
516     $strcalc .= " group by  $linefield, $colfield, issuedate, returndate order by $linefield, $colfield";
517     
518     my $dbcalc = $dbh->prepare($strcalc);
519     $dbcalc->execute;
520 #       warn "filling table";
521     my $issues_count=0;
522     my $previous_row; 
523     my $previous_col;
524     my $loanlength; 
525     my $err;
526     my $emptycol;
527     my $weightrow;
528     
529     while (my  @data = $dbcalc->fetchrow) {
530         my ($row, $col, $issuedate, $returndate, $weight)=@data;
531 #               warn "filling table $row / $col / $issuedate / $returndate /$weight";
532         $emptycol=1 if (!defined($col));
533         $col = "zzEMPTY" if (!defined($col));
534         $row = "zzEMPTY" if (!defined($row));
535         # fill returndate to avoid an error with date calc (needed for all non returned issues)
536         $returndate= join '-',Date::Calc::Today if $returndate eq '0000-00-00';
537     #  DateCalc returns => 0:0:WK:DD:HH:MM:SS   the weeks, days, hours, minutes,
538     #  and seconds between the two
539         $loanlength = Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ;
540     #           warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight;
541     #           warn "513 row :".$row." column :".$col;
542         $table{$row}->{$col}+=$weight*$loanlength;
543     #           $table{$row}->{totalrow}+=$weight*$loanlength;
544         $cnttable{$row}->{$col}= 1;
545         $wgttable{$row}->{$col}+=$weight;
546     }
547     
548     push @loopcol,{coltitle => "NULL"} if ($emptycol);
549     
550     foreach my $row ( sort keys %table ) {
551         my @loopcell;
552     #@loopcol ensures the order for columns is common with column titles
553     # and the number matches the number of columns
554         my $colcount=0;
555         foreach my $col ( @loopcol ) {
556             my $value;
557             if ($table{$row}->{
558                     (        ( $col->{coltitle} eq 'NULL' )
559                           or ( $col->{coltitle} eq q{} )
560                       ) ? 'zzEMPTY' : $col->{coltitle}
561                 }
562               ) {
563                 $value = $table{$row}->{
564                     (        ( $col->{coltitle} eq 'NULL' )
565                           or ( $col->{coltitle} eq q{} )
566                       ) ? 'zzEMPTY' : $col->{coltitle}
567                   } / $wgttable{$row}->{
568                     (        ( $col->{coltitle} eq 'NULL' )
569                           or ( $col->{coltitle} eq q{} )
570                       ) ? 'zzEMPTY' : $col->{coltitle}
571                   };
572             }
573             $table{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}} = $value;
574             $table{$row}->{totalrow}+=$value;
575             #warn "row : $row col:$col  $cnttable{$row}->{(($col->{coltitle} eq \"NULL\")or ($col->{coltitle} eq \"\"))?\"zzEMPTY\":$col->{coltitle}}";
576             $colcount+=$cnttable{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}};
577             push @loopcell, {value => ($value)?sprintf("%.2f",$value):0  } ;
578         }
579         #warn "row : $row colcount:$colcount";
580         my $total;
581         if ( $colcount > 0 ) {
582             $total = $table{$row}->{totalrow} / $colcount;
583         }
584         push @looprow,
585           { 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
586             'loopcell' => \@loopcell,
587             'hilighted' => ( $hilighted > 0 ),
588             'totalrow'  => ($total) ? sprintf( "%.2f", $total ) : 0
589           };
590         $hilighted = -$hilighted;
591     }
592 #       
593 # #     warn "footer processing";
594     foreach my $col ( @loopcol ) {
595         my $total=0;
596         my $nbrow=0;
597         foreach my $row ( @looprow ) {
598             $total += $cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}}*$table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
599             $nbrow +=$cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};;
600 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
601         }
602 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
603         $total = $total/$nbrow if ($nbrow);
604         push @loopfooter, {'totalcol' => ($total)?sprintf("%.2f",$total):0};
605     
606     }
607             
608
609     # the header of the table
610     $globalline{loopfilter}=\@loopfilter;
611     # the core of the table
612     $globalline{looprow} = \@looprow;
613     $globalline{loopcol} = \@loopcol;
614 #       # the foot (totals by borrower type)
615     $globalline{loopfooter} = \@loopfooter;
616     $globalline{total}= $grantotal;
617     $globalline{line} = $line;
618     $globalline{column} = $column;
619     push @mainloop,\%globalline;
620     return \@mainloop;
621 }
622
623 1;