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