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