Bug 14589: Adjust authorities_merge_ajax and replace some indirect syntax
[koha.git] / admin / aqplan.pl
blobe155bd649490a5595723ceca759cb0f222d41daf
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 Text::CSV_XS;
31 use C4::Acquisition;
32 use C4::Budgets;
33 use C4::Context;
34 use C4::Output;
35 use C4::Koha;
36 use C4::Auth;
37 use C4::Debug;
39 my $input = new CGI;
40 #### $input
42 my $dbh = C4::Context->dbh;
44 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
45 { template_name => "admin/aqplan.tt",
46 query => $input,
47 type => "intranet",
48 authnotrequired => 0,
49 flagsrequired => { acquisition => 'planning_manage' },
50 debug => 0,
54 my $budget_period_id = $input->param('budget_period_id');
55 # ' ------- get periods stuff ------------------'
56 # IF PERIOD_ID IS DEFINED, GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
57 my $period = GetBudgetPeriod($budget_period_id);
58 my $count = GetPeriodsCount();
59 my $cur = GetCurrency;
60 $template->param( symbol => $cur->{symbol},
61 currency => $cur->{currency}
63 $template->param( period_button_only => 1 ) if $count == 0;
67 # authcats_loop populates the YUI planning button
68 my $auth_cats_loop = GetBudgetAuthCats($budget_period_id);
69 my $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'};
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,
83 # ------- get periods stuff ------------------
85 my $borrower_id = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
86 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
88 my $periods;
89 my $authcat = $input->param('authcat');
90 my $show_active = $input->param('show_active');
91 my $show_actual = $input->param('show_actual');
92 my $show_percent = $input->param('show_percent');
93 my $output = $input->param("output");
94 my $basename = $input->param("basename");
95 my $del = $input->param("sep");
97 my $show_mine = $input->param('show_mine') ;
99 my @hide_cols = $input->param('hide_cols');
101 if ( $budget_period_locked == 1 && not defined $show_actual ) {
102 $show_actual = 1;
105 $authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given
107 my $budget_id = $input->param('budget_id');
108 my $op = $input->param("op");
110 my $budget_branchcode;
112 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
114 # build categories list
115 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
116 $sth->execute;
118 # the list
119 my @category_list;
121 # a hash, to check that some hardcoded categories exist.
122 my %categories;
123 while ( my ($category) = $sth->fetchrow_array ) {
124 push( @category_list, $category );
125 $categories{$category} = 1;
128 # push koha system categories
129 push( @category_list, 'MONTHS' );
130 push( @category_list, 'ITEMTYPES' );
131 push( @category_list, 'BRANCHES' );
132 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
134 #reorder the list
135 @category_list = sort { $a cmp $b } @category_list;
137 $template->param( authcat_dropbox => {
138 values => \@category_list,
139 default => $authcat,
142 my @budgets = @$budgets_ref;
143 my $CGISort;
144 my @authvals;
145 my %labels;
147 my @names = $input->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];
159 #uniq buds and auth
160 my %seen;
161 @buds = grep { !$seen{$_}++ } @buds;
162 @auth_values = grep { !$seen{$_}++ } @auth_values;
163 my @budget_ids;
164 my @budget_lines;
166 foreach my $budget (@buds) {
167 my %budget_line;
168 my @cells_line;
169 my %cell_hash;
171 foreach my $authvalue (@auth_values) {
172 # get actual stats
173 my $cell_name = "$budget,$authvalue";
174 my $estimated_amount = $input->param("$cell_name");
175 my %cell_hash = (
176 estimated_amount => $estimated_amount,
177 authvalue => $authvalue,
178 authcat => $authcat,
179 budget_id => $budget,
180 budget_period_id => $budget_period_id,
182 push( @cells_line, \%cell_hash );
185 %budget_line = (
186 lines => \@cells_line,
188 push( @budget_lines, \%budget_line );
190 my $plan = \@budget_lines;
191 ModBudgetPlan( $plan, $budget_period_id, $authcat );
193 HideCols($authcat, @hide_cols);
197 # ------------------------------------------------------------
198 if ( $authcat =~ m/^Asort/ ) {
199 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
200 my $sth = $dbh->prepare($query);
201 $sth->execute($authcat );
202 if ( $sth->rows > 0 ) {
203 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
204 my $results = $sth->fetchrow_hashref;
205 push @authvals, $results->{authorised_value};
206 $labels{ $results->{authorised_value} } = $results->{lib};
209 $sth->finish;
210 @authvals = sort { $a <=> $b } @authvals;
212 elsif ( $authcat eq 'MONTHS' ) {
214 # build months
215 my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
216 my @end_date = UnixDate( $budget_period_enddate, ( '%Y', '%m', '%d' ) );
218 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
220 #calc number of months between
221 my $months = ( $Dy * 12 ) + $Dm;
222 my $start_month = @start_date[1];
223 my $end_month = ( $Dy * 12 ) + $Dm;
225 for my $mth ( 0 ... $months ) {
226 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
227 $mth = UnixDate( $mth, "%Y-%m" );
228 push( @authvals, $mth );
230 foreach my $vv (@authvals) {
231 $labels{$vv} = $vv;
235 elsif ( $authcat eq 'ITEMTYPES' ) {
236 my $query = qq| SELECT itemtype, description FROM itemtypes |;
237 my $sth = $dbh->prepare($query);
238 $sth->execute( );
240 if ( $sth->rows > 0 ) {
241 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
242 my $results = $sth->fetchrow_hashref;
243 push @authvals, $results->{itemtype};
244 $labels{ $results->{itemtype} } = $results->{description};
247 $sth->finish;
249 } elsif ( $authcat eq 'BRANCHES' ) {
251 my $query = qq| SELECT branchcode, branchname FROM branches |;
252 my $sth = $dbh->prepare($query);
253 $sth->execute();
255 if ( $sth->rows > 0 ) {
256 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
257 my $results = $sth->fetchrow_hashref;
258 push @authvals, $results->{branchcode};
259 $labels{ $results->{branchcode} } = $results->{branchname};
262 $sth->finish;
263 } elsif ($authcat) {
264 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
265 my $sth = $dbh->prepare($query);
266 $sth->execute($authcat);
267 if ( $sth->rows > 0 ) {
268 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
269 my $results = $sth->fetchrow_hashref;
270 push @authvals, $results->{authorised_value};
271 $labels{ $results->{authorised_value} } = $results->{lib};
274 $sth->finish;
277 my @authvals_row;
278 my $i=1;
279 foreach my $val (@authvals) {
280 my %auth_hash;
281 $auth_hash{val} = $labels{$val};
282 $auth_hash{code} = $val;
283 $auth_hash{colnum} = $i++;
285 # display lookup
286 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
288 push( @authvals_row, \%auth_hash );
291 #get budgets
292 my ( @buds, @auth_values );
293 foreach my $n (@names) {
294 next if $n =~ m/^[^0-9]/;
295 $n =~ m/(\d*),(.*)/;
296 push @buds, $1;
297 push @auth_values, $2;
301 # ------------------------------------------------------------
302 # DEFAULT DISPLAY BEGINS
304 my $CGIextChoice = ( 'CSV' ); # FIXME translation
305 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
307 my ( @budget_lines, %cell_hash );
310 foreach my $budget (@budgets) {
311 my $budget_lock;
313 unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
314 $budget_lock = 1
317 # check budget permission
318 if ( $period->{budget_period_locked} == 1 ) {
319 $budget_lock = 1;
320 } elsif ( $budget->{budget_permission} == 1 ) {
321 $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
322 } elsif ( $budget->{budget_permission} == 2 ) {
323 $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
326 # allow hard-coded itemtype and branch planning
327 unless ( $authcat eq 'ITEMTYPES'
328 or $authcat eq 'BRANCHES'
329 or $authcat eq 'MONTHS' ) {
331 # but skip budgets that don't match the current auth-category
332 next if ( $budget->{'sort1_authcat'} ne $authcat
333 && $budget->{'sort2_authcat'} ne $authcat );
336 my %budget_line; # each row of the table
337 my @cells_line;
338 my $actual_spent;
339 my $estimated_spent;
341 my $i = 0;
342 foreach my $authvalue (@authvals) {
344 # get actual stats
345 my %cell = (
346 budget_id => $budget->{'budget_id'},
347 budget_period_id => $budget->{'budget_period_id'},
348 cell_name => $budget->{'budget_id'} . ',' . $authvalue,
349 authvalue => $authvalue,
350 authcat => $authcat,
351 cell_authvalue => $authvalue,
352 budget_lock => $budget_lock,
355 my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
356 $cell{actual_amount} = sprintf( "%.2f", $actual );
357 $cell{estimated_amount} = sprintf( "%.2f", $estimated );
358 $cell{display} = $authvals_row[$i]{display};
359 $cell{colnum} = $i;
361 $actual_spent += $cell{actual_amount};
362 $estimated_spent += $cell{estimated_amount};
365 push( @cells_line, \%cell );
366 $i++;
369 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
370 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
372 %budget_line = (
373 lines => \@cells_line,
374 budget_name => $budget->{budget_name},
375 budget_amount => $budget->{budget_amount},
376 budget_alloc => $budget->{budget_alloc},
377 budget_act_remain => sprintf( "%.2f", $budget_act_remain ),
378 budget_est_remain => sprintf( "%.2f", $budget_est_remain ),
379 budget_id => $budget->{budget_id},
380 budget_lock => $budget_lock,
385 $budget_line{est_negative} = '1' if $budget_est_remain < 0;
386 $budget_line{est_positive} = '1' if $budget_est_remain > 0;
387 $budget_line{act_negative} = '1' if $budget_act_remain < 0;
388 $budget_line{act_positive} = '1' if $budget_act_remain > 0;
390 # skip if active set , and spent == 0
391 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
393 push( @budget_lines, \%budget_line );
396 if ( $output eq "file" ) {
397 _print_to_csv(\@authvals_row, \@budget_lines);
398 exit(1);
401 my $branchloop = C4::Branch::GetBranchesLoop();
402 $template->param(
403 authvals_row => \@authvals_row,
404 budget_lines => \@budget_lines,
405 budget_period_description => $period->{'budget_period_description'},
406 budget_period_locked => $period->{'budget_period_locked'},
407 budget_period_id => $budget_period_id,
408 authcat => $authcat,
409 show_active => $show_active,
410 show_actual => $show_actual,
411 show_percent => $show_percent,
412 show_mine => $show_mine,
413 CGIextChoice => $CGIextChoice,
414 CGIsepChoice => $CGIsepChoice,
416 authvals => \@authvals_row,
417 hide_cols_loop => \@hide_cols,
418 branchloop => $branchloop,
421 output_html_with_http_headers $input, $cookie, $template->output;
423 sub _print_to_csv {
424 my ( $header, $results ) = @_;
426 binmode STDOUT, ':encoding(UTF-8)';
428 my $csv = Text::CSV_XS->new(
429 { sep_char => $del,
430 always_quote => 'TRUE',
433 print $input->header(
434 -type => 'application/vnd.sun.xml.calc',
435 -encoding => 'utf-8',
436 -attachment => "$basename.csv",
437 -name => "$basename.csv"
439 my @col = ( 'Budget name', 'Budget total' );
440 foreach my $row (@$header) {
441 push @col, $row->{'val'};
443 push @col, 'Budget remaining';
445 $csv->combine(@col);
446 my $str = $csv->string;
447 print "$str\n";
449 foreach my $row (@$results) {
450 my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
451 my $l = $row->{'lines'};
452 foreach my $line (@$l) {
453 push @col, $line->{'estimated_amount'};
455 push @col, $row->{'budget_est_remain'};
456 $csv->combine(@col);
457 my $str = $csv->string;
458 print "$str\n";