Bug 10132: Simplify code, call the method only once
[koha.git] / reports / acquisitions_stats.pl
blobac86289a1afe6cc220b9ec64ab4d75f741cb3c9a
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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>.
20 use Modern::Perl;
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;
34 =head1 NAME
36 reports/acquisitions_stats.pl
38 =head1 DESCRIPTION
40 Plugin that shows a stats on borrowers
42 =cut
44 my $input = new CGI;
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");
64 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
66 template_name => $fullreportname,
67 query => $input,
68 type => "intranet",
69 authnotrequired => 0,
70 flagsrequired => { reports => '*' },
71 debug => 1,
75 our $sep = $input->param("sep") // '';
76 $sep = "\t" if ($sep eq 'tabulation');
78 $template->param(
79 do_it => $do_it,
82 if ($do_it) {
83 my $results =
84 calculate( $line, $column, $podsp, $rodsp, $calc, \@filters );
85 if ( $output eq "screen" ) {
86 $template->param( mainloop => $results );
87 output_html_with_http_headers $input, $cookie, $template->output;
89 else {
90 print $input->header(
91 -type => 'application/vnd.sun.xml.calc',
92 -encoding => 'utf-8',
93 -attachment => "$basename.csv",
94 -name => "$basename.csv"
96 my $cols = @$results[0]->{loopcol};
97 my $lines = @$results[0]->{looprow};
98 print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
99 foreach my $col (@$cols) {
100 print $col->{coltitle} . $sep;
102 print "Total\n";
103 foreach my $line (@$lines) {
104 my $x = $line->{loopcell};
105 print $line->{rowtitle} . $sep;
106 foreach my $cell (@$x) {
107 print $cell->{value} . $sep;
109 print $line->{totalrow};
110 print "\n";
112 print "TOTAL";
113 $cols = @$results[0]->{loopfooter};
114 foreach my $col (@$cols) {
115 print $sep. $col->{totalcol};
117 print $sep. @$results[0]->{total};
119 exit;
121 else {
122 my $dbh = C4::Context->dbh;
123 my $req;
124 $req = $dbh->prepare("SELECT distinctrow id,name FROM aqbooksellers ORDER BY name");
125 $req->execute;
126 my $booksellers = $req->fetchall_arrayref({});
128 $req = $dbh->prepare("SELECT DISTINCTROW budget_code, budget_name FROM aqbudgets ORDER BY budget_name");
129 $req->execute;
130 my @bselect;
131 my %bselect;
133 while ( my ( $value, $desc ) = $req->fetchrow ) {
134 push @bselect, $value;
135 $bselect{$value} = $desc;
137 my $Budgets = {
138 values => \@bselect,
139 labels => \%bselect,
142 $req =
143 $dbh->prepare(
144 "SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"
146 $req->execute;
147 my @s1select;
148 my %s1select;
149 my $hassort1;
150 while ( my ($value) = $req->fetchrow ) {
151 if ($value) {
152 $hassort1 = 1;
153 push @s1select, $value;
154 $s1select{$value} = $value;
157 my $Sort1 = {
158 values => \@s1select,
159 labels => \%s1select,
162 $req =
163 $dbh->prepare(
164 "SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"
166 $req->execute;
167 my @s2select;
168 my %s2select;
169 my $hassort2;
170 my $hglghtsort2;
172 while ( my ($value) = $req->fetchrow ) {
173 if ($value) {
174 $hassort2 = 1;
175 $hglghtsort2 = !($hassort1);
176 push @s2select, $value;
177 $s2select{$value} = $value;
180 my $Sort2 = {
181 values => \@s2select,
182 labels => \%s2select,
185 my $CGIsepChoice = GetDelimiterChoices;
187 my @branches = Koha::Libraries->search({}, { order_by => 'branchname' });
189 my $ccode_subfield_structure = GetMarcSubfieldStructureFromKohaField('items.ccode', '');
190 my $ccode_label;
191 my $ccode_avlist;
192 if($ccode_subfield_structure) {
193 $ccode_label = $ccode_subfield_structure->{liblibrarian};
194 $ccode_avlist = GetAuthorisedValues($ccode_subfield_structure->{authorised_value});
197 my $itemtypes = Koha::ItemTypes->search_with_localization;
198 $template->param(
199 booksellers => $booksellers,
200 itemtypes => $itemtypes, # FIXME Should use the TT plugin instead
201 Budgets => $Budgets,
202 hassort1 => $hassort1,
203 hassort2 => $hassort2,
204 Sort1 => $Sort1,
205 Sort2 => $Sort2,
206 CGIsepChoice => $CGIsepChoice,
207 branches => \@branches,
208 ccode_label => $ccode_label,
209 ccode_avlist => $ccode_avlist,
213 output_html_with_http_headers $input, $cookie, $template->output;
215 sub calculate {
216 my ( $line, $column, $podsp, $rodsp, $process, $filters ) = @_;
217 my @mainloop;
218 my @loopfooter;
219 my @loopcol;
220 my @loopline;
221 my @looprow;
222 my %globalline;
223 my $grantotal = 0;
225 $podsp ||= 0;
226 $rodsp ||= 0;
228 # extract parameters
229 my $dbh = C4::Context->dbh;
231 # Filters
232 # Checking filters
234 my @loopfilter;
235 for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
236 if( defined @$filters[$i] and @$filters[$i] ne '' ) {
237 my %cell;
238 if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) {
239 $cell{err} = 1 if ( @$filters[$i] lt @$filters[ $i - 1 ] );
241 # format the dates filters, otherwise just fill as is
242 if ($i >= 4) {
243 $cell{filter} = @$filters[$i];
244 } else {
245 $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
246 if ( @$filters[$i] );
248 $cell{crit} = $i;
249 push @loopfilter, \%cell;
253 my %filter;
254 my %field;
255 foreach ($line, $column) {
256 $filter{$_} = [];
257 $field{$_} = $_;
258 if ( $_ =~ /closedate/ ) {
259 $filter{$_}->[0] = @$filters[0];
260 $filter{$_}->[1] = @$filters[1];
261 my $a = $_;
262 if ( $podsp == 1 ) {
263 $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))";
264 } elsif ( $podsp == 2 ) {
265 $field{$a} = "concat(hex(month($a)),'-',monthname($a))";
266 } elsif ( $podsp == 3 ) {
267 $field{$a} = "Year($a)";
268 } else {
269 $field{$a} = $a;
272 elsif ( $_ =~ /received/ ) {
273 $filter{$_}->[0] = @$filters[2];
274 $filter{$_}->[1] = @$filters[3];
275 my $a = $_;
276 if ( $rodsp == 1 ) {
277 $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))";
278 } elsif ( $rodsp == 2 ) {
279 $field{$a} = "concat(hex(month($a)),'-',monthname($a))";
280 } elsif ( $rodsp == 3 ) {
281 $field{$a} = "Year($a)";
282 } else {
283 $field{$a} = $a;
286 elsif ( $_ =~ /bookseller/ ) {
287 $filter{$_}->[0] = @$filters[4];
289 elsif ( $_ =~ /homebranch/ ) {
290 $filter{$_}->[0] = @$filters[5];
292 elsif ( $_ =~ /ccode/ ) {
293 $filter{$_}->[0] = @$filters[6];
295 elsif ( $_ =~ /itemtype/ ) {
296 $filter{$_}->[0] = @$filters[7];
298 elsif ( $_ =~ /budget/ ) {
299 $filter{$_}->[0] = @$filters[8];
301 elsif ( $_ =~ /sort1/ ) {
302 $filter{$_}->[0] = @$filters[9];
304 elsif ( $_ =~ /sort2/ ) {
305 $filter{$_}->[0] = @$filters[10];
309 my @linefilter = @{ $filter{$line} };
310 my $linefield = $field{$line};
311 my @colfilter = @{ $filter{$column} };
312 my $colfield = $field{$column};
314 # 1st, loop rows.
315 my $strsth = "
316 SELECT DISTINCTROW $linefield
317 FROM aqorders
318 LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
319 LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
320 LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
321 LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
322 LEFT JOIN aqbudgets ON (aqorders.budget_id = aqbudgets.budget_id )
323 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
324 WHERE $line IS NOT NULL AND $line <> '' ";
326 if (@linefilter) {
327 if ( $linefilter[1] ) {
328 if ( $linefilter[0] ) {
329 $strsth .= " AND $line BETWEEN ? AND ? ";
331 else {
332 $strsth .= " AND $line <= ? ";
335 elsif (
336 ( $linefilter[0] )
337 and ( ( $line =~ /closedate/ )
338 or ( $line =~ /received/ ))
341 $strsth .= " AND $line >= ? ";
343 elsif ( $linefilter[0] ) {
344 $linefilter[0] =~ s/\*/%/g;
345 $strsth .= " AND $line LIKE ? ";
348 $strsth .= " GROUP BY $linefield";
349 $strsth .= " ORDER BY $line";
351 my $sth = $dbh->prepare($strsth);
352 if ( (@linefilter) and ( $linefilter[1] ) ) {
353 $sth->execute( $linefilter[0], $linefilter[1] );
355 elsif ( $linefilter[0] ) {
356 $sth->execute( $linefilter[0] );
358 else {
359 $sth->execute;
361 while ( my ($celvalue) = $sth->fetchrow ) {
362 my %cell;
363 if ($celvalue) {
364 $cell{rowtitle} = $celvalue;
365 push @loopline, \%cell;
367 $cell{totalrow} = 0;
370 # 2nd, loop cols.
371 my $strsth2 = "
372 SELECT DISTINCTROW $colfield
373 FROM aqorders
374 LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
375 LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
376 LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
377 LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
378 LEFT JOIN aqbudgets ON (aqorders.budget_id = aqbudgets.budget_id )
379 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
380 WHERE $column IS NOT NULL AND $column <> ''
383 if (@colfilter) {
384 if ( $colfilter[1] ) {
385 if ( $colfilter[0] ) {
386 $strsth2 .= " AND $column BETWEEN ? AND ? ";
388 else {
389 $strsth2 .= " AND $column <= ? ";
392 elsif (
393 ( $colfilter[0] )
394 and ( ( $column =~ /closedate/ )
395 or ( $line =~ /received/ ))
398 $strsth2 .= " AND $column >= ? ";
400 elsif ( $colfilter[0] ) {
401 $colfilter[0] =~ s/\*/%/g;
402 $strsth2 .= " AND $column LIKE ? ";
406 $strsth2 .= " GROUP BY $colfield";
407 $strsth2 .= " ORDER BY $colfield";
409 my $sth2 = $dbh->prepare($strsth2);
411 if ( (@colfilter) and ($colfilter[1]) ) {
412 $sth2->execute( $colfilter[0], $colfilter[1] );
414 elsif ( $colfilter[0] ) {
415 $sth2->execute( $colfilter[0] );
417 else {
418 $sth2->execute;
420 while ( my $celvalue = $sth2->fetchrow ) {
421 my %cell;
422 if ($celvalue) {
423 $cell{coltitle} = $celvalue;
424 push @loopcol, \%cell;
428 my $i = 0;
429 my @totalcol;
430 my $hilighted = -1;
432 #Initialization of cell values.....
433 my %table;
435 foreach my $row (@loopline) {
436 foreach my $col (@loopcol) {
437 $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0;
439 $table{ $row->{rowtitle} }->{totalrow} = 0;
442 # preparing calculation
443 my $strcalc;
444 $strcalc .= "SELECT $linefield, $colfield, ";
445 if ( $process == 1 ) {
446 $strcalc .= "COUNT(*) ";
447 } elsif ( $process == 2 ) {
448 $strcalc .= "COUNT(DISTINCT(aqorders.biblionumber)) ";
449 } elsif ( $process == 3 || $process == 4 || $process == 5 ) {
450 $strcalc .= "SUM(aqorders.listprice) ";
451 } else {
452 $strcalc .= "NULL ";
454 $strcalc .= "
455 FROM aqorders
456 LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
457 LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
458 LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
459 LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
460 LEFT JOIN aqbudgets ON (aqorders.budget_id = aqbudgets.budget_id )
461 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
462 WHERE aqorders.datecancellationprinted IS NULL ";
463 $strcalc .= " AND (aqorders.datereceived IS NULL OR aqorders.datereceived = '') "
464 if ( $process == 4 );
465 $strcalc .= " AND aqorders.datereceived IS NOT NULL AND aqorders.datereceived <> '' "
466 if ( $process == 5 );
467 @$filters[0] =~ s/\*/%/g if ( @$filters[0] );
468 $strcalc .= " AND aqbasket.closedate >= '" . @$filters[0] . "'"
469 if ( @$filters[0] );
470 @$filters[1] =~ s/\*/%/g if ( @$filters[1] );
471 $strcalc .= " AND aqbasket.closedate <= '" . @$filters[1] . "'"
472 if ( @$filters[1] );
473 @$filters[2] =~ s/\*/%/g if ( @$filters[2] );
474 $strcalc .= " AND aqorders.datereceived >= '" . @$filters[2] . "'"
475 if ( @$filters[2] );
476 @$filters[3] =~ s/\*/%/g if ( @$filters[3] );
477 $strcalc .= " AND aqorders.datereceived <= '" . @$filters[3] . "'"
478 if ( @$filters[3] );
479 @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
480 $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[4] . "'"
481 if ( @$filters[4] );
482 $strcalc .= " AND items.homebranch = '" . @$filters[5] . "'"
483 if ( @$filters[5] );
484 @$filters[6] =~ s/\*/%/g if ( @$filters[6] );
485 $strcalc .= " AND items.ccode = '" . @$filters[6] . "'"
486 if ( @$filters[6] );
487 @$filters[7] =~ s/\*/%/g if ( @$filters[7] );
488 $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[7] . "'"
489 if ( @$filters[7] );
490 @$filters[8] =~ s/\*/%/g if ( @$filters[8] );
491 $strcalc .= " AND aqbudgets.budget_code LIKE '" . @$filters[8] . "'"
492 if ( @$filters[8] );
493 @$filters[9] =~ s/\*/%/g if ( @$filters[9] );
494 $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[9] . "'"
495 if ( @$filters[9] );
496 @$filters[10] =~ s/\*/%/g if ( @$filters[10] );
497 $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[10] . "'"
498 if ( @$filters[10] );
500 $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield";
501 my $dbcalc = $dbh->prepare($strcalc);
502 $dbcalc->execute;
504 my $emptycol;
505 while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
506 $emptycol = 1 if ( !defined($col) );
507 $col = "zzEMPTY" if ( !defined($col) );
508 $row = "zzEMPTY" if ( !defined($row) );
510 $table{$row}->{$col} += $value;
511 $table{$row}->{totalrow} += $value;
512 $grantotal += $value;
515 push @loopcol, { coltitle => "NULL" } if ($emptycol);
517 foreach my $row ( sort keys %table ) {
518 my @loopcell;
519 #@loopcol ensures the order for columns is common with column titles
520 # and the number matches the number of columns
521 foreach my $col (@loopcol) {
522 my $value = $table{$row}->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} };
523 $value = sprintf("%.2f", $value) if($value and grep /$process/, (3,4,5));
524 push @loopcell, { value => $value };
526 my $r = {
527 rowtitle => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
528 loopcell => \@loopcell,
529 hilighted => ( $hilighted > 0 ),
530 totalrow => $table{$row}->{totalrow}
532 $r->{totalrow} = sprintf("%.2f", $r->{totalrow}) if($r->{totalrow} and grep /$process/, (3,4,5));
533 push @looprow, $r;
534 $hilighted = -$hilighted;
537 foreach my $col (@loopcol) {
538 my $total = 0;
539 foreach my $row (@looprow) {
540 $total += $table{
541 ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY"
542 : $row->{rowtitle}
543 }->{
544 ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY"
545 : $col->{coltitle}
548 $total = sprintf("%.2f", $total) if($total and grep /$process/, (3,4,5));
550 push @loopfooter, { 'totalcol' => $total };
553 # the header of the table
554 $globalline{loopfilter} = \@loopfilter;
555 # the core of the table
556 $globalline{looprow} = \@looprow;
557 $globalline{loopcol} = \@loopcol;
559 # # the foot (totals by borrower type)
560 $grantotal = sprintf("%.2f", $grantotal) if ($grantotal and grep /$process/, (3,4,5));
561 $globalline{loopfooter} = \@loopfooter;
562 $globalline{total} = $grantotal;
563 $globalline{line} = $line;
564 $globalline{column} = $column;
565 push @mainloop, \%globalline;
566 return \@mainloop;