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