Bug 7272 setting NULL to debarred field, to avoid having 0000-00-00
[koha.git] / reports / acquisitions_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 # test comment
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Auth;
26 use CGI;
27 use C4::Context;
28 use C4::Reports;
29 use C4::Output;
30 use C4::Koha;
31 use C4::Circulation;
32 use C4::Dates qw/format_date format_date_in_iso/;
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/acquisitions_stats.tmpl";
47 my $line           = $input->param("Line");
48 my $column         = $input->param("Column");
49 my @filters        = $input->param("Filter");
50 $filters[0]= (($line =~ /closedate/ || $column =~ /closedate/) ? format_date_in_iso($filters[0]) : undef);
51 $filters[1]= (($line =~ /closedate/ || $column =~ /closedate/) ? format_date_in_iso($filters[1]) : undef);
52 $filters[2]= (($line =~ /delivery/ || $column =~ /delivery/) ? format_date_in_iso($filters[2]) : undef);
53 $filters[3]= (($line =~ /delivery/ || $column =~ /delivery/) ? format_date_in_iso($filters[3]) : undef);
54 my $podsp          = $input->param("PlacedOnDisplay");
55 my $rodsp          = $input->param("ReceivedOnDisplay");
56 my $aodsp          = $input->param("AcquiredOnDisplay");    ##added by mason.
57 my $calc           = $input->param("Cellvalue");
58 my $output         = $input->param("output");
59 my $basename       = $input->param("basename");
60
61 #warn "calcul : ".$calc;
62 my ($template, $borrowernumber, $cookie)
63         = get_template_and_user({template_name => $fullreportname,
64                                 query => $input,
65                                 type => "intranet",
66                                 authnotrequired => 0,
67                                 flagsrequired => {reports => '*'},
68                                 debug => 1,
69                                 });
70 our $sep     = $input->param("sep");
71 $sep = "\t" if ($sep eq 'tabulation');
72 $template->param(do_it => $do_it,
73         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
74                 );
75 if ($do_it) {
76     my $results =
77       calculate( $line, $column, $podsp, $rodsp, $aodsp, $calc, \@filters );
78     if ( $output eq "screen" ) {
79         $template->param( mainloop => $results );
80         output_html_with_http_headers $input, $cookie, $template->output;
81     }
82     else {
83         print $input->header(
84             -type       => 'application/vnd.sun.xml.calc',
85             -encoding    => 'utf-8',
86             -attachment => "$basename.csv",
87             -name       => "$basename.csv"
88         );
89         my $cols  = @$results[0]->{loopcol};
90         my $lines = @$results[0]->{looprow};
91         print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
92         foreach my $col (@$cols) {
93             print $col->{coltitle} . $sep;
94         }
95         print "Total\n";
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         print "TOTAL";
106         $cols = @$results[0]->{loopfooter};
107         foreach my $col (@$cols) {
108             print $sep. $col->{totalcol};
109         }
110         print $sep. @$results[0]->{total};
111     }
112     exit(1);
113 }
114 else {
115     my $dbh = C4::Context->dbh;
116     my @select;
117     my %select;
118     my $req;
119     $req = $dbh->prepare("SELECT distinctrow id,name FROM aqbooksellers ORDER BY name");
120     $req->execute;
121     my @select;
122     push @select, "";
123         $select{''} = "All Suppliers";
124     while ( my ( $value, $desc ) = $req->fetchrow ) {
125         push @select, $desc;
126         $select{$value}=$desc;
127     }
128     my $CGIBookSellers = CGI::scrolling_list(
129         -name   => 'Filter',
130         -id     => 'supplier',
131         -values => \@select,
132         -labels   => \%select,
133         -size     => 1,
134         -multiple => 0
135     );
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{''} = "All Item Types";
143     while ( my ( $value, $desc ) = $req->fetchrow ) {
144         push @select, $value;
145         $select{$value} = $desc;
146     }
147     my $CGIItemTypes = CGI::scrolling_list(
148         -name     => 'Filter',
149         -id       => 'itemtypes',
150         -values   => \@select,
151         -labels   => \%select,
152         -size     => 1,
153         -multiple => 0
154     );
155
156     $req = $dbh->prepare("SELECT DISTINCTROW budget_code, budget_name FROM aqbudgets ORDER BY budget_name");
157     $req->execute;
158     undef @select;
159     undef %select;
160     push @select, "";
161     $select{''} = "All budgets";
162
163     while ( my ( $value, $desc ) = $req->fetchrow ) {
164         push @select, $value;
165         $select{$value} = $desc;
166     }
167     my $CGIBudget = CGI::scrolling_list(
168         -name     => 'Filter',
169         -id       => 'budget',
170         -values   => \@select,
171         -labels   => \%select,
172         -size     => 1,
173         -multiple => 0
174     );
175
176     $req =
177       $dbh->prepare(
178 "SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"
179       );
180     $req->execute;
181     undef @select;
182     undef %select;
183     push @select, "";
184     $select{''} = "All";
185     my $hassort1;
186     while ( my ($value) = $req->fetchrow ) {
187                 if ($value) {
188                         $hassort1 = 1;
189                         push @select, $value;
190                         $select{$value} = $value;
191                 }
192     }
193     my $CGISort1 = CGI::scrolling_list(
194         -name     => 'Filter',
195         -id       => 'sort1',
196         -values   => \@select,
197         -labels   => \%select,
198         -size     => 1,
199         -multiple => 0
200     );
201
202     $req =
203       $dbh->prepare(
204 "SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"
205       );
206     $req->execute;
207     undef @select;
208     undef %select;
209     push @select, "";
210     $select{''} = "All";
211     my $hassort2;
212     my $hglghtsort2;
213
214     while ( my ($value) = $req->fetchrow ) {
215                 if ($value) {
216                         $hassort2 = 1;
217                         $hglghtsort2 = !($hassort1);
218                         push @select, $value;
219                         $select{$value} = $value;
220                 }
221     }
222     my $CGISort2 = CGI::scrolling_list(
223         -name     => 'Filter',
224         -id       => 'sort2',
225         -values   => \@select,
226         -labels   => \%select,
227         -size     => 1,
228         -multiple => 0
229     );
230
231     my $CGIextChoice = CGI::scrolling_list(
232         -name     => 'MIME',
233         -id       => 'MIME',
234         -values   => ['CSV'], # FIXME translation
235         -size     => 1,
236         -multiple => 0
237     );
238
239     my $CGIsepChoice = GetDelimiterChoices;
240
241     $template->param(
242         CGIBookSeller => $CGIBookSellers,
243         CGIItemType   => $CGIItemTypes,
244         CGIBudget     => $CGIBudget,
245         hassort1      => $hassort1,
246         hassort2      => $hassort2,
247         HlghtSort2    => $hglghtsort2,
248         CGISort1      => $CGISort1,
249         CGISort2      => $CGISort2,
250         CGIextChoice  => $CGIextChoice,
251         CGIsepChoice  => $CGIsepChoice,
252                 date_today => C4::Dates->new()->output()
253     );
254
255 }
256 output_html_with_http_headers $input, $cookie, $template->output;
257
258 sub calculate {
259     my ( $line, $column, $podsp, $rodsp, $aodsp, $process, $filters ) = @_;
260     my @mainloop;
261     my @loopfooter;
262     my @loopcol;
263     my @loopline;
264     my @looprow;
265     my %globalline;
266     my $grantotal = 0;
267
268     # extract parameters
269     my $dbh = C4::Context->dbh;
270
271     # Filters
272     # Checking filters
273     #
274     my @loopfilter;
275     for ( my $i = 0 ; $i <= 8 ; $i++ ) {
276         my %cell;
277         if ( @$filters[$i] ) {
278             if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) {
279                 $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
280             }
281             # format the dates filters, otherwise just fill as is
282             if ($i>=4) {
283                 $cell{filter} .= @$filters[$i];
284             } else {
285                 $cell{filter} .= format_date(@$filters[$i]);
286             }
287             $cell{crit}   .= "Placed On From" if ( $i == 0 );
288             $cell{crit}   .= "Placed On To" if ( $i == 1 );
289             $cell{crit}   .= "Received On From" if ( $i == 2 );
290             $cell{crit}   .= "Received On To" if ( $i == 3 );
291
292 #            $cell{crit} .= "Acquired On From" if ( $i == 4 );
293 #            $cell{crit} .= "Acquired On To"   if ( $i == 5 );
294
295             $cell{crit} .= "BookSeller" if ( $i == 4 );
296             $cell{crit} .= "Doc Type"   if ( $i == 5 );
297             $cell{crit} .= "Budget"     if ( $i == 6 );
298             $cell{crit} .= "Sort1"      if ( $i == 7 );
299             $cell{crit} .= "Sort2"      if ( $i == 8 );
300             push @loopfilter, \%cell;
301         }
302     }
303
304     my @linefilter;
305
306     #       warn "filtres ".@filters[0];
307     #       warn "filtres ".@filters[1];
308     #       warn "filtres ".@filters[2];
309     #       warn "filtres ".@filters[3];
310
311     $linefilter[0] = @$filters[0] if ( $line =~ /closedate/ );
312     $linefilter[1] = @$filters[1] if ( $line =~ /closedate/ );
313     $linefilter[0] = @$filters[2] if ( $line =~ /received/ );
314     $linefilter[1] = @$filters[3] if ( $line =~ /received/ );
315
316 #    $linefilter[0] = @$filters[4] if ( $line =~ /acquired/ );
317 #    $linefilter[1] = @$filters[5] if ( $line =~ /acquired/ );
318
319     $linefilter[0] = @$filters[4]  if ( $line =~ /bookseller/ );
320     $linefilter[0] = @$filters[5]  if ( $line =~ /itemtype/ );
321     $linefilter[0] = @$filters[6]  if ( $line =~ /budget/ );
322     $linefilter[0] = @$filters[7]  if ( $line =~ /sort1/ );
323     $linefilter[0] = @$filters[8] if ( $line =~ /sort2/ );
324
325     #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
326     #
327     my @colfilter;
328     $colfilter[0] = @$filters[0] if ( $column =~ /closedate/ );
329     $colfilter[1] = @$filters[1] if ( $column =~ /closedate/ );
330     $colfilter[0] = @$filters[2] if ( $column =~ /received/ );
331     $colfilter[1] = @$filters[3] if ( $column =~ /received/ );
332
333 #    $colfilter[0] = @$filters[4] if ( $column =~ /acquired/ );
334 #    $colfilter[1] = @$filters[5] if ( $column =~ /acquired/ );
335     $colfilter[0] = @$filters[4]  if ( $column =~ /bookseller/ );
336     $colfilter[0] = @$filters[5]  if ( $column =~ /itemtype/ );
337     $colfilter[0] = @$filters[6]  if ( $column =~ /budget/ );
338     $colfilter[0] = @$filters[7]  if ( $column =~ /sort1/ );
339     $colfilter[0] = @$filters[8]  if ( $column =~ /sort2/ );
340
341     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
342
343 #    warn "line=$line, podsp=$podsp, rodsp=$rodsp, aodsp=$aodsp\n";
344
345     # 1st, loop rows.
346     my $linefield;
347     if ( ( $line =~ /closedate/ ) and ( $podsp == 1 ) ) {
348
349         #Display by day
350         $linefield .= "dayname($line)";
351     }
352     elsif ( ( $line =~ /closedate/ ) and ( $podsp == 2 ) ) {
353
354         #Display by Month
355         $linefield .= "monthname($line)";
356     }
357     elsif ( ( $line =~ /closedate/ ) and ( $podsp == 3 ) ) {
358
359         #Display by Year
360         $linefield .= "Year($line)";
361
362     }
363     elsif ( ( $line =~ /received/ ) and ( $rodsp == 1 ) ) {
364
365         #Display by day
366         $linefield .= "dayname($line)";
367     }
368     elsif ( ( $line =~ /received/ ) and ( $rodsp == 2 ) ) {
369
370         #Display by Month
371         $linefield .= "monthname($line)";
372     }
373     elsif ( ( $line =~ /received/ ) and ( $rodsp == 3 ) ) {
374
375         #Display by Year
376         $linefield .= "Year($line)";
377
378     }
379 #    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 1 ) ) {
380 #
381 #        #Display by day
382 #        $linefield .= "dayname($line)";
383 #    }
384 #    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 2 ) ) {
385 #
386 #        #Display by Month
387 #        $linefield .= "monthname($line)";
388 #    }
389 #    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 3 ) ) {
390 #
391 #        #Display by Year
392 #        $linefield .= "Year($line)";
393 #
394 #    }
395     else {
396         $linefield .= $line;
397     }
398
399     my $strsth;
400     $strsth .=
401       "SELECT DISTINCTROW $linefield FROM (aqorders, aqbasket )
402                 LEFT JOIN items ON (aqorders.biblionumber= items.biblionumber)
403                 LEFT JOIN biblioitems ON (aqorders.biblionumber= biblioitems.biblionumber)
404                 LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
405
406                 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id) WHERE (aqorders.basketno=aqbasket.basketno)
407                 AND $line IS NOT NULL AND $line <> '' ";
408
409 #                               LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
410     
411         if (@linefilter) {
412         if ( $linefilter[1] ) {
413             if ( $linefilter[0] ) {
414                 $strsth .= " AND $line BETWEEN ? AND ? ";
415             }
416             else {
417                 $strsth .= " AND $line <= ? ";
418             }
419         }
420         elsif (
421             ( $linefilter[0] )
422             and (  ( $line =~ /closedate/ )
423                 or ( $line =~ /received/ ))
424 #                or ( $line =~ /acquired/ ) )
425           )
426         {
427             $strsth .= " AND $line >= ? ";
428         }
429         elsif ( $linefilter[0] ) {
430             $linefilter[0] =~ s/\*/%/g;
431             $strsth .= " AND $line LIKE ? ";
432         }
433     }
434     $strsth .= " GROUP BY $linefield";
435     $strsth .= " ORDER BY $line";
436
437     #warn "377:strsth= $strsth";
438
439     my $sth = $dbh->prepare($strsth);
440     if ( (@linefilter) and ( $linefilter[1] ) ) {
441         $sth->execute( $linefilter[0], $linefilter[1] );
442     }
443     elsif ( $linefilter[0] ) {
444         $sth->execute( $linefilter[0] );
445     }
446     else {
447         $sth->execute;
448     }
449         while ( my ($celvalue) = $sth->fetchrow ) {
450                 my %cell;
451                 if ($celvalue) {
452                         $cell{rowtitle} = $celvalue;
453                         push @loopline, \%cell;
454                 }
455                 $cell{totalrow} = 0;
456         }
457 #    warn "column=$column, podsp=$podsp, rodsp=$rodsp, aodsp=$aodsp\n";
458
459     # 2nd, loop cols.
460     my $colfield;
461     if ( ( $column =~ /closedate/ ) and ( $podsp == 1 ) ) {
462
463         #Display by day
464         $colfield .= "dayname($column)";
465     }
466     elsif ( ( $column =~ /closedate/ ) and ( $podsp == 2 ) ) {
467
468         #Display by Month
469         $colfield .= "monthname($column)";
470     }
471     elsif ( ( $column =~ /closedate/ ) and ( $podsp == 3 ) ) {
472
473         #Display by Year
474         $colfield .= "Year($column)";
475
476     }
477     elsif ( ( $column =~ /received/ ) and ( $rodsp == 1 ) ) {
478
479         #Display by day
480         $colfield .= "dayname($column)";
481     }
482     elsif ( ( $column =~ /received/ ) and ( $rodsp == 2 ) ) {
483
484         #Display by Month
485         $colfield .= "monthname($column)";
486     }
487     elsif ( ( $column =~ /received/ ) and ( $rodsp == 3 ) ) {
488
489         #Display by Year
490         $colfield .= "Year($column)";
491
492     }
493 #    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 1 ) ) {
494 #
495 #        #Display by day
496 #        $colfield .= "dayname($column)";
497 #    }
498 #    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 2 ) ) {
499 #
500 #        #Display by Month
501 #        $colfield .= "monthname($column)";
502 #    }
503 #    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 3 ) ) {
504 #
505 #        #Display by Year
506 #        $colfield .= "Year($column)";
507 #
508 #    }
509     else {
510         $colfield .= $column;
511     }
512
513     my $strsth2;
514     $strsth2 .=
515       "SELECT distinctrow $colfield FROM (aqorders, aqbasket )
516                  LEFT JOIN items ON (aqorders.biblionumber= items.biblionumber)
517                  LEFT JOIN biblioitems ON (aqorders.biblionumber= biblioitems.biblionumber)
518                  LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
519
520                  LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id)
521                  WHERE (aqorders.basketno=aqbasket.basketno) AND 
522                  $column IS NOT NULL AND $column <> '' ";
523
524 #                               LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
525
526     if (@colfilter) {
527         if ( $colfilter[1] ) {
528             if ( $colfilter[0] ) {
529                 $strsth2 .= " AND $column BETWEEN  ? AND ? ";
530             }
531             else {
532                 $strsth2 .= " AND $column <= ? ";
533             }
534         }
535         elsif (
536             ( $colfilter[0] )
537             and (  ( $column =~ /closedate/ )
538                 or ( $line =~ /received/ ))
539 #                or ( $line =~ /acquired/ ) )
540           )
541         {
542             $strsth2 .= " AND $column >= ? ";
543         }
544         elsif ( $colfilter[0] ) {
545             $colfilter[0] =~ s/\*/%/g;
546             $strsth2 .= " AND $column LIKE ? ";
547         }
548     }
549
550
551     $strsth2 .= " GROUP BY $colfield";
552     $strsth2 .= " ORDER BY $column";
553
554     my $sth2 = $dbh->prepare($strsth2);
555
556     if ( (@colfilter) and ($colfilter[1]) ) {
557         $sth2->execute( $colfilter[0], $colfilter[1] );
558     }
559     elsif ( $colfilter[0] ) {
560         $sth2->execute( $colfilter[0] );
561     }
562     else {
563         $sth2->execute;
564     }
565         while ( my $celvalue = $sth2->fetchrow ) {
566                 my %cell;
567                 if ($celvalue) {
568                         $cell{coltitle} = $celvalue;
569                         push @loopcol, \%cell;
570                 }
571         }
572
573     #       warn "fin des titres colonnes";
574
575     my $i = 0;
576     my @totalcol;
577     my $hilighted = -1;
578
579     #Initialization of cell values.....
580     my %table;
581
582 #       warn "init table...\n";
583     foreach my $row (@loopline) {
584         foreach my $col (@loopcol) {
585             $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0;
586         }
587         $table{ $row->{rowtitle} }->{totalrow} = 0;
588     }
589
590     # preparing calculation
591     my $strcalc;
592     $strcalc .= "SELECT $linefield, $colfield, ";
593     $strcalc .= "SUM( aqorders.quantity ) " if ( $process == 1 );
594     $strcalc .= "SUM( aqorders.quantity * aqorders.listprice ) "
595       if ( $process == 2 );
596     $strcalc .= "FROM (aqorders, aqbasket )
597                  LEFT JOIN items ON (aqorders.biblionumber= items.biblionumber)
598                  LEFT JOIN biblioitems ON (aqorders.biblionumber= biblioitems.biblionumber)
599                  LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
600
601                  LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id) 
602                  WHERE (aqorders.basketno=aqbasket.basketno) ";
603
604 #                 LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
605     
606         @$filters[0] =~ s/\*/%/g if ( @$filters[0] );
607     $strcalc .= " AND aqbasket.closedate >= '" . @$filters[0] . "'"
608       if ( @$filters[0] );
609     @$filters[1] =~ s/\*/%/g if ( @$filters[1] );
610     $strcalc .= " AND aqbasket.closedate <= '" . @$filters[1] . "'"
611       if ( @$filters[1] );
612     @$filters[2] =~ s/\*/%/g if ( @$filters[2] );
613     $strcalc .= " AND aqorders.datereceived >= '" . @$filters[2] . "'"
614       if ( @$filters[2] );
615     @$filters[3] =~ s/\*/%/g if ( @$filters[3] );
616     $strcalc .= " AND aqorders.datereceived <= '" . @$filters[3] . "'"
617       if ( @$filters[3] );
618 #    @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
619 #    $strcalc .= " AND aqbasket.closedate >= '" . @$filters[4] . "'"
620 #      if ( @$filters[4] );
621 #    @$filters[5] =~ s/\*/%/g if ( @$filters[5] );
622 #    $strcalc .= " AND aqbasket.closedate <= '" . @$filters[5] . "'"
623 #      if ( @$filters[5] );
624     @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
625     $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[4] . "'"
626       if ( @$filters[4] );
627     @$filters[5] =~ s/\*/%/g if ( @$filters[5] );
628     $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[5] . "'"
629       if ( @$filters[5] );
630     @$filters[6] =~ s/\*/%/g if ( @$filters[6] );
631     $strcalc .= " AND aqbudgets.budget_code LIKE '" . @$filters[6] . "'"
632       if ( @$filters[6] );
633     @$filters[7] =~ s/\*/%/g if ( @$filters[7] );
634     $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[7] . "'"
635       if ( @$filters[7] );
636     @$filters[8] =~ s/\*/%/g if ( @$filters[8] );
637     $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[8] . "'"
638       if ( @$filters[8] );
639
640     $strcalc .= " AND aqorders.datecancellationprinted is NULL ";
641
642     $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield";
643
644 #       warn $strcalc . "\n";
645
646     my $dbcalc = $dbh->prepare($strcalc);
647     $dbcalc->execute;
648
649     #       warn "filling table";
650     my $emptycol;
651     while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
652                 next if ($row eq undef || $col eq undef);
653
654 # warn "filling table $row / $col / $value ";
655
656         $emptycol = 1         if ( !defined($col) );
657         $col      = "zzEMPTY" if ( !defined($col) );
658         $row      = "zzEMPTY" if ( !defined($row) );
659
660         $table{$row}->{$col}     += $value;
661         $table{$row}->{totalrow} += $value;
662         $grantotal               += $value;
663     }
664
665     push @loopcol, { coltitle => "NULL" } if ($emptycol);
666
667     foreach my $row ( sort keys %table ) {
668         my @loopcell;
669         #@loopcol ensures the order for columns is common with column titles
670         # and the number matches the number of columns
671         foreach my $col (@loopcol) {
672             my $value = $table{$row}->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} };
673             push @loopcell, { value => $value };
674         }
675         push @looprow,
676           {
677             'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
678             'loopcell'  => \@loopcell,
679             'hilighted' => ( $hilighted > 0 ),
680             'totalrow'  => $table{$row}->{totalrow}
681           };
682         $hilighted = -$hilighted;
683     }
684
685     #       warn "footer processing";
686     foreach my $col (@loopcol) {
687         my $total = 0;
688         foreach my $row (@looprow) {
689             $total += $table{
690                 ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY"
691                 : $row->{rowtitle}
692               }->{
693                 ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY"
694                 : $col->{coltitle}
695               };
696
697 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
698         }
699
700         #               warn "summ for column ".$col->{coltitle}."  = ".$total;
701         push @loopfooter, { 'totalcol' => $total };
702     }
703
704     # the header of the table
705         $globalline{loopfilter}=\@loopfilter;
706     # the core of the table
707     $globalline{looprow} = \@looprow;
708     $globalline{loopcol} = \@loopcol;
709
710     #       # the foot (totals by borrower type)
711     $globalline{loopfooter} = \@loopfooter;
712     $globalline{total}      = $grantotal;
713     $globalline{line}       = $line;
714     $globalline{column}     = $column;
715     push @mainloop, \%globalline;
716     return \@mainloop;
717 }
718
719 1;
720