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