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