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