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