Bug 1861 [QA Followup] - Fix Check_Userid and unit tests
[koha.git] / admin / aqplan.pl
blobcc397fe1979585824b189560d2a5d860eb489da7
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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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;
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::Input;
39 use C4::Debug;
41 my $input = new CGI;
42 #### $input
44 my $dbh = C4::Context->dbh;
46 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
47 { template_name => "admin/aqplan.tt",
48 query => $input,
49 type => "intranet",
50 authnotrequired => 0,
51 flagsrequired => { acquisition => 'planning_manage' },
52 debug => 0,
56 my $budget_period_id = $input->param('budget_period_id');
57 # ' ------- get periods stuff ------------------'
58 # IF PERIOD_ID IS DEFINED, GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
59 my $period = GetBudgetPeriod($budget_period_id);
60 my $count = GetPeriodsCount();
61 my $cur = GetCurrency;
62 $template->param( symbol => $cur->{symbol},
63 currency => $cur->{currency}
65 $template->param( period_button_only => 1 ) if $count == 0;
69 # authcats_loop populates the YUI planning button
70 my $auth_cats_loop = GetBudgetAuthCats($budget_period_id);
71 my $budget_period_id = $period->{'budget_period_id'};
72 my $budget_period_startdate = $period->{'budget_period_startdate'};
73 my $budget_period_enddate = $period->{'budget_period_enddate'};
74 my $budget_period_locked = $period->{'budget_period_locked'};
75 my $budget_period_description = $period->{'budget_period_description'};
78 $template->param(
79 budget_period_id => $budget_period_id,
80 budget_period_locked => $budget_period_locked,
81 budget_period_description => $budget_period_description,
82 auth_cats_loop => $auth_cats_loop,
85 # ------- get periods stuff ------------------
87 my $borrower_id = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
88 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
90 my $periods;
91 my $authcat = $input->param('authcat');
92 my $show_active = $input->param('show_active');
93 my $show_actual = $input->param('show_actual');
94 my $show_percent = $input->param('show_percent');
95 my $output = $input->param("output");
96 my $basename = $input->param("basename");
97 my $del = $input->param("sep");
99 my $show_mine = $input->param('show_mine') ;
101 my @hide_cols = $input->param('hide_cols');
103 if ( $budget_period_locked == 1 && not defined $show_actual ) {
104 $show_actual = 1;
107 $authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given
109 my $budget_id = $input->param('budget_id');
110 my $op = $input->param("op");
112 my $budget_branchcode;
114 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
116 # build categories list
117 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
118 $sth->execute;
120 # the list
121 my @category_list;
123 # a hash, to check that some hardcoded categories exist.
124 my %categories;
125 while ( my ($category) = $sth->fetchrow_array ) {
126 push( @category_list, $category );
127 $categories{$category} = 1;
130 # push koha system categories
131 push( @category_list, 'MONTHS' );
132 push( @category_list, 'ITEMTYPES' );
133 push( @category_list, 'BRANCHES' );
134 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
136 #reorder the list
137 @category_list = sort { $a cmp $b } @category_list;
139 $template->param( authcat_dropbox => {
140 values => \@category_list,
141 default => $authcat,
144 my @budgets = @$budgets_ref;
145 my $CGISort;
146 my @authvals;
147 my %labels;
149 my @names = $input->param();
150 # ------------------------------------------------------------
151 if ( $op eq 'save' ) {
152 #get budgets
153 my ( @buds, @auth_values );
154 foreach my $n (@names) {
155 next if $n =~ m/^[^0-9]/;
156 my @moo = split( ',', $n );
157 push @buds, $moo[0];
158 push @auth_values, $moo[1];
161 #uniq buds and auth
162 my %seen;
163 @buds = grep { !$seen{$_}++ } @buds;
164 @auth_values = grep { !$seen{$_}++ } @auth_values;
165 my @budget_ids;
166 my @budget_lines;
168 foreach my $budget (@buds) {
169 my %budget_line;
170 my @cells_line;
171 my %cell_hash;
173 foreach my $authvalue (@auth_values) {
174 # get actual stats
175 my $cell_name = "$budget,$authvalue";
176 my $estimated_amount = $input->param("$cell_name");
177 my %cell_hash = (
178 estimated_amount => $estimated_amount,
179 authvalue => $authvalue,
180 authcat => $authcat,
181 budget_id => $budget,
182 budget_period_id => $budget_period_id,
184 push( @cells_line, \%cell_hash );
187 %budget_line = (
188 lines => \@cells_line,
190 push( @budget_lines, \%budget_line );
192 my $plan = \@budget_lines;
193 ModBudgetPlan( $plan, $budget_period_id, $authcat );
195 HideCols($authcat, @hide_cols);
199 # ------------------------------------------------------------
200 if ( $authcat =~ m/^Asort/ ) {
201 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
202 my $sth = $dbh->prepare($query);
203 $sth->execute($authcat );
204 if ( $sth->rows > 0 ) {
205 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
206 my $results = $sth->fetchrow_hashref;
207 push @authvals, $results->{authorised_value};
208 $labels{ $results->{authorised_value} } = $results->{lib};
211 $sth->finish;
212 @authvals = sort { $a <=> $b } @authvals;
214 elsif ( $authcat eq 'MONTHS' ) {
216 # build months
217 my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
218 my @end_date = UnixDate( $budget_period_enddate, ( '%Y', '%m', '%d' ) );
220 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
222 #calc number of months between
223 my $months = ( $Dy * 12 ) + $Dm;
224 my $start_month = @start_date[1];
225 my $end_month = ( $Dy * 12 ) + $Dm;
227 for my $mth ( 0 ... $months ) {
228 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
229 $mth = UnixDate( $mth, "%Y-%m" );
230 push( @authvals, $mth );
232 foreach my $vv (@authvals) {
233 $labels{$vv} = $vv;
237 elsif ( $authcat eq 'ITEMTYPES' ) {
238 my $query = qq| SELECT itemtype, description FROM itemtypes |;
239 my $sth = $dbh->prepare($query);
240 $sth->execute( );
242 if ( $sth->rows > 0 ) {
243 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
244 my $results = $sth->fetchrow_hashref;
245 push @authvals, $results->{itemtype};
246 $labels{ $results->{itemtype} } = $results->{description};
249 $sth->finish;
251 } elsif ( $authcat eq 'BRANCHES' ) {
253 my $query = qq| SELECT branchcode, branchname FROM branches |;
254 my $sth = $dbh->prepare($query);
255 $sth->execute();
257 if ( $sth->rows > 0 ) {
258 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
259 my $results = $sth->fetchrow_hashref;
260 push @authvals, $results->{branchcode};
261 $labels{ $results->{branchcode} } = $results->{branchname};
264 $sth->finish;
265 } elsif ($authcat) {
266 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
267 my $sth = $dbh->prepare($query);
268 $sth->execute($authcat);
269 if ( $sth->rows > 0 ) {
270 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
271 my $results = $sth->fetchrow_hashref;
272 push @authvals, $results->{authorised_value};
273 $labels{ $results->{authorised_value} } = $results->{lib};
276 $sth->finish;
279 my @authvals_row;
280 my $i=1;
281 foreach my $val (@authvals) {
282 my %auth_hash;
283 $auth_hash{val} = $labels{$val};
284 $auth_hash{code} = $val;
285 $auth_hash{colnum} = $i++;
287 # display lookup
288 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
290 push( @authvals_row, \%auth_hash );
293 #get budgets
294 my ( @buds, @auth_values );
295 foreach my $n (@names) {
296 next if $n =~ m/^[^0-9]/;
297 $n =~ m/(\d*),(.*)/;
298 push @buds, $1;
299 push @auth_values, $2;
303 # ------------------------------------------------------------
304 # DEFAULT DISPLAY BEGINS
306 my $CGIextChoice = ( 'CSV' ); # FIXME translation
307 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
309 my ( @budget_lines, %cell_hash );
312 foreach my $budget (@budgets) {
313 my $budget_lock;
315 unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
316 $budget_lock = 1
319 # check budget permission
320 if ( $period->{budget_period_locked} == 1 ) {
321 $budget_lock = 1;
322 } elsif ( $budget->{budget_permission} == 1 ) {
323 $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
324 } elsif ( $budget->{budget_permission} == 2 ) {
325 $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
328 # allow hard-coded itemtype and branch planning
329 unless ( $authcat eq 'ITEMTYPES'
330 or $authcat eq 'BRANCHES'
331 or $authcat eq 'MONTHS' ) {
333 # but skip budgets that dont match the current auth-category
334 next if ( $budget->{'sort1_authcat'} ne $authcat
335 && $budget->{'sort2_authcat'} ne $authcat );
338 my %budget_line; # each row of the table
339 my @cells_line;
340 my $actual_spent;
341 my $estimated_spent;
343 my $i = 0;
344 foreach my $authvalue (@authvals) {
346 # get actual stats
347 my %cell = (
348 budget_id => $budget->{'budget_id'},
349 budget_period_id => $budget->{'budget_period_id'},
350 cell_name => $budget->{'budget_id'} . ',' . $authvalue,
351 authvalue => $authvalue,
352 authcat => $authcat,
353 cell_authvalue => $authvalue,
354 budget_lock => $budget_lock,
357 my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
358 $cell{actual_amount} = sprintf( "%.2f", $actual );
359 $cell{estimated_amount} = sprintf( "%.2f", $estimated );
360 $cell{display} = $authvals_row[$i]{display};
361 $cell{colnum} = $i;
363 $actual_spent += $cell{actual_amount};
364 $estimated_spent += $cell{estimated_amount};
367 push( @cells_line, \%cell );
368 $i++;
371 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
372 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
374 %budget_line = (
375 lines => \@cells_line,
376 budget_name_indent => $budget->{budget_name_indent},
377 budget_amount => $budget->{budget_amount},
378 budget_alloc => $budget->{budget_alloc},
379 budget_act_remain => sprintf( "%.2f", $budget_act_remain ),
380 budget_est_remain => sprintf( "%.2f", $budget_est_remain ),
381 budget_id => $budget->{budget_id},
382 budget_lock => $budget_lock,
387 $budget_line{est_negative} = '1' if $budget_est_remain < 0;
388 $budget_line{est_positive} = '1' if $budget_est_remain > 0;
389 $budget_line{act_negative} = '1' if $budget_act_remain < 0;
390 $budget_line{act_positive} = '1' if $budget_act_remain > 0;
392 # skip if active set , and spent == 0
393 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
395 push( @budget_lines, \%budget_line );
398 if ( $output eq "file" ) {
399 _print_to_csv(\@authvals_row, \@budget_lines);
400 exit(1);
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
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 $row->{'budget_name_indent'} =~ s/&nbsp;/ /g;
451 my @col = ( $row->{'budget_name_indent'}, $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";