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