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