Bug 28591: Don't pass debug to get_template_and_user
[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 Modern::Perl;
24 use CGI qw ( -utf8 );
25 use List::Util qw/min/;
26 use Date::Calc qw/Delta_YMD Easter_Sunday Today Decode_Date_EU/;
27 use Date::Manip qw/ ParseDate UnixDate DateCalc/;
28 use Text::CSV_XS;
29
30 use C4::Acquisition;
31 use C4::Budgets;
32 use C4::Context;
33 use C4::Output;
34 use C4::Koha;
35 use C4::Auth;
36 use C4::Debug;
37 use Koha::Acquisition::Currencies;
38
39 our $input = CGI->new;
40 ####  $input
41
42 my $dbh = C4::Context->dbh;
43
44 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
45     {   template_name   => "admin/aqplan.tt",
46         query           => $input,
47         type            => "intranet",
48         flagsrequired   => { acquisition => 'planning_manage' },
49     }
50 );
51
52 my $budget_period_id = $input->param('budget_period_id');
53 # ' ------- get periods stuff ------------------'
54 # IF PERIOD_ID IS DEFINED,  GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
55 my $period = GetBudgetPeriod($budget_period_id);
56 my $count  = GetPeriodsCount();
57 my $active_currency = Koha::Acquisition::Currencies->get_active;
58 if ( $active_currency ) {
59     $template->param( symbol => $active_currency->symbol,
60                       currency => $active_currency->currency,
61                    );
62 }
63 $template->param( period_button_only => 1 ) if $count == 0;
64
65
66
67 # authcats_loop populates the YUI planning button
68 my $auth_cats_loop            = GetBudgetAuthCats($budget_period_id);
69 $budget_period_id          = $period->{'budget_period_id'};
70 my $budget_period_startdate   = $period->{'budget_period_startdate'};
71 my $budget_period_enddate     = $period->{'budget_period_enddate'};
72 my $budget_period_locked      = $period->{'budget_period_locked'};
73 my $budget_period_description = $period->{'budget_period_description'};
74
75
76 $template->param(
77     budget_period_id          => $budget_period_id,
78     budget_period_locked      => $budget_period_locked,
79     budget_period_description => $budget_period_description,
80     auth_cats_loop            => $auth_cats_loop,
81 );
82
83 # ------- get periods stuff ------------------
84
85
86 my $borrower_branchcode = my $branch_code = C4::Context->userenv->{'branch'};
87
88 my $authcat      = $input->param('authcat');
89 my $show_active  = $input->param('show_active') // 0;
90 my $show_actual  = $input->param('show_actual');
91 my $show_percent = $input->param('show_percent');
92 my $output       = $input->param("output") // q{};
93 our $basename     = $input->param("basename");
94 our $del          = $input->param("sep");
95
96 my $show_mine       = $input->param('show_mine') ;
97
98 my @hide_cols      = $input->multi_param('hide_cols');
99
100 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
101      $show_actual  = 1;
102 }
103
104 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
105
106 my $budget_id = $input->param('budget_id');
107 my $op        = $input->param("op") // q{};
108
109 my $budgets_ref = GetBudgetHierarchy(
110     $budget_period_id,
111     $show_mine ? $borrower_branchcode : '',
112     $show_mine ? $borrowernumber      : ''
113 );
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, $_ ) 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 @authvals;
145 my %labels;
146
147 my @names = $input->multi_param();
148 # ------------------------------------------------------------
149 if ( $op eq 'save' ) {
150     #get budgets
151     my ( @buds, @auth_values );
152     foreach my $n (@names) {
153         next if $n =~ m/^[^0-9]/;
154         my @moo = split( ',', $n );
155         push @buds, $moo[0];
156         push @auth_values, $moo[1];
157     }
158
159     #uniq buds and auth
160     my %seen;
161     @buds        = grep { !$seen{$_}++ } @buds;
162     @auth_values = grep { !$seen{$_}++ } @auth_values;
163     my @budget_lines;
164
165     foreach my $budget (@buds) {
166         my %budget_line;
167         my @cells_line;
168         my %cell_hash;
169
170         foreach my $authvalue (@auth_values) {
171             # get actual stats
172             my $cell_name        = "$budget,$authvalue";
173             my $estimated_amount = $input->param("$cell_name");
174             my %cell_hash = (
175                 estimated_amount => $estimated_amount,
176                 authvalue        => $authvalue,
177                 authcat          => $authcat,
178                 budget_id        => $budget,
179                 budget_period_id => $budget_period_id,
180             );
181             push( @cells_line, \%cell_hash );
182         }
183
184         %budget_line = (
185             lines => \@cells_line,
186         );
187         push( @budget_lines, \%budget_line );
188     }
189     my $plan = \@budget_lines;
190     ModBudgetPlan( $plan, $budget_period_id, $authcat );
191
192 HideCols($authcat, @hide_cols);
193
194
195 }
196 # ------------------------------------------------------------
197 if ( $authcat =~ m/^Asort/ ) {
198    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
199     my $sth   = $dbh->prepare($query);
200     $sth->execute($authcat  );
201     if ( $sth->rows > 0 ) {
202         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
203             my $results = $sth->fetchrow_hashref;
204             push @authvals, $results->{authorised_value};
205             $labels{ $results->{authorised_value} } = $results->{lib};
206         }
207     }
208     $sth->finish;
209     @authvals = sort { $a <=> $b } @authvals;
210 }
211 elsif ( $authcat eq 'MONTHS' && $budget_period_startdate && $budget_period_enddate ) {
212
213     # build months
214     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
215     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
216
217     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
218
219     #calc number of months between
220     my $months      = ( $Dy * 12 ) + $Dm;
221     my $start_month = $start_date[1];
222     my $end_month   = ( $Dy * 12 ) + $Dm;
223
224     for my $mth ( 0 ... $months ) {
225         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
226         $mth = UnixDate( $mth, "%Y-%m" );
227         push( @authvals, $mth );
228     }
229     foreach my $vv (@authvals) {
230         $labels{$vv} = $vv;
231     }
232 }
233
234 elsif ( $authcat eq 'ITEMTYPES' ) {
235     my $query = qq| SELECT itemtype, description FROM itemtypes |;
236     my $sth   = $dbh->prepare($query);
237     $sth->execute(  );
238
239     if ( $sth->rows > 0 ) {
240         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
241             my $results = $sth->fetchrow_hashref;
242             push @authvals, $results->{itemtype};
243             $labels{ $results->{itemtype} } = $results->{description};
244         }
245     }
246     $sth->finish;
247
248 } elsif ( $authcat eq 'BRANCHES' ) {
249
250     my $query = qq| SELECT branchcode, branchname FROM branches |;
251     my $sth   = $dbh->prepare($query);
252     $sth->execute();
253
254     if ( $sth->rows > 0 ) {
255         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
256             my $results = $sth->fetchrow_hashref;
257             push @authvals, $results->{branchcode};
258             $labels{ $results->{branchcode} } = $results->{branchname};
259         }
260     }
261     $sth->finish;
262 } elsif ($authcat) {
263     my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
264     my $sth   = $dbh->prepare($query);
265     $sth->execute($authcat);
266     if ( $sth->rows > 0 ) {
267         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
268             my $results = $sth->fetchrow_hashref;
269             push @authvals, $results->{authorised_value};
270             $labels{ $results->{authorised_value} } = $results->{lib};
271         }
272     }
273     $sth->finish;
274 }
275
276 my @authvals_row;
277 my $i=1;
278 foreach my $val (@authvals) {
279     my %auth_hash;
280     $auth_hash{val} =   $labels{$val};
281     $auth_hash{code} =   $val;
282     $auth_hash{colnum} =   $i++;
283
284     # display lookup
285     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
286
287     push( @authvals_row, \%auth_hash );
288 }
289
290 #get budgets
291 my ( @buds, @auth_values );
292 foreach my $n (@names) {
293     next if $n =~ m/^[^0-9]/;
294     $n =~ m/(\d*),(.*)/;
295     push @buds, $1;
296     push @auth_values, $2;
297 }
298
299
300 # ------------------------------------------------------------
301 #         DEFAULT DISPLAY BEGINS
302
303 my $CGIextChoice = ( 'CSV' ); # FIXME translation
304 my $CGIsepChoice = ( C4::Context->preference("CSVDelimiter") );
305
306 my ( @budget_lines, %cell_hash );
307
308
309 foreach my $budget (@budgets) {
310     my $budget_lock;
311
312     unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
313         $budget_lock = 1
314     }
315
316     # check budget permission
317     if ( $period->{budget_period_locked} == 1 ) {
318         $budget_lock = 1;
319     } elsif ( $budget->{budget_permission} == 1 ) {
320         $budget_lock = 1 if $borrowernumber != $budget->{'budget_owner_id'};
321     } elsif ( $budget->{budget_permission} == 2 ) {
322         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
323     }
324
325     # allow hard-coded itemtype and branch planning
326     unless ( $authcat eq 'ITEMTYPES'
327         or  $authcat eq 'BRANCHES'
328         or  $authcat eq 'MONTHS' ) {
329
330         # but skip budgets that don't match the current auth-category
331         next if ( $budget->{'sort1_authcat'} ne $authcat
332             && $budget->{'sort2_authcat'} ne $authcat );
333     }
334
335     my %budget_line; # each row of the  table
336     my @cells_line;
337     my $actual_spent;
338     my $estimated_spent;
339
340     my $i = 0;
341     foreach my $authvalue (@authvals) {
342
343         # get actual stats
344         my %cell = (
345             budget_id        => $budget->{'budget_id'},
346             budget_period_id => $budget->{'budget_period_id'},
347             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
348             authvalue        => $authvalue,
349             authcat          => $authcat,
350             cell_authvalue   => $authvalue,
351             budget_lock      => $budget_lock,
352         );
353
354         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
355         $cell{actual_amount}    = sprintf( "%.2f", $actual // 0 );
356         $cell{estimated_amount} = sprintf( "%.2f", $estimated // 0 );
357         $cell{display}          = $authvals_row[$i]{display};
358         $cell{colnum}           = $i;
359
360         $actual_spent    += $cell{actual_amount};
361         $estimated_spent += $cell{estimated_amount};
362
363
364         push( @cells_line, \%cell );
365         $i++;
366     }
367
368     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
369     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
370
371     %budget_line = (
372         lines                   => \@cells_line,
373         budget_name             => $budget->{budget_name},
374         budget_amount           => $budget->{budget_amount},
375         budget_alloc            => $budget->{budget_alloc},
376         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
377         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
378         budget_id               => $budget->{budget_id},
379         budget_lock             => $budget_lock,
380     );
381
382
383
384     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
385     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
386     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
387     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
388
389     # skip if active set , and spent == 0
390     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
391
392     push( @budget_lines, \%budget_line );
393 }
394
395 if ( $output eq "file" ) {
396     _print_to_csv(\@authvals_row, \@budget_lines);
397     exit(1);
398 }
399
400 $template->param(
401     authvals_row              => \@authvals_row,
402     budget_lines              => \@budget_lines,
403     budget_period_description => $period->{'budget_period_description'},
404     budget_period_locked      => $period->{'budget_period_locked'},
405     budget_period_id          => $budget_period_id,
406     authcat                   => $authcat,
407     show_active               => $show_active,
408     show_actual               => $show_actual,
409     show_percent              => $show_percent,
410     show_mine                 => $show_mine,
411     CGIextChoice              => $CGIextChoice,
412     CGIsepChoice              => $CGIsepChoice,
413
414     authvals              => \@authvals_row,
415     hide_cols_loop              => \@hide_cols,
416 );
417
418 output_html_with_http_headers $input, $cookie, $template->output;
419
420 sub _print_to_csv {
421     my ( $header, $results ) = @_;
422
423     binmode STDOUT, ':encoding(UTF-8)';
424
425     my $csv = Text::CSV_XS->new(
426         {   sep_char     => $del,
427             always_quote => 'TRUE',
428         }
429     );
430     print $input->header(
431         -type       => 'application/vnd.sun.xml.calc',
432         -encoding   => 'utf-8',
433         -attachment => "$basename.csv",
434         -name       => "$basename.csv"
435     );
436     my @col = ( 'Budget name', 'Budget total' );
437     foreach my $row (@$header) {
438         push @col, $row->{'val'};
439     }
440     push @col, 'Budget remaining';
441
442     $csv->combine(@col);
443     my $str = $csv->string;
444     print "$str\n";
445
446     foreach my $row (@$results) {
447         my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
448         my $l = $row->{'lines'};
449         foreach my $line (@$l) {
450             push @col, $line->{'estimated_amount'};
451         }
452         push @col, $row->{'budget_est_remain'};
453         $csv->combine(@col);
454         my $str = $csv->string;
455         print "$str\n";
456     }
457 }