Bug 28327: Unify CSV delimiter special behavior for tabulation
[koha.git] / reports / borrowers_out.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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23 use C4::Auth qw( get_template_and_user );
24 use C4::Context;
25 use C4::Output qw( output_html_with_http_headers );
26 use C4::Reports qw( GetDelimiterChoices );
27
28 use Koha::DateUtils qw( dt_from_string output_pref );
29 use Koha::Patron::Categories;
30
31 =head1 NAME
32
33 reports/borrowers_out.pl
34
35 =head1 DESCRIPTION
36
37 Plugin that shows a stats on borrowers
38
39 =cut
40
41 my $input = CGI->new;
42 my $do_it=$input->param('do_it');
43 my $fullreportname = "reports/borrowers_out.tt";
44 my $limit = $input->param("Limit");
45 my $column = $input->param("Criteria");
46 my @filters = $input->multi_param("Filter");
47 $filters[1] = eval { output_pref( { dt => dt_from_string( $filters[1]), dateonly => 1, dateformat => 'iso' } ); }
48     if ( $filters[1] );
49
50 my $output = $input->param("output");
51 my $basename = $input->param("basename");
52 our $sep     = C4::Context->csv_delimiter(scalar $input->param("sep"));
53 my ($template, $borrowernumber, $cookie)
54     = get_template_and_user({template_name => $fullreportname,
55                 query => $input,
56                 type => "intranet",
57                 flagsrequired => {reports => '*'},
58                 });
59 $template->param(do_it => $do_it,
60         );
61 if ($do_it) {
62 # Displaying results
63     my $results = calculate($limit, $column, \@filters);
64     if ($output eq "screen"){
65 # Printing results to screen
66         $template->param(mainloop => $results);
67         output_html_with_http_headers $input, $cookie, $template->output;
68         exit;
69     } else {
70 # Printing to a csv file
71         print $input->header(-type => 'application/vnd.sun.xml.calc',
72                             -encoding    => 'utf-8',
73                             -attachment=>"$basename.csv",
74                             -filename=>"$basename.csv" );
75         my $cols = @$results[0]->{loopcol};
76         my $lines = @$results[0]->{looprow};
77 # header top-right
78         print "num /". @$results[0]->{column} .$sep;
79 # Other header
80         foreach my $col ( @$cols ) {
81             print $col->{coltitle}.$sep;
82         }
83         print "Total\n";
84 # Table
85         foreach my $line ( @$lines ) {
86             my $x = $line->{loopcell};
87             print $line->{rowtitle}.$sep;
88             foreach my $cell (@$x) {
89                 my $cellvalue = defined $cell->{value} ? $cell->{value}.$sep : ''.$sep;
90                 print $cellvalue;
91             }
92 #            print $line->{totalrow};
93             print "\n";
94         }
95 # footer
96         print "TOTAL";
97         $cols = @$results[0]->{loopfooter};
98         foreach my $col ( @$cols ) {
99             print $sep.$col->{totalcol};
100         }
101         print $sep.@$results[0]->{total};
102         exit;
103     }
104 # Displaying choices
105 } else {
106     my $dbh = C4::Context->dbh;
107
108     my $CGIextChoice = ( 'CSV' ); # FIXME translation
109         my $CGIsepChoice = GetDelimiterChoices;
110
111     my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']});
112     $template->param(
113                     CGIextChoice => $CGIextChoice,
114                     CGIsepChoice => $CGIsepChoice,
115                     patron_categories => $patron_categories,
116                     );
117 output_html_with_http_headers $input, $cookie, $template->output;
118 }
119
120
121 sub calculate {
122     my ($line, $column, $filters) = @_;
123     my @mainloop;
124     my @loopfooter;
125     my @loopcol;
126     my @looprow;
127     my %globalline;
128     my $grantotal =0;
129 # extract parameters
130     my $dbh = C4::Context->dbh;
131
132 # Filters
133 # Checking filters
134 #
135     my @loopfilter;
136     for (my $i=0;$i<=2;$i++) {
137         my %cell;
138         if ( @$filters[$i] ) {
139             if (($i==1) and (@$filters[$i-1])) {
140                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
141             }
142             $cell{filter} .= @$filters[$i];
143             $cell{crit} .="Bor Cat" if ($i==0);
144             $cell{crit} .="Without issues since" if ($i==1);
145             push @loopfilter, \%cell;
146         }
147     }
148     my $colfield;
149     my $colorder;
150     if ($column){
151         $column = "borrowers.".$column if $column=~/categorycode/ || $column=~/branchcode/;
152         my @colfilter ;
153         $colfilter[0] = @$filters[0] if ($column =~ /category/ )  ;
154     #   $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
155     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
156                                                 
157     # loop cols.
158         $colfield .= $column;
159         $colorder .= $column;
160         
161         my $strsth2;
162         $strsth2 .= "select distinct " . $dbh->quote($colfield) . " FROM borrowers WHERE 1";
163         my @query_args;
164         if ( $colfilter[0] ) {
165             $colfilter[0] =~ s/\*/%/g;
166             $strsth2 .= " and " . $dbh->quote($column) . "LIKE ?" ;
167             push @query_args, $colfilter[0];
168         }
169         $strsth2 .=" group by " . $dbh->quote($colfield);
170         $strsth2 .=" order by " . $dbh->quote($colorder);
171         # warn "". $strsth2;
172         
173         my $sth2 = $dbh->prepare( $strsth2 );
174         $sth2->execute( @query_args );
175         while (my ($celvalue) = $sth2->fetchrow) {
176             my %cell;
177     #           my %ft;
178     #           warn "coltitle :".$celvalue;
179             $cell{coltitle} = $celvalue;
180     #           $ft{totalcol} = 0;
181             push @loopcol, \%cell;
182         }
183     #   warn "fin des titres colonnes";
184     }
185     
186     my $i=0;
187 #       my @totalcol;
188     
189     #Initialization of cell values.....
190     my @table;
191     
192 #       warn "init table";
193     if($line) {
194         for (my $i=1;$i<=$line;$i++) {
195             foreach my $col ( @loopcol ) {
196                 $table[$i]->{($col->{coltitle})?$col->{coltitle}:"Global"}=0;
197             }
198         }
199     }
200
201
202 # preparing calculation
203     my $strcalc ;
204     
205 # Processing calculation
206     $strcalc .= "SELECT CONCAT( borrowers.surname , \"\\t\",borrowers.firstname, \"\\t\", borrowers.cardnumber)";
207     $strcalc .= " , " . $dbh->quote($colfield) if ($colfield);
208     $strcalc .= " FROM borrowers ";
209     $strcalc .= "WHERE 1 ";
210     my @query_args;
211     if ( @$filters[0] ) {
212         @$filters[0]=~ s/\*/%/g;
213         $strcalc .= " AND borrowers.categorycode like ?";
214         push @query_args, @$filters[0];
215     }
216     $strcalc .= " AND NOT EXISTS (SELECT * FROM issues WHERE issues.borrowernumber=borrowers.borrowernumber ";
217     if ( @$filters[1] ) {
218         $strcalc .= " AND issues.timestamp > ?";
219         push @query_args, @$filters[1];
220     }
221     $strcalc .= ") ";
222     $strcalc .= " AND NOT EXISTS (SELECT * FROM old_issues WHERE old_issues.borrowernumber=borrowers.borrowernumber ";
223     if ( @$filters[1] ) {
224         $strcalc .= " AND old_issues.timestamp > ?";
225         push @query_args, @$filters[1];
226     }
227     $strcalc .= ") ";
228     $strcalc .= " group by borrowers.borrowernumber";
229     $strcalc .= ", " . $dbh->quote($colfield) if ($column);
230     $strcalc .= " order by " . $dbh->quote($colfield) if ($colfield);
231     my $max;
232     if ($line) {
233         if (@loopcol) {
234             $max = $line*@loopcol;
235         } else { $max=$line;}
236         $strcalc .= " LIMIT 0,$max";
237      } 
238     
239     my $dbcalc = $dbh->prepare($strcalc);
240     $dbcalc->execute( @query_args );
241 #       warn "filling table";
242     my $previous_col;
243     $i=1;
244     while (my  @data = $dbcalc->fetchrow) {
245         my ($row, $col )=@data;
246         $col = "zzEMPTY" if (!defined($col));
247         $i=1 if (($previous_col) and not($col eq $previous_col));
248         $table[$i]->{$col}=$row;
249 #               warn " $i $col $row";
250         $i++;
251         $previous_col=$col;
252     }
253     
254     push @loopcol,{coltitle => "Global"} if not($column);
255     
256     $max =(($line)?$line:@table -1);
257     for ($i=1; $i<=$max;$i++) {
258         my @loopcell;
259         #@loopcol ensures the order for columns is common with column titles
260         # and the number matches the number of columns
261         my $colcount=0;
262         foreach my $col ( @loopcol ) {
263             my $value;
264             if (@loopcol){
265                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}};
266             } else {
267                 $value =$table[$i]->{"zzEMPTY"};
268             }
269             push @loopcell, {value => $value} ;
270         }
271         push @looprow,{ 'rowtitle' => $i ,
272                         'loopcell' => \@loopcell,
273                     };
274     }
275     
276             
277
278     # the header of the table
279     $globalline{loopfilter}=\@loopfilter;
280     # the core of the table
281     $globalline{looprow} = \@looprow;
282     $globalline{loopcol} = \@loopcol;
283 #       # the foot (totals by borrower type)
284     $globalline{loopfooter} = \@loopfooter;
285     $globalline{total}= $grantotal;
286     $globalline{line} = $line;
287     $globalline{column} = $column;
288     push @mainloop,\%globalline;
289     return \@mainloop;
290 }
291
292 1;
293 __END__