b7b01e23d8891756b6b890fec9bcc112186183fe
[srvgit] / reports / catalogue_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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22 use C4::Auth;
23 use CGI qw ( -utf8 );
24 use C4::Context;
25 use C4::Output;
26 use C4::Koha;
27 use C4::Reports;
28 use C4::Circulation;
29 use C4::Biblio qw/GetMarcSubfieldStructureFromKohaField/;
30
31 use Koha::AuthorisedValues;
32 use Koha::DateUtils;
33 use Koha::ItemTypes;
34
35 =head1 NAME
36
37 plugin that shows a stats on borrowers
38
39 =head1 DESCRIPTION
40
41 =cut
42
43 our $debug = 0;
44 my $input = CGI->new;
45 my $fullreportname = "reports/catalogue_stats.tt";
46 my $do_it       = $input->param('do_it');
47 my $line        = $input->param("Line");
48 my $column      = $input->param("Column");
49 my $cellvalue      = $input->param("Cellvalue"); # one of 'items', 'biblios', 'deleteditems'
50 my @filters     = $input->multi_param("Filter");
51 my $cotedigits  = $input->param("cotedigits");
52 my $output      = $input->param("output");
53 my $basename    = $input->param("basename");
54 our $sep        = $input->param("sep");
55 $sep = "\t" if ($sep eq 'tabulation');
56 my $item_itype;
57 if(C4::Context->preference('item-level_itypes')) {
58         $item_itype = "items\.itype"
59 } else {
60         $item_itype = "itemtype";
61 }
62 if(C4::Context->preference('marcflavour') ne "UNIMARC" && ($line=~ /publicationyear/ )) {
63     $line = "copyrightdate";
64 }
65 if(C4::Context->preference('marcflavour') ne "UNIMARC" && ($column =~ /publicationyear/ )) {
66     $column = "copyrightdate";
67 }
68
69 my ($template, $borrowernumber, $cookie)
70         = get_template_and_user({template_name => $fullreportname,
71                                 query => $input,
72                                 type => "intranet",
73                                 flagsrequired => {reports => '*'},
74                                 });
75 $template->param(do_it => $do_it);
76 if ($do_it) {
77     my $results = calculate( $line, $column, $cellvalue, $cotedigits, \@filters );
78     if ( $output eq "screen" ) {
79         $template->param( mainloop => $results );
80         output_html_with_http_headers $input, $cookie, $template->output;
81         exit;
82     } else {
83         print $input->header(
84             -type       => 'text/csv',
85             -encoding   => 'utf-8',
86             -attachment => "$basename.csv",
87             -name       => "$basename.csv"
88         );
89         my $cols  = @$results[0]->{loopcol};
90         my $lines = @$results[0]->{looprow};
91         print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
92         foreach my $col (@$cols) {
93             print $col->{coltitle} . $sep;
94         }
95         print "Total\n";
96         foreach my $line (@$lines) {
97             my $x = $line->{loopcell};
98             print $line->{rowtitle} . $sep;
99             foreach my $cell (@$x) {
100                 print $cell->{value} . $sep;
101             }
102             print $line->{totalrow};
103             print "\n";
104         }
105         print "TOTAL";
106         $cols = @$results[0]->{loopfooter};
107         foreach my $col (@$cols) {
108             print $sep. $col->{totalcol};
109         }
110         print $sep. @$results[0]->{total};
111         exit;
112     }
113 } else {
114         my $dbh = C4::Context->dbh;
115         my $count=0;
116
117     my $itemtypes = Koha::ItemTypes->search_with_localization;
118
119     my @authvals = map { { code => $_->{authorised_value}, description => $_->{lib} } } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } );
120     my @locations = map { { code => $_->{authorised_value}, description => $_->{lib} } } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } );
121
122     foreach my $kohafield (qw(items.notforloan items.materials)) {
123         my $subfield_structure = GetMarcSubfieldStructureFromKohaField($kohafield);
124         if($subfield_structure) {
125             my $avlist;
126             my $avcategory = $subfield_structure->{authorised_value};
127             if($avcategory) {
128                 $avlist = GetAuthorisedValues($avcategory);
129             }
130             my $kf = $kohafield;
131             $kf =~ s/^items\.//;
132             $template->param(
133                 $kf => 1,
134                 $kf."_label" => $subfield_structure->{liblibrarian},
135                 $kf."_avlist" => $avlist
136             );
137         }
138     }
139
140     my @mime  = ( map { +{type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation
141
142     $template->param(
143         itemtypes    => $itemtypes,
144         locationloop => \@locations,
145         authvals     => \@authvals,
146         CGIextChoice => \@mime,
147         CGIsepChoice => GetDelimiterChoices,
148         item_itype   => $item_itype,
149     );
150
151 }
152 output_html_with_http_headers $input, $cookie, $template->output;
153
154 ## End of Main Body
155
156
157 sub calculate {
158     my ( $line, $column, $cellvalue, $cotedigits, $filters ) = @_;
159     my @mainloop;
160     my @loopfooter;
161     my @loopcol;
162     my @loopline;
163     my @looprow;
164     my %globalline;
165     my $grantotal     = 0;
166     my $barcodelike   = @$filters[16];
167     my $barcodefilter = @$filters[17];
168     my $not;
169     my $itemstable = ($cellvalue eq 'deleteditems') ? 'deleteditems' : 'items';
170
171     my $dbh = C4::Context->dbh;
172
173     # if barcodefilter is empty set as %
174     if ($barcodefilter) {
175
176         # Check if barcodefilter is "like" or "not like"
177         if ( !$barcodelike ) {
178             $not = "not";
179         }
180
181         # Change * to %
182         $barcodefilter =~ s/\*/%/g;
183     }
184
185     # Filters
186     # Checking filters
187     #
188     my @loopfilter;
189     for ( my $i = 0 ; $i <= @$filters ; $i++ ) {
190         my %cell;
191         if ( defined @$filters[$i] and @$filters[$i] ne '' and $i != 11 ) {
192             if ( ( ( $i == 1 ) or ( $i == 5 ) ) and ( @$filters[ $i - 1 ] ) ) {
193                 $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
194             }
195             $cell{filter} .= @$filters[$i];
196             $cell{crit} .=
197                 ( $i == 0 )  ? "Item CallNumber From"
198               : ( $i == 1 )  ? "Item CallNumber To"
199               : ( $i == 2 )  ? "Item type"
200               : ( $i == 3 )  ? "Publisher"
201               : ( $i == 4 )  ? "Publication year From"
202               : ( $i == 5 )  ? "Publication year To"
203               : ( $i == 6 ) ? "Library"
204               : ( $i == 7 ) ? "Shelving Location"
205               : ( $i == 8 ) ? "Collection Code"
206               : ( $i == 9 ) ? "Status"
207               : ( $i == 10 ) ? "Materials"
208               : ( $i == 12 and $filters->[11] == 0 ) ? "Barcode (not like)"
209               : ( $i == 12 and $filters->[11] == 1 ) ? "Barcode (like)"
210               : ( $i == 13 ) ? "Date acquired (item) from"
211               : ( $i == 14 ) ? "Date acquired (item) to"
212               : ( $i == 15 ) ? "Date deleted (item) from"
213               : ( $i == 16 ) ? "Date deleted (item) to"
214               :                '';
215
216             push @loopfilter, \%cell;
217         }
218     }
219
220     @$filters[13] = dt_from_string(@$filters[13])->date() if @$filters[13];
221     @$filters[14] = dt_from_string(@$filters[14])->date() if @$filters[14];
222     @$filters[15] = dt_from_string(@$filters[15])->date() if @$filters[15];
223     @$filters[16] = dt_from_string(@$filters[16])->date() if @$filters[16];
224
225     my @linefilter;
226     $linefilter[0] = @$filters[0] if ( $line =~ /items\.itemcallnumber/ );
227     $linefilter[1] = @$filters[1] if ( $line =~ /items\.itemcallnumber/ );
228     if ( C4::Context->preference('item-level_itypes') ) {
229         $linefilter[0] = @$filters[2] if ( $line =~ /items\.itype/ );
230     } else {
231         $linefilter[0] = @$filters[2] if ( $line =~ /itemtype/ );
232     }
233     $linefilter[0] = @$filters[3] if ( $line =~ /publishercode/ );
234     $linefilter[0] = @$filters[4] if ( $line =~ /publicationyear/ );
235     $linefilter[1] = @$filters[5] if ( $line =~ /publicationyear/ );
236
237     $linefilter[0] = @$filters[6] if ( $line =~ /items\.homebranch/ );
238     $linefilter[0] = @$filters[7] if ( $line =~ /items\.location/ );
239     $linefilter[0] = @$filters[8] if ( $line =~ /items\.ccode/ );
240     $linefilter[0] = @$filters[9] if ( $line =~ /items\.notforloan/ );
241     $linefilter[0] = @$filters[10] if ( $line =~ /items\.materials/ );
242     $linefilter[0] = @$filters[13] if ( $line =~ /items\.dateaccessioned/ );
243     $linefilter[1] = @$filters[14] if ( $line =~ /items\.dateaccessioned/ );
244     $linefilter[0] = @$filters[15] if ( $line =~ /deleteditems\.timestamp/ );
245     $linefilter[1] = @$filters[16] if ( $line =~ /deleteditems\.timestamp/ );
246
247     my @colfilter;
248     $colfilter[0] = @$filters[0] if ( $column =~ /items\.itemcallnumber/ );
249     $colfilter[1] = @$filters[1] if ( $column =~ /items\.itemcallnumber/ );
250     if ( C4::Context->preference('item-level_itypes') ) {
251         $colfilter[0] = @$filters[2] if ( $column =~ /items\.itype/ );
252     } else {
253         $colfilter[0] = @$filters[2] if ( $column =~ /itemtype/ );
254     }
255     $colfilter[0] = @$filters[3]  if ( $column =~ /publishercode/ );
256     $colfilter[0] = @$filters[4]  if ( $column =~ /publicationyear/ );
257     $colfilter[1] = @$filters[5]  if ( $column =~ /publicationyear/ );
258     $colfilter[0] = @$filters[6] if ( $column =~ /items\.homebranch/ );
259     $colfilter[0] = @$filters[7] if ( $column =~ /items\.location/ );
260     $colfilter[0] = @$filters[8] if ( $column =~ /items\.ccode/ );
261     $colfilter[0] = @$filters[9] if ( $column =~ /items\.notforloan/ );
262     $colfilter[0] = @$filters[10] if ( $column =~ /items\.materials/ );
263     $colfilter[0] = @$filters[13] if ( $column =~ /items.dateaccessioned/ );
264     $colfilter[1] = @$filters[14] if ( $column =~ /items\.dateaccessioned/ );
265     $colfilter[0] = @$filters[15] if ( $column =~ /deleteditems\.timestamp/ );
266     $colfilter[1] = @$filters[16] if ( $column =~ /deleteditems\.timestamp/ );
267
268     # 1st, loop rows.
269     my $origline = $line;
270     $line =~ s/^items\./deleteditems./ if($cellvalue eq "deleteditems");
271     my $linefield;
272     if ( ( $line =~ /itemcallnumber/ ) and ($cotedigits) ) {
273         $linefield = "left($line,$cotedigits)";
274     } elsif ( $line =~ /^deleteditems\.timestamp$/ ) {
275         $linefield = "DATE($line)";
276     } else {
277         $linefield = $line;
278     }
279
280     my $strsth = "SELECT DISTINCTROW $linefield FROM $itemstable
281                     LEFT JOIN biblioitems USING (biblioitemnumber)
282                     LEFT JOIN biblio ON (biblioitems.biblionumber = biblio.biblionumber)
283                   WHERE 1 ";
284     $strsth .= " AND barcode $not LIKE ? " if ($barcodefilter);
285     if (@linefilter) {
286         if ( $linefilter[1] ) {
287             $strsth .= " AND $line >= ? ";
288             $strsth .= " AND $line <= ? ";
289         } elsif ( defined $linefilter[0] and $linefilter[0] ne '' ) {
290             $linefilter[0] =~ s/\*/%/g;
291             $strsth .= " AND $line LIKE ? ";
292         }
293     }
294     $strsth .= " ORDER BY $linefield";
295     $debug and print STDERR "catalogue_stats SQL: $strsth\n";
296
297     my $sth = $dbh->prepare($strsth);
298     if ( $barcodefilter and (@linefilter) and ( $linefilter[1] ) ) {
299         $sth->execute( $barcodefilter, $linefilter[0], $linefilter[1] );
300     } elsif ( (@linefilter) and ( $linefilter[1] ) ) {
301         $sth->execute( $linefilter[0], $linefilter[1] );
302     } elsif ( $barcodefilter and $linefilter[0] ) {
303         $sth->execute( $barcodefilter, $linefilter[0] );
304     } elsif ( $linefilter[0] ) {
305         $sth->execute($linefilter[0]);
306     } elsif ($barcodefilter) {
307         $sth->execute($barcodefilter);
308     } else {
309         $sth->execute();
310     }
311     my $rowauthvals = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origline } ) };
312     while ( my ($celvalue) = $sth->fetchrow ) {
313         my %cell;
314         if (defined $celvalue and $celvalue ne '') {
315             if($rowauthvals and $rowauthvals->{$celvalue}) {
316                 $cell{rowtitle} = $rowauthvals->{$celvalue};
317             } else {
318                 $cell{rowtitle} = $celvalue;
319             }
320             $cell{value} = $celvalue;
321         }
322         else {
323             $cell{rowtitle} = "NULL";
324             $cell{value} = "zzEMPTY";
325         }
326         $cell{totalrow} = 0;
327         push @loopline, \%cell;
328     }
329
330     # 2nd, loop cols.
331     my $origcolumn = $column;
332     $column =~ s/^items\./deleteditems./ if($cellvalue eq "deleteditems");
333     my $colfield;
334     if ( ( $column =~ /itemcallnumber/ ) and ($cotedigits) ) {
335         $colfield = "left($column,$cotedigits)";
336     } elsif ( $column =~ /^deleteditems\.timestamp$/ ) {
337         $colfield = "DATE($column)";
338     } else {
339         $colfield = $column;
340     }
341
342     my $strsth2 = "
343         SELECT distinctrow $colfield
344         FROM   $itemstable
345         LEFT JOIN biblioitems
346             USING (biblioitemnumber)
347         LEFT JOIN biblio
348             ON (biblioitems.biblionumber = biblio.biblionumber)
349         WHERE 1 ";
350     $strsth2 .= " AND barcode $not LIKE ?" if $barcodefilter;
351
352     if ( (@colfilter) and ( $colfilter[1] ) ) {
353         $strsth2 .= " AND $column >= ? AND $column <= ?";
354     } elsif ( defined $colfilter[0] and $colfilter[0] ne '' ) {
355         $colfilter[0] =~ s/\*/%/g;
356         $strsth2 .= " AND $column LIKE ? ";
357     }
358     $strsth2 .= " ORDER BY $colfield";
359     $debug and print STDERR "SQL: $strsth2";
360     my $sth2 = $dbh->prepare($strsth2);
361     if ( $barcodefilter and (@colfilter) and ( $colfilter[1] ) ) {
362         $sth2->execute( $barcodefilter, $colfilter[0], $colfilter[1] );
363     } elsif ( (@colfilter) and ( $colfilter[1] ) ) {
364         $sth2->execute( $colfilter[0], $colfilter[1] );
365     } elsif ( $barcodefilter && $colfilter[0] ) {
366         $sth2->execute( $barcodefilter , $colfilter[0] );
367     } elsif ( $colfilter[0]) {
368         $sth2->execute( $colfilter[0] );
369     } elsif ($barcodefilter) {
370         $sth2->execute($barcodefilter);
371     } else {
372         $sth2->execute();
373     }
374     my $colauthvals = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origcolumn } ) };
375     while ( my ($celvalue) = $sth2->fetchrow ) {
376         my %cell;
377         if (defined $celvalue and $celvalue ne '') {
378             if($colauthvals and $colauthvals->{$celvalue}) {
379                 $cell{coltitle} = $colauthvals->{$celvalue};
380             } else {
381                 $cell{coltitle} = $celvalue;
382             }
383             $cell{value} = $celvalue;
384         }
385         else {
386             $cell{coltitle} = "NULL";
387             $cell{value} = "zzEMPTY";
388         }
389         $cell{totalcol} = 0;
390         push @loopcol, \%cell;
391     }
392
393     my $i = 0;
394     my $hilighted = -1;
395
396     #Initialization of cell values.....
397     my %table;
398
399     foreach my $row (@loopline) {
400         foreach my $col (@loopcol) {
401             $table{ $row->{value} }->{ $col->{value} } = 0;
402         }
403         $table{ $row->{value} }->{totalrow} = 0;
404     }
405
406     # preparing calculation
407     my $select_cellvalue = " COUNT(*) ";
408     $select_cellvalue = " COUNT(DISTINCT biblioitems.biblionumber) " if($cellvalue eq 'biblios');
409     my $strcalc = "
410         SELECT $linefield, $colfield, $select_cellvalue
411         FROM $itemstable
412         LEFT JOIN biblioitems ON ($itemstable.biblioitemnumber = biblioitems.biblioitemnumber)
413         LEFT JOIN biblio ON (biblioitems.biblionumber = biblio.biblionumber)
414         WHERE 1 ";
415
416     my @sqlargs;
417
418     if ($barcodefilter) {
419         $strcalc .= "AND barcode $not like ? ";
420         push @sqlargs, $barcodefilter;
421     }
422
423     if ( @$filters[0] ) {
424         $strcalc .= " AND $itemstable.itemcallnumber >= ? ";
425         @$filters[0] =~ s/\*/%/g;
426         push @sqlargs, @$filters[0];
427     }
428
429     if ( @$filters[1] ) {
430         $strcalc .= " AND $itemstable.itemcallnumber <= ? ";
431         @$filters[1] =~ s/\*/%/g;
432         push @sqlargs, @$filters[1];
433     }
434
435     if ( @$filters[2] ) {
436         $strcalc .= " AND " . ( C4::Context->preference('item-level_itypes') ? "$itemstable.itype" : 'biblioitems.itemtype' ) . " LIKE ? ";
437         @$filters[2] =~ s/\*/%/g;
438         push @sqlargs, @$filters[2];
439     }
440
441     if ( @$filters[3] ) {
442         $strcalc .= " AND biblioitems.publishercode LIKE ? ";
443         @$filters[3] =~ s/\*/%/g;
444         @$filters[3] .= "%" unless @$filters[3] =~ /%/;
445         push @sqlargs, @$filters[3];
446     }
447     if ( @$filters[4] ) {
448         $strcalc .= " AND " .
449         (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate')
450         . "> ? ";
451         @$filters[4] =~ s/\*/%/g;
452         push @sqlargs, @$filters[4];
453     }
454     if ( @$filters[5] ) {
455         @$filters[5] =~ s/\*/%/g;
456         $strcalc .= " AND " .
457         (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate')
458         . "< ? ";
459         push @sqlargs, @$filters[5];
460     }
461     if ( @$filters[6] ) {
462         $strcalc .= " AND $itemstable.homebranch LIKE ? ";
463         @$filters[6] =~ s/\*/%/g;
464         push @sqlargs, @$filters[6];
465     }
466     if ( @$filters[7] ) {
467         $strcalc .= " AND $itemstable.location LIKE ? ";
468         @$filters[7] =~ s/\*/%/g;
469         push @sqlargs, @$filters[7];
470     }
471     if ( @$filters[8] ) {
472         $strcalc .= " AND $itemstable.ccode  LIKE ? ";
473         @$filters[8] =~ s/\*/%/g;
474         push @sqlargs, @$filters[8];
475     }
476     if ( defined @$filters[9] and @$filters[9] ne '' ) {
477         $strcalc .= " AND $itemstable.notforloan  LIKE ? ";
478         @$filters[9] =~ s/\*/%/g;
479         push @sqlargs, @$filters[9];
480     }
481     if ( defined @$filters[10] and @$filters[10] ne '' ) {
482         $strcalc .= " AND $itemstable.materials  LIKE ? ";
483         @$filters[10] =~ s/\*/%/g;
484         push @sqlargs, @$filters[10];
485     }
486     if ( @$filters[13] ) {
487         $strcalc .= " AND $itemstable.dateaccessioned >= ? ";
488         @$filters[13] =~ s/\*/%/g;
489         push @sqlargs, @$filters[13];
490     }
491     if ( @$filters[14] ) {
492         $strcalc .= " AND $itemstable.dateaccessioned <= ? ";
493         @$filters[14] =~ s/\*/%/g;
494         push @sqlargs, @$filters[14];
495     }
496     if ( $cellvalue eq 'deleteditems' and @$filters[15] ) {
497         $strcalc .= " AND DATE(deleteditems.timestamp) >= ? ";
498         @$filters[15] =~ s/\*/%/g;
499         push @sqlargs, @$filters[15];
500     }
501     if ( $cellvalue eq 'deleteditems' and @$filters[16] ) {
502         @$filters[16] =~ s/\*/%/g;
503         $strcalc .= " AND DATE(deleteditems.timestamp) <= ?";
504         push @sqlargs, @$filters[16];
505     }
506     $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
507     $debug and warn "SQL: $strcalc";
508     my $dbcalc = $dbh->prepare($strcalc);
509     $dbcalc->execute(@sqlargs);
510
511     while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
512
513         $col      = "zzEMPTY" if ( !defined($col) );
514         $row      = "zzEMPTY" if ( !defined($row) );
515
516         $table{$row}->{$col}     += $value;
517         $table{$row}->{totalrow} += $value;
518         $grantotal               += $value;
519     }
520
521     foreach my $row ( @loopline ) {
522         my @loopcell;
523
524         #@loopcol ensures the order for columns is common with column titles
525         # and the number matches the number of columns
526         foreach my $col (@loopcol) {
527             my $value = $table{$row->{value}}->{ $col->{value} };
528             push @loopcell, { value => $value };
529         }
530         push @looprow,
531           { 'rowtitle' => $row->{rowtitle},
532             'value'    => $row->{value},
533             'loopcell' => \@loopcell,
534             'hilighted' => ( $hilighted *= -1 > 0 ),
535             'totalrow' => $table{$row->{value}}->{totalrow}
536           };
537     }
538
539     foreach my $col (@loopcol) {
540         my $total = 0;
541         foreach my $row (@looprow) {
542             $total += $table{ $row->{value} }->{ $col->{value} };
543         }
544
545         push @loopfooter, { 'totalcol' => $total };
546     }
547
548     # the header of the table
549     $globalline{loopfilter} = \@loopfilter;
550
551     # the core of the table
552     $globalline{looprow} = \@looprow;
553     $globalline{loopcol} = \@loopcol;
554
555     # the foot (totals by borrower type)
556     $globalline{loopfooter} = \@loopfooter;
557     $globalline{total}      = $grantotal;
558     $globalline{line}       = $line;
559     $globalline{column}     = $column;
560     push @mainloop, \%globalline;
561     return \@mainloop;
562 }