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