Translation end.
[koha.git] / reports / borrowers_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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use CGI;
22 use C4::Auth;
23 use C4::Context;
24 use C4::Branch; # GetBranches
25 use C4::Koha;
26 use C4::Dates;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Circulation;
30 use Date::Calc qw(
31   Today
32   Add_Delta_YM
33   );
34
35 =head1 NAME
36
37 plugin that shows a stats on borrowers
38
39 =head1 DESCRIPTION
40
41 =over 2
42
43 =cut
44
45 my $input = new CGI;
46 my $do_it=$input->param('do_it');
47 my $fullreportname = "reports/borrowers_stats.tmpl";
48 my $line = $input->param("Line");
49 my $column = $input->param("Column");
50 my @filters = $input->param("Filter");
51 my $digits = $input->param("digits");
52 my $period = $input->param("period");
53 my $borstat = $input->param("status");
54 my $borstat1 = $input->param("activity");
55 my $output = $input->param("output");
56 my $basename = $input->param("basename");
57 my $mime = $input->param("MIME");
58 my $del = $input->param("sep");
59
60 my ($template, $borrowernumber, $cookie)
61         = get_template_and_user({template_name => $fullreportname,
62                                 query => $input,
63                                 type => "intranet",
64                                 authnotrequired => 0,
65                                 flagsrequired => {reports=> 1},
66                                 debug => 1,
67                                 });
68 $template->param(do_it => $do_it);
69 if ($do_it) {
70         my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters);
71         if ($output eq "screen"){
72                 $template->param(mainloop => $results);
73                 output_html_with_http_headers $input, $cookie, $template->output;
74                 exit(1);
75         } else {
76                 print $input->header(-type => 'application/vnd.sun.xml.calc',
77                                      -encoding    => 'utf-8',
78                                      -name=>"$basename.csv",
79                                      -attachment=>"$basename.csv");
80                 my $cols = @$results[0]->{loopcol};
81                 my $lines = @$results[0]->{looprow};
82                 my $sep;
83                 $sep =C4::Context->preference("delimiter");
84                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
85                 foreach my $col ( @$cols ) {
86                         print $col->{coltitle}.$sep;
87                 }
88                 print "Total\n";
89                 foreach my $line ( @$lines ) {
90                         my $x = $line->{loopcell};
91                         print $line->{rowtitle}.$sep;
92                         foreach my $cell (@$x) {
93                                 print $cell->{value}.$sep;
94                         }
95                         print $line->{totalrow};
96                         print "\n";
97                 }
98                 print "TOTAL";
99                 $cols = @$results[0]->{loopfooter};
100                 foreach my $col ( @$cols ) {
101                         print $sep.$col->{totalcol};
102                 }
103                 print $sep.@$results[0]->{total};
104                 exit(1);
105         }
106 } else {
107         my $dbh = C4::Context->dbh;
108         my @values;
109         my %labels;
110         my $req;
111         $req = $dbh->prepare( "select categorycode, description from categories order by description");
112         $req->execute;
113         my %select_catcode;
114         my @select_catcode;
115         push @select_catcode,"";
116         $select_catcode{""} ="";
117         while (my ($catcode, $description) =$req->fetchrow) {
118                 push @select_catcode, $catcode;
119                 $select_catcode{$catcode} = $description;
120         }
121         my $CGICatCode=CGI::scrolling_list( -name     => 'Filter',
122                                 -id => 'catcode',
123                                 -values   => \@select_catcode,
124                                 -labels   => \%select_catcode,
125                                 -size     => 1,
126                                 -multiple => 0 );
127
128         
129 my $branches = GetBranches;
130 my @branchloop;
131 my @select_branch;
132 #my %select_branches;
133 push @select_branch,"";
134 #$select_branches{""}="";
135 foreach my $thisbranch (sort keys %$branches) {
136         push @select_branch,$thisbranch;
137    # my $selected = 1 if $thisbranch eq $branch;
138     my %row =(value => $thisbranch,
139 #                selected => $selected,
140                 branchname => $branches->{$thisbranch}->{'branchname'},
141             );
142     push @branchloop, \%row;
143 }
144     my $CGIBranch=CGI::scrolling_list( -name     => 'Filter',
145                              -id => 'branch',
146                              -values   => \@select_branch,
147 #                             -labels   => \%select_branches,
148                              -size     => 1,
149                              -multiple => 0 );
150
151
152         $req = $dbh->prepare( "select distinctrow zipcode from borrowers order by zipcode");
153         $req->execute;
154         my @select_zipcode;
155         push @select_zipcode,"";
156         while (my ($value) =$req->fetchrow) {
157                 if ($value) {
158                         push @select_zipcode, $value;
159                 }
160         }
161
162         my $CGIZipCode=CGI::scrolling_list( -name     => 'Filter',
163                                 -id => 'zipcode',
164                                 -values   => \@select_zipcode,
165                                 -size     => 1,
166                                 -multiple => 0 );
167
168
169         $req = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' order by lib");
170         $req->execute;
171         my @select_sort1;
172         my %select_sort1;
173         push @select_sort1,"";
174         $select_sort1{""}="";
175         my $hassort1;
176         while (my ($auth_value,$lib) =$req->fetchrow) {
177                 if ($auth_value) {
178                         $hassort1=1;
179                         push @select_sort1, $auth_value;
180                         $select_sort1{$auth_value}=$lib
181                 }
182         }
183
184         my $CGIsort1=CGI::scrolling_list( -name     => 'Filter',
185                                 -id => 'sort1',
186                                 -values   => \@select_sort1,
187                                 -labels =>\%select_sort1,
188                                 -size     => 1,
189                                 -multiple => 0 );
190         
191         $req = $dbh->prepare( "select distinctrow sort2 from borrowers order by sort2");
192         $req->execute;
193         my @select_sort2;
194         push @select_sort2,"";
195         my $hassort2;
196         while (my ($value) =$req->fetchrow) {
197                 if ($value) {
198                         $hassort2 = 1;
199                         push @select_sort2, $value;
200                 }
201         }
202         my $CGIsort2=CGI::scrolling_list( -name     => 'Filter',
203                                 -id => 'sort2',
204                                 -values   => \@select_sort2,
205                                 -size     => 1,
206                                 -multiple => 0 );
207         
208         my @mime = ( C4::Context->preference("MIME") );
209         foreach my $mime (@mime){
210                 warn "".$mime;
211         }
212         
213         my $CGIextChoice=CGI::scrolling_list(
214                                 -name => 'MIME',
215                                 -id => 'MIME',
216                                 -values   => \@mime,
217                                 -size     => 1,
218                                 -multiple => 0 );
219         
220         my @dels = ( C4::Context->preference("delimiter") );
221         my $CGIsepChoice=CGI::scrolling_list(
222                                 -name => 'sep',
223                                 -id => 'sep',
224                                 -values   => \@dels,
225                                 -size     => 1,
226                                 -multiple => 0 );
227
228         $template->param(               CGICatCode => $CGICatCode,
229                                         CGIZipCode => $CGIZipCode,
230                                         CGISort1 => $CGIsort1,
231                                         hassort1 => $hassort1,
232                                         CGISort2 => $CGIsort2,
233                                         hassort2 => $hassort2,
234                                         CGIextChoice => $CGIextChoice,
235                                         CGIsepChoice => $CGIsepChoice,
236                                         CGIBranch => $CGIBranch,
237                                         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
238                     );
239
240 }
241 output_html_with_http_headers $input, $cookie, $template->output;
242
243
244
245 sub calculate {
246         my ($line, $column, $digits, $status, $activity, $filters) = @_;
247         my @mainloop;
248         my @loopfooter;
249         my @loopcol;
250         my @loopline;
251         my @looprow;
252         my %globalline;
253         my $grantotal =0;
254 # extract parameters
255         my $dbh = C4::Context->dbh;
256
257 # Filters
258         my $linefilter = "";
259 #       warn "filtres ".@filters[0];
260 #       warn "filtres ".@filters[4];
261 #       warn "filtres ".@filters[5];
262 #       warn "filtres ".@filters[6];
263
264         
265         $linefilter = @$filters[0] if ($line =~ /categorycode/ )  ;
266         $linefilter = @$filters[1] if ($line =~ /zipcode/ )  ;
267         $linefilter = @$filters[2] if ($line =~ /branchcode/ ) ;
268         $linefilter = @$filters[5] if ($line =~ /sort1/ ) ;
269         $linefilter = @$filters[6] if ($line =~ /sort2/ ) ;
270
271         my $colfilter = "";
272         $colfilter = @$filters[0] if ($column =~ /categorycode/);
273         $colfilter = @$filters[1] if ($column =~ /zipcode/);
274         $colfilter = @$filters[2] if ($column =~ /branchcode/);
275         $colfilter = @$filters[5] if ($column =~ /sort1/);
276         $colfilter = @$filters[6] if ($column =~ /sort2/);
277
278         my @loopfilter;
279         for (my $i=0;$i<=6;$i++) {
280                 my %cell;
281                 if ( @$filters[$i] ) {
282                         $cell{filter} .= @$filters[$i];
283                         $cell{crit} .="Cat Code " if ($i==0);
284                         $cell{crit} .="Zip Code" if ($i==1);
285                         $cell{crit} .="Branchcode" if ($i==2);
286                         $cell{crit} .="Date of Birth" if ($i==3);
287                         $cell{crit} .="Date of Birth" if ($i==4);
288                         $cell{crit} .="Sort1" if ($i==5);
289                         $cell{crit} .="Sort2" if ($i==6);
290                         push @loopfilter, \%cell;
291                 }
292         }
293         if ($status) {
294                 push @loopfilter,{crit=>"Status",filter=>$status}
295         }
296                 
297         if ($activity) {
298                 push @loopfilter,{crit=>"Activity",filter=>$activity};
299         }
300 # year of activity
301         my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0);
302         my $newperioddate=$period_year."-".$period_month."-".$period_day;
303 #       warn "PERIOD".$period;
304 # 1st, loop rows.
305         my $linefield;
306         if (($line =~/zipcode/) and ($digits)) {
307                 $linefield .="left($line,$digits)";
308         } else{
309                 $linefield .= $line;
310         }
311         
312         my $strsth;
313         $strsth .= "select distinctrow $linefield from borrowers where $line is not null ";
314         $linefilter =~ s/\*/%/g;
315         if ( $linefilter ) {
316                 $strsth .= " and $linefield LIKE ? " ;
317         }
318         $strsth .= " and $status='1' " if ($status);
319         $strsth .=" order by $linefield";
320 #       warn "". $strsth;
321         
322         my $sth = $dbh->prepare( $strsth );
323         if ( $linefilter ) {
324                 $sth->execute($linefilter);
325         } else {
326                 $sth->execute;
327         }
328         while ( my ($celvalue) = $sth->fetchrow) {
329                 my %cell;
330                 if ($celvalue) {
331                         $cell{rowtitle} = $celvalue;
332 #               } else {
333 #                       $cell{rowtitle} = "";
334                 }
335                 $cell{totalrow} = 0;
336                 push @loopline, \%cell;
337         }
338
339 # 2nd, loop cols.
340         my $colfield;
341         if (($column =~/zipcode/) and ($digits)) {
342                 $colfield .= "left($column,$digits)";
343         } else{
344                 $colfield .= $column;
345         }
346         my $strsth2;
347         $colfilter =~ s/\*/%/g;
348         $strsth2 .= "select distinctrow $colfield from borrowers where $column is not null";
349         if ( $colfilter ) {
350                 $strsth2 .= " and $colfield LIKE ? ";
351         }
352         $strsth2 .= " and $status='1' " if ($status);
353         $strsth2 .= " order by $colfield";
354 #       warn "". $strsth2;
355         my $sth2 = $dbh->prepare( $strsth2 );
356         if ($colfilter) {
357                 $sth2->execute($colfilter);
358         } else {
359                 $sth2->execute;
360         }
361         while (my ($celvalue) = $sth2->fetchrow) {
362                 my %cell;
363                 my %ft;
364                 if ($celvalue) {
365                         $cell{coltitle} = $celvalue;
366                 }
367                 push @loopcol, \%cell;
368         }
369         
370
371         my $i=0;
372         my @totalcol;
373         my $hilighted=-1;
374         
375         #Initialization of cell values.....
376         my %table;
377 #       warn "init table";
378         foreach my $row ( @loopline ) {
379                 foreach my $col ( @loopcol ) {
380 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
381                         $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
382                 }
383                 $table{$row->{rowtitle}}->{totalrow}=0;
384         }
385
386 # preparing calculation
387         my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM borrowers WHERE 1 ";
388         @$filters[0]=~ s/\*/%/g if (@$filters[0]);
389         $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
390         @$filters[1]=~ s/\*/%/g if (@$filters[1]);
391         $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] );
392         @$filters[2]=~ s/\*/%/g if (@$filters[2]);
393         $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] );
394         @$filters[3]=~ s/\*/%/g if (@$filters[3]);
395         $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] );
396         @$filters[4]=~ s/\*/%/g if (@$filters[4]);
397         $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] );
398         @$filters[5]=~ s/\*/%/g if (@$filters[5]);
399         $strcalc .= " AND sort1 like '" . @$filters[5] ."'" if ( @$filters[5] );
400         @$filters[6]=~ s/\*/%/g if (@$filters[6]);
401         $strcalc .= " AND sort2 like '" . @$filters[6] ."'" if ( @$filters[6] );
402         $strcalc .= " AND borrowernumber in (select distinct(borrowernumber) from issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active');
403         $strcalc .= " AND borrowernumber not in (select distinct(borrowernumber) from issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'nonactive');
404         $strcalc .= " AND $status='1' " if ($status);
405         $strcalc .= " group by $linefield, $colfield";
406 #       warn "". $strcalc;
407         my $dbcalc = $dbh->prepare($strcalc);
408         $dbcalc->execute;
409 #       warn "filling table";
410         
411         my $emptycol; 
412         while (my ($row, $col, $value) = $dbcalc->fetchrow) {
413 #               warn "filling table $row / $col / $value ";
414                 $emptycol = 1 if ($col eq undef);
415                 $col = "zzEMPTY" if ($col eq undef);
416                 $row = "zzEMPTY" if ($row eq undef);
417                 
418                 $table{$row}->{$col}+=$value;
419                 $table{$row}->{totalrow}+=$value;
420                 $grantotal += $value;
421         }
422         
423         push @loopcol,{coltitle => "NULL"} if ($emptycol);
424         
425         foreach my $row ( sort keys %table ) {
426                 my @loopcell;
427                 #@loopcol ensures the order for columns is common with column titles
428                 # and the number matches the number of columns
429                 foreach my $col ( @loopcol ) {
430                         my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
431                         push @loopcell, {value => $value  } ;
432                 }
433                 push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
434                                                 'loopcell' => \@loopcell,
435                                                 'hilighted' => ($hilighted >0),
436                                                 'totalrow' => $table{$row}->{totalrow}
437                                         };
438                 $hilighted = -$hilighted;
439         }
440         
441         foreach my $col ( @loopcol ) {
442                 my $total=0;
443                 foreach my $row ( @looprow ) {
444                         $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
445 #                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
446                 }
447 #               warn "summ for column ".$col->{coltitle}."  = ".$total;
448                 push @loopfooter, {'totalcol' => $total};
449         }
450                         
451
452         # the header of the table
453         $globalline{loopfilter}=\@loopfilter;
454         # the core of the table
455         $globalline{looprow} = \@looprow;
456         $globalline{loopcol} = \@loopcol;
457 #       # the foot (totals by borrower type)
458         $globalline{loopfooter} = \@loopfooter;
459         $globalline{total}= $grantotal;
460         $globalline{line} = $line;
461         $globalline{column} = $column;
462         push @mainloop,\%globalline;
463         return \@mainloop;
464 }
465