Bug 14977: Followup to fix issue with NewsChannels.t
[koha.git] / admin / aqplan.pl
blob082faeb4ffa796fdc8e6ad8d7f2119c27768b7f2
1 #!/usr/bin/perl
3 # Copyright 2008-2009 BibLibre SARL
4 # This file is part of Koha.
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.
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.
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>.
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)
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;
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;
40 my $input = new CGI;
41 #### $input
43 my $dbh = C4::Context->dbh;
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,
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}
64 $template->param( period_button_only => 1 ) if $count == 0;
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'};
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,
84 # ------- get periods stuff ------------------
86 my $borrower_id = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
87 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
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");
98 my $show_mine = $input->param('show_mine') ;
100 my @hide_cols = $input->param('hide_cols');
102 if ( $budget_period_locked == 1 && not defined $show_actual ) {
103 $show_actual = 1;
106 $authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given
108 my $budget_id = $input->param('budget_id');
109 my $op = $input->param("op");
111 my $budget_branchcode;
113 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
115 # build categories list
116 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
117 $sth->execute;
119 # the list
120 my @category_list;
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;
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;
135 #reorder the list
136 @category_list = sort { $a cmp $b } @category_list;
138 $template->param( authcat_dropbox => {
139 values => \@category_list,
140 default => $authcat,
143 my @budgets = @$budgets_ref;
144 my $CGISort;
145 my @authvals;
146 my %labels;
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];
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;
167 foreach my $budget (@buds) {
168 my %budget_line;
169 my @cells_line;
170 my %cell_hash;
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,
183 push( @cells_line, \%cell_hash );
186 %budget_line = (
187 lines => \@cells_line,
189 push( @budget_lines, \%budget_line );
191 my $plan = \@budget_lines;
192 ModBudgetPlan( $plan, $budget_period_id, $authcat );
194 HideCols($authcat, @hide_cols);
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};
210 $sth->finish;
211 @authvals = sort { $a <=> $b } @authvals;
213 elsif ( $authcat eq 'MONTHS' ) {
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' ) );
219 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
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;
226 for my $mth ( 0 ... $months ) {
227 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
228 $mth = UnixDate( $mth, "%Y-%m" );
229 push( @authvals, $mth );
231 foreach my $vv (@authvals) {
232 $labels{$vv} = $vv;
236 elsif ( $authcat eq 'ITEMTYPES' ) {
237 my $query = qq| SELECT itemtype, description FROM itemtypes |;
238 my $sth = $dbh->prepare($query);
239 $sth->execute( );
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};
248 $sth->finish;
250 } elsif ( $authcat eq 'BRANCHES' ) {
252 my $query = qq| SELECT branchcode, branchname FROM branches |;
253 my $sth = $dbh->prepare($query);
254 $sth->execute();
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};
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};
275 $sth->finish;
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++;
286 # display lookup
287 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
289 push( @authvals_row, \%auth_hash );
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;
302 # ------------------------------------------------------------
303 # DEFAULT DISPLAY BEGINS
305 my $CGIextChoice = ( 'CSV' ); # FIXME translation
306 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
308 my ( @budget_lines, %cell_hash );
311 foreach my $budget (@budgets) {
312 my $budget_lock;
314 unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
315 $budget_lock = 1
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};
327 # allow hard-coded itemtype and branch planning
328 unless ( $authcat eq 'ITEMTYPES'
329 or $authcat eq 'BRANCHES'
330 or $authcat eq 'MONTHS' ) {
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 );
337 my %budget_line; # each row of the table
338 my @cells_line;
339 my $actual_spent;
340 my $estimated_spent;
342 my $i = 0;
343 foreach my $authvalue (@authvals) {
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,
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;
362 $actual_spent += $cell{actual_amount};
363 $estimated_spent += $cell{estimated_amount};
366 push( @cells_line, \%cell );
367 $i++;
370 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
371 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
373 %budget_line = (
374 lines => \@cells_line,
375 budget_name => $budget->{budget_name},
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,
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;
391 # skip if active set , and spent == 0
392 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
394 push( @budget_lines, \%budget_line );
397 if ( $output eq "file" ) {
398 _print_to_csv(\@authvals_row, \@budget_lines);
399 exit(1);
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,
417 authvals => \@authvals_row,
418 hide_cols_loop => \@hide_cols,
419 branchloop => $branchloop,
422 output_html_with_http_headers $input, $cookie, $template->output;
424 sub _print_to_csv {
425 my ( $header, $results ) = @_;
427 binmode STDOUT, ':encoding(UTF-8)';
429 my $csv = Text::CSV_XS->new(
430 { sep_char => $del,
431 always_quote => 'TRUE',
434 print $input->header(
435 -type => 'application/vnd.sun.xml.calc',
436 -encoding => 'utf-8',
437 -attachment => "$basename.csv",
438 -name => "$basename.csv"
440 my @col = ( 'Budget name', 'Budget total' );
441 foreach my $row (@$header) {
442 push @col, $row->{'val'};
444 push @col, 'Budget remaining';
446 $csv->combine(@col);
447 my $str = $csv->string;
448 print "$str\n";
450 foreach my $row (@$results) {
451 my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
452 my $l = $row->{'lines'};
453 foreach my $line (@$l) {
454 push @col, $line->{'estimated_amount'};
456 push @col, $row->{'budget_est_remain'};
457 $csv->combine(@col);
458 my $str = $csv->string;
459 print "$str\n";