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