Bug 14428: Remove C4::Input
[koha.git] / admin / aqplan.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008-2009 BibLibre SARL
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18
19 #script to administer the aqbudgets0 table
20 #written 20/02/2002 by paul.poulain@free.fr
21 # This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html)
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use CGI qw ( -utf8 );
26 use List::Util qw/min/;
27 use Date::Calc qw/Delta_YMD Easter_Sunday Today Decode_Date_EU/;
28 use Date::Manip qw/ ParseDate UnixDate DateCalc/;
29 use C4::Dates qw/format_date format_date_in_iso/;
30 use Text::CSV_XS;
31
32 use C4::Acquisition;
33 use C4::Budgets;
34 use C4::Context;
35 use C4::Output;
36 use C4::Koha;
37 use C4::Auth;
38 use C4::Debug;
39
40 my $input = new CGI;
41 ####  $input
42
43 my $dbh = C4::Context->dbh;
44
45 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
46     {   template_name   => "admin/aqplan.tt",
47         query           => $input,
48         type            => "intranet",
49         authnotrequired => 0,
50         flagsrequired   => { acquisition => 'planning_manage' },
51         debug           => 0,
52     }
53 );
54
55 my $budget_period_id = $input->param('budget_period_id');
56 # ' ------- get periods stuff ------------------'
57 # IF PERIOD_ID IS DEFINED,  GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
58 my $period = GetBudgetPeriod($budget_period_id);
59 my $count  = GetPeriodsCount();
60 my $cur    = GetCurrency;
61 $template->param( symbol => $cur->{symbol},
62                   currency => $cur->{currency}
63                );
64 $template->param( period_button_only => 1 ) if $count == 0;
65
66
67
68 # authcats_loop populates the YUI planning button
69 my $auth_cats_loop            = GetBudgetAuthCats($budget_period_id);
70 my $budget_period_id          = $period->{'budget_period_id'};
71 my $budget_period_startdate   = $period->{'budget_period_startdate'};
72 my $budget_period_enddate     = $period->{'budget_period_enddate'};
73 my $budget_period_locked      = $period->{'budget_period_locked'};
74 my $budget_period_description = $period->{'budget_period_description'};
75
76
77 $template->param(
78     budget_period_id          => $budget_period_id,
79     budget_period_locked      => $budget_period_locked,
80     budget_period_description => $budget_period_description,
81     auth_cats_loop            => $auth_cats_loop,
82 );
83
84 # ------- get periods stuff ------------------
85
86 my $borrower_id         = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
87 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
88
89 my $periods;
90 my $authcat      = $input->param('authcat');
91 my $show_active  = $input->param('show_active');
92 my $show_actual  = $input->param('show_actual');
93 my $show_percent = $input->param('show_percent');
94 my $output       = $input->param("output");
95 my $basename     = $input->param("basename");
96 my $del          = $input->param("sep");
97
98 my $show_mine       = $input->param('show_mine') ;
99
100 my @hide_cols      = $input->param('hide_cols');
101
102 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
103      $show_actual  = 1;
104 }
105
106 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
107
108 my $budget_id = $input->param('budget_id');
109 my $op        = $input->param("op");
110
111 my $budget_branchcode;
112
113 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
114
115 # build categories list
116 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
117 $sth->execute;
118
119 # the list
120 my @category_list;
121
122 # a hash, to check that some hardcoded categories exist.
123 my %categories;
124 while ( my ($category) = $sth->fetchrow_array ) {
125     push( @category_list, $category );
126     $categories{$category} = 1;
127 }
128
129 # push koha system categories
130 push( @category_list, 'MONTHS' );
131 push( @category_list, 'ITEMTYPES' );
132 push( @category_list, 'BRANCHES' );
133 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
134
135 #reorder the list
136 @category_list = sort { $a cmp $b } @category_list;
137
138 $template->param( authcat_dropbox => {
139         values => \@category_list,
140         default => $authcat,
141     });
142
143 my @budgets = @$budgets_ref;
144 my $CGISort;
145 my @authvals;
146 my %labels;
147
148 my @names = $input->param();
149 # ------------------------------------------------------------
150 if ( $op eq 'save' ) {
151     #get budgets
152     my ( @buds, @auth_values );
153     foreach my $n (@names) {
154         next if $n =~ m/^[^0-9]/;
155         my @moo = split( ',', $n );
156         push @buds, $moo[0];
157         push @auth_values, $moo[1];
158     }
159
160     #uniq buds and auth
161     my %seen;
162     @buds        = grep { !$seen{$_}++ } @buds;
163     @auth_values = grep { !$seen{$_}++ } @auth_values;
164     my @budget_ids;
165     my @budget_lines;
166
167     foreach my $budget (@buds) {
168         my %budget_line;
169         my @cells_line;
170         my %cell_hash;
171
172         foreach my $authvalue (@auth_values) {
173             # get actual stats
174             my $cell_name        = "$budget,$authvalue";
175             my $estimated_amount = $input->param("$cell_name");
176             my %cell_hash = (
177                 estimated_amount => $estimated_amount,
178                 authvalue        => $authvalue,
179                 authcat          => $authcat,
180                 budget_id        => $budget,
181                 budget_period_id => $budget_period_id,
182             );
183             push( @cells_line, \%cell_hash );
184         }
185
186         %budget_line = (
187             lines => \@cells_line,
188         );
189         push( @budget_lines, \%budget_line );
190     }
191     my $plan = \@budget_lines;
192     ModBudgetPlan( $plan, $budget_period_id, $authcat );
193
194 HideCols($authcat, @hide_cols);
195
196
197 }
198 # ------------------------------------------------------------
199 if ( $authcat =~ m/^Asort/ ) {
200    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
201     my $sth   = $dbh->prepare($query);
202     $sth->execute($authcat  );
203     if ( $sth->rows > 0 ) {
204         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
205             my $results = $sth->fetchrow_hashref;
206             push @authvals, $results->{authorised_value};
207             $labels{ $results->{authorised_value} } = $results->{lib};
208         }
209     }
210     $sth->finish;
211     @authvals = sort { $a <=> $b } @authvals;
212 }
213 elsif ( $authcat eq 'MONTHS' ) {
214
215     # build months
216     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
217     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
218
219     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
220
221     #calc number of months between
222     my $months      = ( $Dy * 12 ) + $Dm;
223     my $start_month = @start_date[1];
224     my $end_month   = ( $Dy * 12 ) + $Dm;
225
226     for my $mth ( 0 ... $months ) {
227         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
228         $mth = UnixDate( $mth, "%Y-%m" );
229         push( @authvals, $mth );
230     }
231     foreach my $vv (@authvals) {
232         $labels{$vv} = $vv;
233     }
234 }
235
236 elsif ( $authcat eq 'ITEMTYPES' ) {
237     my $query = qq| SELECT itemtype, description FROM itemtypes |;
238     my $sth   = $dbh->prepare($query);
239     $sth->execute(  );
240
241     if ( $sth->rows > 0 ) {
242         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
243             my $results = $sth->fetchrow_hashref;
244             push @authvals, $results->{itemtype};
245             $labels{ $results->{itemtype} } = $results->{description};
246         }
247     }
248     $sth->finish;
249
250 } elsif ( $authcat eq 'BRANCHES' ) {
251
252     my $query = qq| SELECT branchcode, branchname FROM branches |;
253     my $sth   = $dbh->prepare($query);
254     $sth->execute();
255
256     if ( $sth->rows > 0 ) {
257         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
258             my $results = $sth->fetchrow_hashref;
259             push @authvals, $results->{branchcode};
260             $labels{ $results->{branchcode} } = $results->{branchname};
261         }
262     }
263     $sth->finish;
264 } elsif ($authcat) {
265     my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
266     my $sth   = $dbh->prepare($query);
267     $sth->execute($authcat);
268     if ( $sth->rows > 0 ) {
269         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
270             my $results = $sth->fetchrow_hashref;
271             push @authvals, $results->{authorised_value};
272             $labels{ $results->{authorised_value} } = $results->{lib};
273         }
274     }
275     $sth->finish;
276 }
277
278 my @authvals_row;
279 my $i=1;
280 foreach my $val (@authvals) {
281     my %auth_hash;
282     $auth_hash{val} =   $labels{$val};
283     $auth_hash{code} =   $val;
284     $auth_hash{colnum} =   $i++;
285
286     # display lookup
287     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
288
289     push( @authvals_row, \%auth_hash );
290 }
291
292 #get budgets
293 my ( @buds, @auth_values );
294 foreach my $n (@names) {
295     next if $n =~ m/^[^0-9]/;
296     $n =~ m/(\d*),(.*)/;
297     push @buds, $1;
298     push @auth_values, $2;
299 }
300
301
302 # ------------------------------------------------------------
303 #         DEFAULT DISPLAY BEGINS
304
305 my $CGIextChoice = ( 'CSV' ); # FIXME translation
306 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
307
308 my ( @budget_lines, %cell_hash );
309
310
311 foreach my $budget (@budgets) {
312     my $budget_lock;
313
314     unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
315         $budget_lock = 1
316     }
317
318     # check budget permission
319     if ( $period->{budget_period_locked} == 1 ) {
320         $budget_lock = 1;
321     } elsif ( $budget->{budget_permission} == 1 ) {
322         $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
323     } elsif ( $budget->{budget_permission} == 2 ) {
324         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
325     }
326
327     # allow hard-coded itemtype and branch planning
328     unless ( $authcat eq 'ITEMTYPES'
329         or  $authcat eq 'BRANCHES'
330         or  $authcat eq 'MONTHS' ) {
331
332         # but skip budgets that don't match the current auth-category
333         next if ( $budget->{'sort1_authcat'} ne $authcat
334             && $budget->{'sort2_authcat'} ne $authcat );
335     }
336
337     my %budget_line; # each row of the  table
338     my @cells_line;
339     my $actual_spent;
340     my $estimated_spent;
341
342     my $i = 0;
343     foreach my $authvalue (@authvals) {
344
345         # get actual stats
346         my %cell = (
347             budget_id        => $budget->{'budget_id'},
348             budget_period_id => $budget->{'budget_period_id'},
349             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
350             authvalue        => $authvalue,
351             authcat          => $authcat,
352             cell_authvalue   => $authvalue,
353             budget_lock      => $budget_lock,
354         );
355
356         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
357         $cell{actual_amount}    = sprintf( "%.2f", $actual );
358         $cell{estimated_amount} = sprintf( "%.2f", $estimated );
359         $cell{display}          = $authvals_row[$i]{display};
360         $cell{colnum}           = $i;
361
362         $actual_spent    += $cell{actual_amount};
363         $estimated_spent += $cell{estimated_amount};
364
365
366         push( @cells_line, \%cell );
367         $i++;
368     }
369
370     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
371     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
372
373     %budget_line = (
374         lines                   => \@cells_line,
375         budget_name_indent      => $budget->{budget_name_indent},
376         budget_amount           => $budget->{budget_amount},
377         budget_alloc            => $budget->{budget_alloc},
378         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
379         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
380         budget_id               => $budget->{budget_id},
381         budget_lock             => $budget_lock,
382     );
383
384
385
386     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
387     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
388     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
389     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
390
391     # skip if active set , and spent == 0
392     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
393
394     push( @budget_lines, \%budget_line );
395 }
396
397 if ( $output eq "file" ) {
398     _print_to_csv(\@authvals_row, \@budget_lines);
399     exit(1);
400 }
401
402 my $branchloop = C4::Branch::GetBranchesLoop();
403 $template->param(
404     authvals_row              => \@authvals_row,
405     budget_lines              => \@budget_lines,
406     budget_period_description => $period->{'budget_period_description'},
407     budget_period_locked      => $period->{'budget_period_locked'},
408     budget_period_id          => $budget_period_id,
409     authcat                   => $authcat,
410     show_active               => $show_active,
411     show_actual               => $show_actual,
412     show_percent              => $show_percent,
413     show_mine                 => $show_mine,
414     CGIextChoice              => $CGIextChoice,
415     CGIsepChoice              => $CGIsepChoice,
416
417     authvals              => \@authvals_row,
418     hide_cols_loop              => \@hide_cols,
419     branchloop                => $branchloop,
420 );
421
422 output_html_with_http_headers $input, $cookie, $template->output;
423
424 sub _print_to_csv {
425     my ( $header, $results ) = @_;
426
427     binmode STDOUT, ':encoding(UTF-8)';
428
429     my $csv = Text::CSV_XS->new(
430         {   sep_char     => $del,
431             always_quote => 'TRUE',
432         }
433     );
434     print $input->header(
435         -type       => 'application/vnd.sun.xml.calc',
436         -encoding   => 'utf-8',
437         -attachment => "$basename.csv",
438         -name       => "$basename.csv"
439     );
440     my @col = ( 'Budget name', 'Budget total' );
441     foreach my $row (@$header) {
442         push @col, $row->{'val'};
443     }
444     push @col, 'Budget remaining';
445
446     $csv->combine(@col);
447     my $str = $csv->string;
448     print "$str\n";
449
450     foreach my $row (@$results) {
451         $row->{'budget_name_indent'} =~ s/&nbsp;/ /g;
452         my @col = ( $row->{'budget_name_indent'}, $row->{'budget_amount'} );
453         my $l = $row->{'lines'};
454         foreach my $line (@$l) {
455             push @col, $line->{'estimated_amount'};
456         }
457         push @col, $row->{'budget_est_remain'};
458         $csv->combine(@col);
459         my $str = $csv->string;
460         print "$str\n";
461     }
462 }