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