Bug 33290: Fix incorrect variable in http-client.js
[koha-ffzg.git] / reports / acquisitions_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use C4::Auth qw( get_template_and_user );
23 use CGI qw ( -utf8 );
24 use C4::Context;
25 use C4::Reports qw( GetDelimiterChoices );
26 use C4::Output qw( output_html_with_http_headers );
27 use C4::Koha qw( GetAuthorisedValues );
28 use C4::Biblio qw( GetMarcSubfieldStructureFromKohaField );
29 use Koha::ItemTypes;
30 use Koha::Libraries;
31
32 =head1 NAME
33
34 reports/acquisitions_stats.pl
35
36 =head1 DESCRIPTION
37
38 Plugin that shows a stats on borrowers
39
40 =cut
41
42 my $input          = CGI->new;
43 my $do_it          = $input->param('do_it');
44 my $fullreportname = "reports/acquisitions_stats.tt";
45 my $line           = $input->param("Line");
46 my $column         = $input->param("Column");
47 my @filters        = $input->multi_param("Filter");
48 my $podsp          = $input->param("PlacedOnDisplay");
49 my $rodsp          = $input->param("ReceivedOnDisplay");
50 my $calc           = $input->param("Cellvalue");
51 my $output         = $input->param("output");
52 my $basename       = $input->param("basename");
53
54 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
55     {
56         template_name   => $fullreportname,
57         query           => $input,
58         type            => "intranet",
59         flagsrequired   => { reports => '*' },
60     }
61 );
62
63 our $sep = C4::Context->csv_delimiter(scalar $input->param("sep"));
64
65 $template->param(
66     do_it                    => $do_it,
67 );
68
69 if ($do_it) {
70     my $results =
71       calculate( $line, $column, $podsp, $rodsp, $calc, \@filters );
72     if ( $output eq "screen" ) {
73         $template->param( mainloop => $results );
74         output_html_with_http_headers $input, $cookie, $template->output;
75     }
76     else {
77         print $input->header(
78             -type       => 'application/vnd.sun.xml.calc',
79             -encoding    => 'utf-8',
80             -attachment => "$basename.csv",
81             -name       => "$basename.csv"
82         );
83         my $cols  = @$results[0]->{loopcol};
84         my $lines = @$results[0]->{looprow};
85         print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
86         foreach my $col (@$cols) {
87             print $col->{coltitle} . $sep;
88         }
89         print "Total\n";
90         foreach my $line (@$lines) {
91             my $x = $line->{loopcell};
92             print $line->{rowtitle} . $sep;
93             foreach my $cell (@$x) {
94                 print $cell->{value} . $sep;
95             }
96             print $line->{totalrow};
97             print "\n";
98         }
99         print "TOTAL";
100         $cols = @$results[0]->{loopfooter};
101         foreach my $col (@$cols) {
102             print $sep. $col->{totalcol};
103         }
104         print $sep. @$results[0]->{total};
105     }
106     exit;
107 }
108 else {
109     my $dbh = C4::Context->dbh;
110     my $req;
111     $req = $dbh->prepare("SELECT distinctrow id,name FROM aqbooksellers ORDER BY name");
112     $req->execute;
113     my $booksellers = $req->fetchall_arrayref({});
114
115     $req = $dbh->prepare("SELECT DISTINCTROW budget_code, budget_name FROM aqbudgets ORDER BY budget_name");
116     $req->execute;
117     my @bselect;
118     my %bselect;
119
120     while ( my ( $value, $desc ) = $req->fetchrow ) {
121         push @bselect, $value;
122         $bselect{$value} = $desc;
123     }
124     my $Budgets = {
125         values   => \@bselect,
126         labels   => \%bselect,
127     };
128
129     $req =
130       $dbh->prepare(
131 "SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"
132       );
133     $req->execute;
134     my @s1select;
135     my %s1select;
136     my $hassort1;
137     while ( my ($value) = $req->fetchrow ) {
138         if ($value) {
139             $hassort1 = 1;
140             push @s1select, $value;
141             $s1select{$value} = $value;
142         }
143     }
144     my $Sort1 = {
145         values   => \@s1select,
146         labels   => \%s1select,
147     };
148
149     $req =
150       $dbh->prepare(
151 "SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"
152       );
153     $req->execute;
154     my @s2select;
155     my %s2select;
156     my $hassort2;
157     my $hglghtsort2;
158
159     while ( my ($value) = $req->fetchrow ) {
160         if ($value) {
161             $hassort2    = 1;
162             $hglghtsort2 = !($hassort1);
163             push @s2select, $value;
164             $s2select{$value} = $value;
165         }
166     }
167     my $Sort2 = {
168         values   => \@s2select,
169         labels   => \%s2select,
170     };
171
172     my $CGIsepChoice = GetDelimiterChoices;
173
174     my $libraries = Koha::Libraries->search({}, { order_by => 'branchname' });
175
176     my $ccode_subfield_structure = GetMarcSubfieldStructureFromKohaField('items.ccode');
177     my $ccode_label;
178     my $ccode_avlist;
179     if($ccode_subfield_structure) {
180         $ccode_label = $ccode_subfield_structure->{liblibrarian};
181         $ccode_avlist = GetAuthorisedValues($ccode_subfield_structure->{authorised_value});
182     }
183
184     my $itemtypes = Koha::ItemTypes->search_with_localization;
185     $template->param(
186         booksellers   => $booksellers,
187         itemtypes     => $itemtypes, # FIXME Should use the TT plugin instead
188         Budgets       => $Budgets,
189         hassort1      => $hassort1,
190         hassort2      => $hassort2,
191         Sort1         => $Sort1,
192         Sort2         => $Sort2,
193         CGIsepChoice  => $CGIsepChoice,
194         branches      => $libraries,
195         ccode_label   => $ccode_label,
196         ccode_avlist  => $ccode_avlist,
197     );
198
199 }
200 output_html_with_http_headers $input, $cookie, $template->output;
201
202 sub calculate {
203     my ( $line, $column, $podsp, $rodsp, $process, $filters ) = @_;
204     my @mainloop;
205     my @loopfooter;
206     my @loopcol;
207     my @loopline;
208     my @looprow;
209     my %globalline;
210     my $grantotal = 0;
211
212     $podsp ||= 0;
213     $rodsp ||= 0;
214
215     # extract parameters
216     my $dbh = C4::Context->dbh;
217
218     # Filters
219     # Checking filters
220     #
221     my @loopfilter;
222     for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
223         if( defined @$filters[$i] and @$filters[$i] ne '' ) {
224             my %cell;
225             if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) {
226                 $cell{err} = 1 if ( @$filters[$i] lt @$filters[ $i - 1 ] );
227             }
228             $cell{filter} = @$filters[$i];
229             $cell{crit} = $i;
230             push @loopfilter, \%cell;
231         }
232     }
233
234     my %filter;
235     my %field;
236     foreach ($line, $column) {
237         $filter{$_} = [];
238         $field{$_} = $_;
239         if ( $_ =~ /closedate/ ) {
240             $filter{$_}->[0] = @$filters[0];
241             $filter{$_}->[1] = @$filters[1];
242             my $a = $_;
243             if ( $podsp == 1 ) {
244                 $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))";
245             } elsif ( $podsp == 2 ) {
246                 $field{$a} = "concat(hex(month($a)),'-',monthname($a))";
247             } elsif ( $podsp == 3 ) {
248                 $field{$a} = "Year($a)";
249             } else {
250                 $field{$a} = $a;
251             }
252         }
253         elsif ( $_ =~ /received/ ) {
254             $filter{$_}->[0] = @$filters[2];
255             $filter{$_}->[1] = @$filters[3];
256             my $a = $_;
257             if ( $rodsp == 1 ) {
258                 $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))";
259             } elsif ( $rodsp == 2 ) {
260                 $field{$a} = "concat(hex(month($a)),'-',monthname($a))";
261             } elsif ( $rodsp == 3 ) {
262                 $field{$a} = "Year($a)";
263             } else {
264                 $field{$a} = $a;
265             }
266         }
267         elsif ( $_ =~ /bookseller/ ) {
268             $filter{$_}->[0] = @$filters[4];
269         }
270         elsif ( $_ =~ /homebranch/ ) {
271             $filter{$_}->[0] = @$filters[5];
272         }
273         elsif ( $_ =~ /ccode/ ) {
274             $filter{$_}->[0] = @$filters[6];
275         }
276         elsif ( $_ =~ /itemtype/ ) {
277             $filter{$_}->[0] = @$filters[7];
278         }
279         elsif ( $_ =~ /budget/ ) {
280             $filter{$_}->[0] = @$filters[8];
281         }
282         elsif ( $_ =~ /sort1/ ) {
283             $filter{$_}->[0] = @$filters[9];
284         }
285         elsif ( $_ =~ /sort2/ ) {
286             $filter{$_}->[0] = @$filters[10];
287         }
288     }
289
290     my @linefilter = @{ $filter{$line} };
291     my $linefield = $field{$line};
292     my @colfilter = @{ $filter{$column} };
293     my $colfield = $field{$column};
294
295     # 1st, loop rows.
296     my $strsth = "
297         SELECT DISTINCTROW $linefield
298         FROM aqorders
299           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
300           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
301           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
302           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
303           LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
304           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
305         WHERE $line IS NOT NULL AND $line <> '' ";
306
307     if (@linefilter) {
308         if ( $linefilter[1] ) {
309             if ( $linefilter[0] ) {
310                 $strsth .= " AND $line BETWEEN ? AND ? ";
311             }
312             else {
313                 $strsth .= " AND $line <= ? ";
314             }
315         }
316         elsif (
317             ( $linefilter[0] )
318             and (  ( $line =~ /closedate/ )
319                 or ( $line =~ /received/ ))
320           )
321         {
322             $strsth .= " AND $line >= ? ";
323         }
324         elsif ( $linefilter[0] ) {
325             $linefilter[0] =~ s/\*/%/g;
326             $strsth .= " AND $line LIKE ? ";
327         }
328     }
329     $strsth .= " GROUP BY $linefield";
330     $strsth .= " ORDER BY $line";
331
332     my $sth = $dbh->prepare($strsth);
333     if ( (@linefilter) and ( $linefilter[1] ) ) {
334         $sth->execute( $linefilter[0], $linefilter[1] );
335     }
336     elsif ( $linefilter[0] ) {
337         $sth->execute( $linefilter[0] );
338     }
339     else {
340         $sth->execute;
341     }
342     while ( my ($celvalue) = $sth->fetchrow ) {
343         my %cell;
344         if ($celvalue) {
345             $cell{rowtitle} = $celvalue;
346             push @loopline, \%cell;
347         }
348         $cell{totalrow} = 0;
349     }
350
351     # 2nd, loop cols.
352     my $strsth2 = "
353         SELECT DISTINCTROW $colfield
354         FROM aqorders
355           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
356           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
357           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
358           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
359           LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
360           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
361         WHERE $column IS NOT NULL AND $column <> ''
362     ";
363
364     if (@colfilter) {
365         if ( $colfilter[1] ) {
366             if ( $colfilter[0] ) {
367                 $strsth2 .= " AND $column BETWEEN  ? AND ? ";
368             }
369             else {
370                 $strsth2 .= " AND $column <= ? ";
371             }
372         }
373         elsif (
374             ( $colfilter[0] )
375             and (  ( $column =~ /closedate/ )
376                 or ( $line =~ /received/ ))
377           )
378         {
379             $strsth2 .= " AND $column >= ? ";
380         }
381         elsif ( $colfilter[0] ) {
382             $colfilter[0] =~ s/\*/%/g;
383             $strsth2 .= " AND $column LIKE ? ";
384         }
385     }
386
387     $strsth2 .= " GROUP BY $colfield";
388     $strsth2 .= " ORDER BY $colfield";
389
390     my $sth2 = $dbh->prepare($strsth2);
391
392     if ( (@colfilter) and ($colfilter[1]) ) {
393         $sth2->execute( $colfilter[0], $colfilter[1] );
394     }
395     elsif ( $colfilter[0] ) {
396         $sth2->execute( $colfilter[0] );
397     }
398     else {
399         $sth2->execute;
400     }
401     while ( my $celvalue = $sth2->fetchrow ) {
402         my %cell;
403         if ($celvalue) {
404             $cell{coltitle} = $celvalue;
405             push @loopcol, \%cell;
406         }
407     }
408
409     my $i = 0;
410     my $hilighted = -1;
411
412     #Initialization of cell values.....
413     my %table;
414
415     foreach my $row (@loopline) {
416         foreach my $col (@loopcol) {
417             $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0;
418         }
419         $table{ $row->{rowtitle} }->{totalrow} = 0;
420     }
421
422     # preparing calculation
423     my $strcalc;
424     $strcalc .= "SELECT $linefield, $colfield, ";
425     if ( $process == 1 ) {
426         $strcalc .= "COUNT(*) ";
427     } elsif ( $process == 2 ) {
428         $strcalc .= "COUNT(DISTINCT(aqorders.biblionumber)) ";
429     } elsif ( $process == 3 || $process == 4 || $process == 5 ) {
430         $strcalc .= "SUM(aqorders.listprice) ";
431     } else {
432         $strcalc .= "NULL ";
433     }
434     $strcalc .= "
435         FROM aqorders
436           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
437           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
438           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
439           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
440           LEFT JOIN aqbudgets ON (aqorders.budget_id = aqbudgets.budget_id )
441           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
442         WHERE aqorders.datecancellationprinted IS NULL ";
443     $strcalc .= " AND (aqorders.datereceived IS NULL OR aqorders.datereceived = '') "
444         if ( $process == 4 );
445     $strcalc .= " AND aqorders.datereceived IS NOT NULL AND aqorders.datereceived <> '' "
446         if ( $process == 5 );
447     @$filters[0] =~ s/\*/%/g if ( @$filters[0] );
448     $strcalc .= " AND aqbasket.closedate >= '" . @$filters[0] . "'"
449       if ( @$filters[0] );
450     @$filters[1] =~ s/\*/%/g if ( @$filters[1] );
451     $strcalc .= " AND aqbasket.closedate <= '" . @$filters[1] . "'"
452       if ( @$filters[1] );
453     @$filters[2] =~ s/\*/%/g if ( @$filters[2] );
454     $strcalc .= " AND aqorders.datereceived >= '" . @$filters[2] . "'"
455       if ( @$filters[2] );
456     @$filters[3] =~ s/\*/%/g if ( @$filters[3] );
457     $strcalc .= " AND aqorders.datereceived <= '" . @$filters[3] . "'"
458       if ( @$filters[3] );
459     @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
460     $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[4] . "'"
461       if ( @$filters[4] );
462     $strcalc .= " AND items.homebranch = '" . @$filters[5] . "'"
463       if ( @$filters[5] );
464     @$filters[6] =~ s/\*/%/g if ( @$filters[6] );
465     $strcalc .= " AND items.ccode = '" . @$filters[6] . "'"
466       if ( @$filters[6] );
467     @$filters[7] =~ s/\*/%/g if ( @$filters[7] );
468     $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[7] . "'"
469       if ( @$filters[7] );
470     @$filters[8] =~ s/\*/%/g if ( @$filters[8] );
471     $strcalc .= " AND aqbudgets.budget_code LIKE '" . @$filters[8] . "'"
472       if ( @$filters[8] );
473     @$filters[9] =~ s/\*/%/g if ( @$filters[9] );
474     $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[9] . "'"
475       if ( @$filters[9] );
476     @$filters[10] =~ s/\*/%/g if ( @$filters[10] );
477     $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[10] . "'"
478       if ( @$filters[10] );
479
480     $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield";
481     my $dbcalc = $dbh->prepare($strcalc);
482     $dbcalc->execute;
483
484     my $emptycol;
485     while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
486         $emptycol = 1         if ( !defined($col) );
487         $col      = "zzEMPTY" if ( !defined($col) );
488         $row      = "zzEMPTY" if ( !defined($row) );
489
490         $table{$row}->{$col}     += $value;
491         $table{$row}->{totalrow} += $value;
492         $grantotal               += $value;
493     }
494
495     push @loopcol, { coltitle => "NULL" } if ($emptycol);
496
497     foreach my $row ( sort keys %table ) {
498         my @loopcell;
499         #@loopcol ensures the order for columns is common with column titles
500         # and the number matches the number of columns
501         foreach my $col (@loopcol) {
502             my $value = $table{$row}->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} };
503             $value = sprintf("%.2f", $value) if($value and grep /$process/, (3,4,5));
504             push @loopcell, { value => $value };
505         }
506         my $r = {
507             rowtitle => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
508             loopcell  => \@loopcell,
509             hilighted => ( $hilighted > 0 ),
510             totalrow  => $table{$row}->{totalrow}
511         };
512         $r->{totalrow} = sprintf("%.2f", $r->{totalrow}) if($r->{totalrow} and grep /$process/, (3,4,5));
513         push @looprow, $r;
514         $hilighted = -$hilighted;
515     }
516
517     foreach my $col (@loopcol) {
518         my $total = 0;
519         foreach my $row (@looprow) {
520             $total += $table{
521                 ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY"
522                 : $row->{rowtitle}
523               }->{
524                 ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY"
525                 : $col->{coltitle}
526               };
527         }
528         $total = sprintf("%.2f", $total) if($total and grep /$process/, (3,4,5));
529
530         push @loopfooter, { 'totalcol' => $total };
531     }
532
533     # the header of the table
534     $globalline{loopfilter} = \@loopfilter;
535     # the core of the table
536     $globalline{looprow} = \@looprow;
537     $globalline{loopcol} = \@loopcol;
538
539     #       # the foot (totals by borrower type)
540     $grantotal = sprintf("%.2f", $grantotal) if ($grantotal and grep /$process/, (3,4,5));
541     $globalline{loopfooter} = \@loopfooter;
542     $globalline{total}      = $grantotal;
543     $globalline{line}       = $line;
544     $globalline{column}     = $column;
545     push @mainloop, \%globalline;
546     return \@mainloop;
547 }
548
549 1;
550