Bug 7896: Acq statistics wizard: add filters and cell values
[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 @select;
121     my %select;
122     my $req;
123     $req = $dbh->prepare("SELECT distinctrow id,name FROM aqbooksellers ORDER BY name");
124     $req->execute;
125     push @select, "";
126     $select{''} = "All Suppliers";
127     while ( my ( $value, $desc ) = $req->fetchrow ) {
128         push @select, $desc;
129         $select{$value}=$desc;
130     }
131     my $CGIBookSellers = CGI::scrolling_list(
132         -name   => 'Filter',
133         -id     => 'supplier',
134         -values => \@select,
135         -labels   => \%select,
136         -size     => 1,
137         -multiple => 0
138     );
139
140     $req = $dbh->prepare("SELECT DISTINCTROW itemtype,description FROM itemtypes ORDER BY description");
141     $req->execute;
142     undef @select;
143     undef %select;
144     push @select, "";
145     $select{''} = "All Item Types";
146     while ( my ( $value, $desc ) = $req->fetchrow ) {
147         push @select, $value;
148         $select{$value} = $desc;
149     }
150     my $CGIItemTypes = CGI::scrolling_list(
151         -name     => 'Filter',
152         -id       => 'itemtypes',
153         -values   => \@select,
154         -labels   => \%select,
155         -size     => 1,
156         -multiple => 0
157     );
158
159     $req = $dbh->prepare("SELECT DISTINCTROW budget_code, budget_name FROM aqbudgets ORDER BY budget_name");
160     $req->execute;
161     undef @select;
162     undef %select;
163     push @select, "";
164     $select{''} = "All budgets";
165
166     while ( my ( $value, $desc ) = $req->fetchrow ) {
167         push @select, $value;
168         $select{$value} = $desc;
169     }
170     my $CGIBudget = CGI::scrolling_list(
171         -name     => 'Filter',
172         -id       => 'budget',
173         -values   => \@select,
174         -labels   => \%select,
175         -size     => 1,
176         -multiple => 0
177     );
178
179     $req =
180       $dbh->prepare(
181 "SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"
182       );
183     $req->execute;
184     undef @select;
185     undef %select;
186     push @select, "";
187     $select{''} = "All";
188     my $hassort1;
189     while ( my ($value) = $req->fetchrow ) {
190         if ($value) {
191             $hassort1 = 1;
192             push @select, $value;
193             $select{$value} = $value;
194         }
195     }
196     my $CGISort1 = CGI::scrolling_list(
197         -name     => 'Filter',
198         -id       => 'sort1',
199         -values   => \@select,
200         -labels   => \%select,
201         -size     => 1,
202         -multiple => 0
203     );
204
205     $req =
206       $dbh->prepare(
207 "SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"
208       );
209     $req->execute;
210     undef @select;
211     undef %select;
212     push @select, "";
213     $select{''} = "All";
214     my $hassort2;
215     my $hglghtsort2;
216
217     while ( my ($value) = $req->fetchrow ) {
218         if ($value) {
219             $hassort2    = 1;
220             $hglghtsort2 = !($hassort1);
221             push @select, $value;
222             $select{$value} = $value;
223         }
224     }
225     my $CGISort2 = CGI::scrolling_list(
226         -name     => 'Filter',
227         -id       => 'sort2',
228         -values   => \@select,
229         -labels   => \%select,
230         -size     => 1,
231         -multiple => 0
232     );
233
234     my $CGIextChoice = CGI::scrolling_list(
235         -name     => 'MIME',
236         -id       => 'MIME',
237         -values   => ['CSV'], # FIXME translation
238         -size     => 1,
239         -multiple => 0
240     );
241
242     my $CGIsepChoice = GetDelimiterChoices;
243
244     my $branches = GetBranches;
245     my @branches;
246     foreach ( sort keys %$branches ) {
247         push @branches, $branches->{$_};
248     }
249
250     my $ccode_subfield_structure = GetMarcSubfieldStructureFromKohaField('items.ccode', '');
251     my $ccode_label;
252     my $ccode_avlist;
253     if($ccode_subfield_structure) {
254         $ccode_label = $ccode_subfield_structure->{liblibrarian};
255         $ccode_avlist = GetAuthorisedValues($ccode_subfield_structure->{authorised_value});
256     }
257
258     $template->param(
259         CGIBookSeller => $CGIBookSellers,
260         CGIItemType   => $CGIItemTypes,
261         CGIBudget     => $CGIBudget,
262         hassort1      => $hassort1,
263         hassort2      => $hassort2,
264         CGISort1      => $CGISort1,
265         CGISort2      => $CGISort2,
266         CGIextChoice  => $CGIextChoice,
267         CGIsepChoice  => $CGIsepChoice,
268         branches      => \@branches,
269         ccode_label   => $ccode_label,
270         ccode_avlist  => $ccode_avlist,
271     );
272
273 }
274 output_html_with_http_headers $input, $cookie, $template->output;
275
276 sub calculate {
277     my ( $line, $column, $podsp, $rodsp, $process, $filters ) = @_;
278     my @mainloop;
279     my @loopfooter;
280     my @loopcol;
281     my @loopline;
282     my @looprow;
283     my %globalline;
284     my $grantotal = 0;
285
286     $podsp ||= 0;
287     $rodsp ||= 0;
288
289     # extract parameters
290     my $dbh = C4::Context->dbh;
291
292     # Filters
293     # Checking filters
294     #
295     my @loopfilter;
296     for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
297         if( defined @$filters[$i] and @$filters[$i] ne '' ) {
298             my %cell;
299             if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) {
300                 $cell{err} = 1 if ( @$filters[$i] lt @$filters[ $i - 1 ] );
301             }
302             # format the dates filters, otherwise just fill as is
303             if ($i >= 4) {
304                 $cell{filter} = @$filters[$i];
305             } else {
306                 $cell{filter} = format_date(@$filters[$i]);
307             }
308             given ($i) {
309                 when (0)  { $cell{crit} = "Placed On From" }
310                 when (1)  { $cell{crit} = "Placed On To" }
311                 when (2)  { $cell{crit} = "Received On From" }
312                 when (3)  { $cell{crit} = "Received On To" }
313                 when (4)  { $cell{crit} = "Bookseller" }
314                 when (5)  { $cell{crit} = "Home branch" }
315                 when (6)  { $cell{crit} = "Collection" }
316                 when (7)  { $cell{crit} = "Doc Type" }
317                 when (8)  { $cell{crit} = "Budget" }
318                 when (9)  { $cell{crit} = "Sort1" }
319                 when (10) { $cell{crit} = "Sort2" }
320                 default   { $cell{crit} = "" }
321             }
322             push @loopfilter, \%cell;
323         }
324     }
325
326     my %filter;
327     my %field;
328     foreach ($line, $column) {
329         $filter{$_} = [];
330         $field{$_} = $_;
331         given ($_) {
332             when (/closedate/) {
333                 $filter{$_}->[0] = @$filters[0];
334                 $filter{$_}->[1] = @$filters[1];
335                 my $a = $_;
336                 given ($podsp) {
337                     when (1) { $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))" }
338                     when (2) { $field{$a} = "concat(hex(month($a)),'-',monthname($a))" }
339                     when (3) { $field{$a} = "Year($a)" }
340                     default  { $field{$a} = $a }
341                 }
342             }
343             when (/received/) {
344                 $filter{$_}->[0] = @$filters[2];
345                 $filter{$_}->[1] = @$filters[3];
346                 my $a = $_;
347                 given ($rodsp) {
348                     when (1) { $field{$a} = "concat(hex(weekday($a)+1),'-',dayname($a))" }
349                     when (2) { $field{$a} = "concat(hex(month($a)),'-',monthname($a))" }
350                     when (3) { $field{$a} = "Year($a)" }
351                     default  { $field{$a} = $a }
352                 }
353             }
354             when (/bookseller/) {
355                 $filter{$_}->[0] = @$filters[4];
356             }
357             when (/homebranch/) {
358                 $filter{$_}->[0] = @$filters[5];
359             }
360             when (/ccode/) {
361                 $filter{$_}->[0] = @$filters[6];
362             }
363             when (/itemtype/) {
364                 $filter{$_}->[0] = @$filters[7];
365             }
366             when (/budget/) {
367                 $filter{$_}->[0] = @$filters[8];
368             }
369             when (/sort1/) {
370                 $filter{$_}->[0] = @$filters[9];
371             }
372             when (/sort2/) {
373                 $filter{$_}->[0] = @$filters[10];
374             }
375         }
376     }
377
378     my @linefilter = @{ $filter{$line} };
379     my $linefield = $field{$line};
380     my @colfilter = @{ $filter{$column} };
381     my $colfield = $field{$column};
382
383     # 1st, loop rows.
384     my $strsth = "
385         SELECT DISTINCTROW $linefield
386         FROM aqorders
387           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
388           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
389           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
390           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
391           LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
392           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
393         WHERE $line IS NOT NULL AND $line <> '' ";
394
395     if (@linefilter) {
396         if ( $linefilter[1] ) {
397             if ( $linefilter[0] ) {
398                 $strsth .= " AND $line BETWEEN ? AND ? ";
399             }
400             else {
401                 $strsth .= " AND $line <= ? ";
402             }
403         }
404         elsif (
405             ( $linefilter[0] )
406             and (  ( $line =~ /closedate/ )
407                 or ( $line =~ /received/ ))
408           )
409         {
410             $strsth .= " AND $line >= ? ";
411         }
412         elsif ( $linefilter[0] ) {
413             $linefilter[0] =~ s/\*/%/g;
414             $strsth .= " AND $line LIKE ? ";
415         }
416     }
417     $strsth .= " GROUP BY $linefield";
418     $strsth .= " ORDER BY $line";
419
420     my $sth = $dbh->prepare($strsth);
421     if ( (@linefilter) and ( $linefilter[1] ) ) {
422         $sth->execute( $linefilter[0], $linefilter[1] );
423     }
424     elsif ( $linefilter[0] ) {
425         $sth->execute( $linefilter[0] );
426     }
427     else {
428         $sth->execute;
429     }
430     while ( my ($celvalue) = $sth->fetchrow ) {
431         my %cell;
432         if ($celvalue) {
433             $cell{rowtitle} = $celvalue;
434             push @loopline, \%cell;
435         }
436         $cell{totalrow} = 0;
437     }
438
439     # 2nd, loop cols.
440     my $strsth2 = "
441         SELECT DISTINCTROW $colfield
442         FROM aqorders
443           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
444           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
445           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
446           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
447           LEFT JOIN aqbudgets  ON (aqorders.budget_id = aqbudgets.budget_id )
448           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
449         WHERE $column IS NOT NULL AND $column <> ''
450     ";
451
452     if (@colfilter) {
453         if ( $colfilter[1] ) {
454             if ( $colfilter[0] ) {
455                 $strsth2 .= " AND $column BETWEEN  ? AND ? ";
456             }
457             else {
458                 $strsth2 .= " AND $column <= ? ";
459             }
460         }
461         elsif (
462             ( $colfilter[0] )
463             and (  ( $column =~ /closedate/ )
464                 or ( $line =~ /received/ ))
465           )
466         {
467             $strsth2 .= " AND $column >= ? ";
468         }
469         elsif ( $colfilter[0] ) {
470             $colfilter[0] =~ s/\*/%/g;
471             $strsth2 .= " AND $column LIKE ? ";
472         }
473     }
474
475     $strsth2 .= " GROUP BY $colfield";
476     $strsth2 .= " ORDER BY $colfield";
477
478     my $sth2 = $dbh->prepare($strsth2);
479
480     if ( (@colfilter) and ($colfilter[1]) ) {
481         $sth2->execute( $colfilter[0], $colfilter[1] );
482     }
483     elsif ( $colfilter[0] ) {
484         $sth2->execute( $colfilter[0] );
485     }
486     else {
487         $sth2->execute;
488     }
489     while ( my $celvalue = $sth2->fetchrow ) {
490         my %cell;
491         if ($celvalue) {
492             $cell{coltitle} = $celvalue;
493             push @loopcol, \%cell;
494         }
495     }
496
497     my $i = 0;
498     my @totalcol;
499     my $hilighted = -1;
500
501     #Initialization of cell values.....
502     my %table;
503
504     foreach my $row (@loopline) {
505         foreach my $col (@loopcol) {
506             $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0;
507         }
508         $table{ $row->{rowtitle} }->{totalrow} = 0;
509     }
510
511     # preparing calculation
512     my $strcalc;
513     $strcalc .= "SELECT $linefield, $colfield, ";
514     given ($process) {
515         when (1) { $strcalc .= "COUNT(*) " }
516         when (2) { $strcalc .= "COUNT(DISTINCT(aqorders.biblionumber)) " }
517         when ([3,4,5]) { $strcalc .= "SUM(aqorders.listprice) " }
518         default { $strcalc .= "NULL " }
519     }
520     $strcalc .= "
521         FROM aqorders
522           LEFT JOIN aqbasket ON (aqorders.basketno = aqbasket.basketno)
523           LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber)
524           LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber)
525           LEFT JOIN biblioitems ON (aqorders.biblionumber = biblioitems.biblionumber)
526           LEFT JOIN aqbudgets ON (aqorders.budget_id = aqbudgets.budget_id )
527           LEFT JOIN aqbooksellers ON (aqbasket.booksellerid = aqbooksellers.id)
528         WHERE aqorders.datecancellationprinted IS NULL ";
529     $strcalc .= " AND (aqorders.datereceived IS NULL OR aqorders.datereceived = '') "
530         if ( $process == 4 );
531     $strcalc .= " AND aqorders.datereceived IS NOT NULL AND aqorders.datereceived <> '' "
532         if ( $process == 5 );
533     @$filters[0] =~ s/\*/%/g if ( @$filters[0] );
534     $strcalc .= " AND aqbasket.closedate >= '" . @$filters[0] . "'"
535       if ( @$filters[0] );
536     @$filters[1] =~ s/\*/%/g if ( @$filters[1] );
537     $strcalc .= " AND aqbasket.closedate <= '" . @$filters[1] . "'"
538       if ( @$filters[1] );
539     @$filters[2] =~ s/\*/%/g if ( @$filters[2] );
540     $strcalc .= " AND aqorders.datereceived >= '" . @$filters[2] . "'"
541       if ( @$filters[2] );
542     @$filters[3] =~ s/\*/%/g if ( @$filters[3] );
543     $strcalc .= " AND aqorders.datereceived <= '" . @$filters[3] . "'"
544       if ( @$filters[3] );
545     @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
546     $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[4] . "'"
547       if ( @$filters[4] );
548     $strcalc .= " AND items.homebranch = '" . @$filters[5] . "'"
549       if ( @$filters[5] );
550     @$filters[6] =~ s/\*/%/g if ( @$filters[6] );
551     $strcalc .= " AND items.ccode = '" . @$filters[6] . "'"
552       if ( @$filters[6] );
553     @$filters[7] =~ s/\*/%/g if ( @$filters[7] );
554     $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[7] . "'"
555       if ( @$filters[7] );
556     @$filters[8] =~ s/\*/%/g if ( @$filters[8] );
557     $strcalc .= " AND aqbudgets.budget_code LIKE '" . @$filters[8] . "'"
558       if ( @$filters[8] );
559     @$filters[9] =~ s/\*/%/g if ( @$filters[9] );
560     $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[9] . "'"
561       if ( @$filters[9] );
562     @$filters[10] =~ s/\*/%/g if ( @$filters[10] );
563     $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[10] . "'"
564       if ( @$filters[10] );
565
566     $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield";
567     my $dbcalc = $dbh->prepare($strcalc);
568     $dbcalc->execute;
569
570     my $emptycol;
571     while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
572         $emptycol = 1         if ( !defined($col) );
573         $col      = "zzEMPTY" if ( !defined($col) );
574         $row      = "zzEMPTY" if ( !defined($row) );
575
576         $table{$row}->{$col}     += $value;
577         $table{$row}->{totalrow} += $value;
578         $grantotal               += $value;
579     }
580
581     push @loopcol, { coltitle => "NULL" } if ($emptycol);
582
583     foreach my $row ( sort keys %table ) {
584         my @loopcell;
585         #@loopcol ensures the order for columns is common with column titles
586         # and the number matches the number of columns
587         foreach my $col (@loopcol) {
588             my $value = $table{$row}->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} };
589             $value = sprintf("%.2f", $value) if($value and grep /$process/, (3,4,5));
590             push @loopcell, { value => $value };
591         }
592         my $r = {
593             rowtitle => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
594             loopcell  => \@loopcell,
595             hilighted => ( $hilighted > 0 ),
596             totalrow  => $table{$row}->{totalrow}
597         };
598         $r->{totalrow} = sprintf("%.2f", $r->{totalrow}) if($r->{totalrow} and grep /$process/, (3,4,5));
599         push @looprow, $r;
600         $hilighted = -$hilighted;
601     }
602
603     foreach my $col (@loopcol) {
604         my $total = 0;
605         foreach my $row (@looprow) {
606             $total += $table{
607                 ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY"
608                 : $row->{rowtitle}
609               }->{
610                 ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY"
611                 : $col->{coltitle}
612               };
613         }
614         $total = sprintf("%.2f", $total) if($total and grep /$process/, (3,4,5));
615
616         push @loopfooter, { 'totalcol' => $total };
617     }
618
619     # the header of the table
620     $globalline{loopfilter} = \@loopfilter;
621     # the core of the table
622     $globalline{looprow} = \@looprow;
623     $globalline{loopcol} = \@loopcol;
624
625     #       # the foot (totals by borrower type)
626     $grantotal = sprintf("%.2f", $grantotal) if ($grantotal and grep /$process/, (3,4,5));
627     $globalline{loopfooter} = \@loopfooter;
628     $globalline{total}      = $grantotal;
629     $globalline{line}       = $line;
630     $globalline{column}     = $column;
631     push @mainloop, \%globalline;
632     return \@mainloop;
633 }
634
635 1;
636