Patch from Joe Atzberger to remove $Id$ and $Log$ from scripts
[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 with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 use strict;
22 use C4::Auth;
23 use CGI;
24 use C4::Context;
25 use C4::Branch; # GetBranches
26 use C4::Output;
27 use C4::Koha;
28 use C4::Circulation;
29 use C4::Date;
30 use Date::Calc qw(Delta_Days);
31
32 =head1 NAME
33
34 plugin that shows a stats on borrowers
35
36 =head1 DESCRIPTION
37
38 =over 2
39
40 =cut
41
42 my $input = new CGI;
43 my $do_it=$input->param('do_it');
44 my $fullreportname = "reports/issues_avg_stats.tmpl";
45 my $line = $input->param("Line");
46 my $column = $input->param("Column");
47 my @filters = $input->param("Filter");
48 $filters[0]=format_date_in_iso($filters[0]);
49 $filters[1]=format_date_in_iso($filters[1]);
50 $filters[2]=format_date_in_iso($filters[2]);
51 $filters[3]=format_date_in_iso($filters[3]);
52 my $podsp = $input->param("IssueDisplay");
53 my $rodsp = $input->param("ReturnDisplay");
54 my $calc = $input->param("Cellvalue");
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my $mime = $input->param("MIME");
58 my $del = $input->param("sep");
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 => 1},
66                 debug => 1,
67                     });
68 $template->param(do_it => $do_it,
69         DHTMLcalendar_dateformat => get_date_format_string_for_DHTMLcalendar(),
70     );
71 if ($do_it) {
72 # Displaying results
73     my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters);
74     if ($output eq "screen"){
75 # Printing results to screen
76         $template->param(mainloop => $results);
77         output_html_with_http_headers $input, $cookie, $template->output;
78         exit(1);
79     } else {
80 # Printing to a csv file
81         print $input->header(-type => 'application/vnd.sun.xml.calc',
82                                     -encoding    => 'utf-8',
83             -attachment=>"$basename.csv",
84             -filename=>"$basename.csv" );
85         my $cols = @$results[0]->{loopcol};
86         my $lines = @$results[0]->{looprow};
87         my $sep;
88         $sep =C4::Context->preference("delimiter");
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 @mime = ( C4::Context->preference("MIME") );
204 #       foreach my $mime (@mime){
205 #               warn "".$mime;
206 #       }
207     
208     my $CGIextChoice=CGI::scrolling_list(
209                 -name     => 'MIME',
210                 -id       => 'MIME',
211                 -values   => \@mime,
212                 -size     => 1,
213                 -multiple => 0 );
214     
215     my @dels = ( C4::Context->preference("delimiter") );
216     my $CGIsepChoice=CGI::scrolling_list(
217                 -name     => 'sep',
218                 -id       => 'sep',
219                 -values   => \@dels,
220                 -size     => 1,
221                 -multiple => 0 );
222     
223     $template->param(
224                     CGIBorCat => $CGIBorCat,
225                     CGIItemType => $CGIItemTypes,
226                     CGIBranch => $CGIBranch,
227                     hassort1=> $hassort1,
228                     hassort2=> $hassort2,
229                     HlghtSort2 => $hglghtsort2,
230                     CGISort1 => $CGISort1,
231                     CGISort2 => $CGISort2,
232                     CGIextChoice => $CGIextChoice,
233                     CGIsepChoice => $CGIsepChoice
234                     );
235 output_html_with_http_headers $input, $cookie, $template->output;
236 }
237
238
239
240
241 sub calculate {
242     my ($line, $column, $rodsp, $podsp, $process, $filters) = @_;
243     my @mainloop;
244     my @loopfooter;
245     my @loopcol;
246     my @loopline;
247     my @looprow;
248     my %globalline;
249     my $grantotal =0;
250 # extract parameters
251     my $dbh = C4::Context->dbh;
252
253 # Filters
254 # Checking filters
255 #
256     my @loopfilter;
257     for (my $i=0;$i<=6;$i++) {
258         my %cell;
259         if ( @$filters[$i] ) {
260             if (($i==1) and (@$filters[$i-1])) {
261                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
262             }
263             # format the dates filters, otherwise just fill as is
264             if ($i>=4) {
265                 $cell{filter} .= @$filters[$i];
266             } else {
267                 $cell{filter} .= format_date(@$filters[$i]);
268             }
269             $cell{crit} .="Issue From" if ($i==0);
270             $cell{crit} .="Issue To" if ($i==1);
271             $cell{crit} .="Issue Month" if ($i==2);
272             $cell{crit} .="Issue Day" if ($i==3);
273             $cell{crit} .="Return From" if ($i==4);
274             $cell{crit} .="Return To" if ($i==5);
275             $cell{crit} .="Return Month" if ($i==6);
276             $cell{crit} .="Return Day" if ($i==7);
277             $cell{crit} .="Borrower Cat" if ($i==8);
278             $cell{crit} .="Doc Type" if ($i==9);
279             $cell{crit} .="Branch" if ($i==10);
280             $cell{crit} .="Sort1" if ($i==11);
281             $cell{crit} .="Sort2" if ($i==12);
282             push @loopfilter, \%cell;
283         }
284     }
285     push @loopfilter,{crit=>"Issue Display",filter=>$rodsp} if ($rodsp);
286     push @loopfilter,{crit=>"Return Display",filter=>$podsp} if ($podsp);
287
288     
289     
290     my @linefilter;
291 #       warn "filtres ".@filters[0];
292 #       warn "filtres ".@filters[1];
293 #       warn "filtres ".@filters[2];
294 #       warn "filtres ".@filters[3];
295     $line = "issues.".$line if ($line=~/branchcode/) or ($line=~/timestamp/);
296     $line = "biblioitems.".$line if $line=~/itemtype/;
297     
298     $linefilter[0] = @$filters[0] if ($line =~ /timestamp/ )  ;
299     $linefilter[1] = @$filters[1] if ($line =~ /timestamp/ )  ;
300     $linefilter[2] = @$filters[2] if ($line =~ /timestamp/ )  ;
301     $linefilter[3] = @$filters[3] if ($line =~ /timestamp/ )  ;
302     $linefilter[0] = @$filters[4] if ($line =~ /returndate/ )  ;
303     $linefilter[1] = @$filters[5] if ($line =~ /returndate/ )  ;
304     $linefilter[2] = @$filters[6] if ($line =~ /returndate/ )  ;
305     $linefilter[3] = @$filters[7] if ($line =~ /returndate/ )  ;
306     $linefilter[0] = @$filters[8] if ($line =~ /category/ )  ;
307     $linefilter[0] = @$filters[9] if ($line =~ /itemtype/ )  ;
308     $linefilter[0] = @$filters[10] if ($line =~ /branch/ )  ;
309 #       $linefilter[0] = @$filters[11] if ($line =~ /sort2/ ) ;
310     $linefilter[0] = @$filters[11] if ($line =~ /sort1/ ) ;
311     $linefilter[0] = @$filters[12] if ($line =~ /sort2/ ) ;
312 #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
313
314     $column = "issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
315     $column = "biblioitems.".$column if $column=~/itemtype/;
316     my @colfilter ;
317     $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
318     $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
319     $colfilter[2] = @$filters[2] if ($column =~ /timestamp/ )  ;
320     $colfilter[3] = @$filters[3] if ($column =~ /timestamp/ )  ;
321     $colfilter[0] = @$filters[4] if ($column =~ /returndate/ )  ;
322     $colfilter[1] = @$filters[5] if ($column =~ /returndate/ )  ;
323     $colfilter[2] = @$filters[6] if ($column =~ /returndate/ )  ;
324     $colfilter[3] = @$filters[7] if ($column =~ /returndate/ )  ;
325     $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
326     $colfilter[0] = @$filters[9] if ($column =~ /itemtype/ )  ;
327     $colfilter[0] = @$filters[10] if ($column =~ /branch/ )  ;
328 #       $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
329     $colfilter[0] = @$filters[11] if ($column =~ /sort1/ ) ;
330     $colfilter[0] = @$filters[12] if ($column =~ /sort2/ ) ;
331 #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
332                                             
333 # 1st, loop rows.                             
334     my $linefield;
335     my $lineorder;                               
336     if ((($line =~/timestamp/) and ($podsp == 1)) or  (($line =~/returndate/) and ($rodsp == 1))) {
337         #Display by day
338         $linefield .="dayname($line)";  
339         $lineorder .="weekday($line)";  
340     } elsif ((($line =~/timestamp/) and ($podsp == 2)) or  (($line =~/returndate/) and ($rodsp == 2))) {
341         #Display by Month
342         $linefield .="monthname($line)";  
343         $lineorder .="month($line)";  
344     } elsif ((($line =~/timestamp/) and ($podsp == 3)) or  (($line =~/returndate/) and ($rodsp == 3))) {
345         #Display by Year
346         $linefield .="Year($line)";
347         $lineorder .= $line;  
348     } elsif (($line=~/timestamp/) or ($line=~/returndate/)){
349         $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")";
350         $lineorder .= $line;  
351     } else {
352         $linefield .= $line;
353         $lineorder .= $line;  
354     }  
355     
356     my $strsth;
357     $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";
358     
359     if (($line=~/timestamp/) or ($line=~/returndate/)){
360         if ($linefilter[1] and ($linefilter[0])){
361             $strsth .= " and $line between '$linefilter[0]' and '$linefilter[1]' " ;
362         } elsif ($linefilter[1]) {
363                 $strsth .= " and $line < \'$linefilter[1]\' " ;
364         } elsif ($linefilter[0]) {
365             $strsth .= " and $line > \'$linefilter[0]\' " ;
366         }
367         if ($linefilter[2]){
368             $strsth .= " and dayname($line) = '$linefilter[2]' " ;
369         }
370         if ($linefilter[3]){
371             $strsth .= " and monthname($line) = '$linefilter[3]' " ;
372         }
373     } elsif ($linefilter[0]) {
374         $linefilter[0] =~ s/\*/%/g;
375         $strsth .= " and $line LIKE '$linefilter[0]' " ;
376     }
377     $strsth .=" group by $linefield";
378     $strsth .=" order by $lineorder";
379     
380     my $sth = $dbh->prepare( $strsth );
381     $sth->execute;
382
383     
384     while ( my ($celvalue) = $sth->fetchrow) {
385         my %cell;
386         if ($celvalue) {
387             $cell{rowtitle} = $celvalue;
388         } else {
389             $cell{rowtitle} = "";
390         }
391         $cell{totalrow} = 0;
392         push @loopline, \%cell;
393     }
394
395 # 2nd, loop cols.
396     my $colfield;
397     my $colorder;                               
398     if ((($column =~/timestamp/) and ($podsp == 1)) or  (($column =~/returndate/) and ($rodsp == 1))) {
399         #Display by day
400         $colfield .="dayname($column)";  
401         $colorder .="weekday($column)";
402     } elsif ((($column =~/timestamp/) and ($podsp == 2)) or  (($column =~/returndate/) and ($rodsp == 2))) {
403         #Display by Month
404         $colfield .="monthname($column)";  
405         $colorder .="month($column)";  
406     } elsif ((($column =~/timestamp/) and ($podsp == 3)) or  (($column =~/returndate/) and ($rodsp == 3))) {
407         #Display by Year
408         $colfield .="Year($column)";
409         $colorder .= $column;
410     } elsif (($column=~/timestamp/) or ($column=~/returndate/)){
411         $colfield .= 'date_format( '."'".$column."'". ', "%Y-%m-%d")';
412         $colorder .= $column;
413     } else {
414         $colfield .= $column;
415         $colorder .= $column;
416     }  
417     
418     my $strsth2;
419     $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";
420     
421     if (($column=~/timestamp/) or ($column=~/returndate/)){
422         if ($colfilter[1] and ($colfilter[0])){
423             $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
424         } elsif ($colfilter[1]) {
425                 $strsth2 .= " and $column < '$colfilter[1]' " ;
426         } elsif ($colfilter[0]) {
427             $strsth2 .= " and $column > '$colfilter[0]' " ;
428         }
429         if ($colfilter[2]){
430             $strsth2 .= " and dayname($column) = '$colfilter[2]' " ;
431         }
432         if ($colfilter[3]){
433             $strsth2 .= " and monthname($column) = '$colfilter[3]' " ;
434         }
435     } elsif ($colfilter[0]) {
436         $colfilter[0] =~ s/\*/%/g;
437         $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
438     }
439     $strsth2 .=" group by $colfield";
440     $strsth2 .=" order by $colorder";
441     warn "". $strsth2;
442     
443     my $sth2 = $dbh->prepare( $strsth2 );
444     if (( @colfilter ) and ($colfilter[1])){
445         $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
446     } elsif ($colfilter[0]) {
447         $sth2->execute($colfilter[0]);
448     } else {
449         $sth2->execute;
450     }
451     
452
453     while (my ($celvalue) = $sth2->fetchrow) {
454         my %cell;
455         my %ft;
456 #               warn "coltitle :".$celvalue;
457         $cell{coltitle} = $celvalue;
458         $ft{totalcol} = 0;
459         push @loopcol, \%cell;
460     }
461 #       warn "fin des titres colonnes";
462
463     my $i=0;
464     my @totalcol;
465     my $hilighted=-1;
466     
467     #Initialization of cell values.....
468     my %table;
469     my %wgttable;
470     my %cnttable;
471     
472 #       warn "init table";
473     foreach my $row ( @loopline ) {
474         foreach my $col ( @loopcol ) {
475 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
476             $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
477         }
478         $table{$row->{rowtitle}}->{totalrow}=0;
479     }
480
481 # preparing calculation
482     my $strcalc ;
483     
484 # Processing average loanperiods
485     $strcalc .= "SELECT $linefield, $colfield, ";
486     $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";
487
488     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
489     $strcalc .= " AND issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
490     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
491     $strcalc .= " AND issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
492     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
493     $strcalc .= " AND issues.returndate > '" . @$filters[4] ."'" if ( @$filters[4] );
494     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
495     $strcalc .= " AND issues.returndate < '" . @$filters[5] ."'" if ( @$filters[5] );
496     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
497     $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] ."'" if ( @$filters[8] );
498     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
499     $strcalc .= " AND biblioitems.itemtype like '" . @$filters[9] ."'" if ( @$filters[9] );
500     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
501     $strcalc .= " AND issues.branchcode like '" . @$filters[10] ."'" if ( @$filters[10] );
502     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
503     $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] ."'" if ( @$filters[11] );
504     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
505     $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] ."'" if ( @$filters[12] );
506     $strcalc .= " AND dayname(timestamp) like '" . @$filters[2]."'" if (@$filters[2]);
507     $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] ."'" if ( @$filters[3] );
508     $strcalc .= " AND dayname(returndate) like '" . @$filters[5]."'" if (@$filters[5]);
509     $strcalc .= " AND monthname(returndate) like '" . @$filters[6] ."'" if ( @$filters[6] );
510     
511     $strcalc .= " group by  $linefield, $colfield, issuedate, returndate order by $linefield, $colfield";
512     warn "SQL :". $strcalc;
513     
514     my $dbcalc = $dbh->prepare($strcalc);
515     $dbcalc->execute;
516 #       warn "filling table";
517     my $issues_count=0;
518     my $previous_row; 
519     my $previous_col;
520     my $loanlength; 
521     my $err;
522     my $emptycol;
523     my $weightrow;
524     
525     while (my  @data = $dbcalc->fetchrow) {
526         my ($row, $col, $issuedate, $returndate, $weight)=@data;
527 #               warn "filling table $row / $col / $issuedate / $returndate /$weight";
528         $emptycol=1 if ($col eq undef);
529         $col = "zzEMPTY" if ($col eq undef);
530         $row = "zzEMPTY" if ($row eq undef);
531         # fill returndate to avoid an error with date calc (needed for all non returned issues)
532         $returndate= join '-',Date::Calc::Today if $returndate eq '0000-00-00';
533         my $result =Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ;
534     #  DateCalc returns => 0:0:WK:DD:HH:MM:SS   the weeks, days, hours, minutes,
535     #  and seconds between the two
536         $loanlength = $result;
537     #           warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight;
538     #           warn "513 row :".$row." column :".$col;
539         $table{$row}->{$col}+=$weight*$loanlength;
540     #           $table{$row}->{totalrow}+=$weight*$loanlength;
541         $cnttable{$row}->{$col}= 1;
542         $wgttable{$row}->{$col}+=$weight;
543     }
544     
545     push @loopcol,{coltitle => "NULL"} if ($emptycol);
546     
547     foreach my $row ( sort keys %table ) {
548         my @loopcell;
549     #@loopcol ensures the order for columns is common with column titles
550     # and the number matches the number of columns
551         my $colcount=0;
552         foreach my $col ( @loopcol ) {
553             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}});
554
555             $table{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}} = $value;
556             $table{$row}->{totalrow}+=$value;
557             #warn "row : $row col:$col  $cnttable{$row}->{(($col->{coltitle} eq \"NULL\")or ($col->{coltitle} eq \"\"))?\"zzEMPTY\":$col->{coltitle}}";
558             $colcount+=$cnttable{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}};
559             push @loopcell, {value => ($value)?sprintf("%.2f",$value):0  } ;
560         }
561         #warn "row : $row colcount:$colcount";
562         my $total = $table{$row}->{totalrow}/$colcount if ($colcount>0);
563         push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
564                         'loopcell' => \@loopcell,
565                         'hilighted' => ($hilighted >0),
566                         'totalrow' => ($total)?sprintf("%.2f",$total):0
567                     };
568         $hilighted = -$hilighted;
569     }
570 #       
571 # #     warn "footer processing";
572     foreach my $col ( @loopcol ) {
573         my $total=0;
574         my $nbrow=0;
575         foreach my $row ( @looprow ) {
576             $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}};
577             $nbrow +=$cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};;
578 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
579         }
580 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
581         $total = $total/$nbrow if ($nbrow);
582         push @loopfooter, {'totalcol' => ($total)?sprintf("%.2f",$total):0};
583     
584     }
585             
586
587     # the header of the table
588     $globalline{loopfilter}=\@loopfilter;
589     # the core of the table
590     $globalline{looprow} = \@looprow;
591     $globalline{loopcol} = \@loopcol;
592 #       # the foot (totals by borrower type)
593     $globalline{loopfooter} = \@loopfooter;
594     $globalline{total}= $grantotal;
595     $globalline{line} = $line;
596     $globalline{column} = $column;
597     push @mainloop,\%globalline;
598     return \@mainloop;
599 }
600
601 1;