Bug 12862: OPAC bootstrap - clean up language="javascript"
[koha.git] / admin / aqplan.pl
blob4be57a6dfb758937e14eccd16bf1e938f20e24da
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 Number::Format qw(format_price);
31 use Text::CSV_XS;
33 use C4::Acquisition;
34 use C4::Budgets;
35 use C4::Context;
36 use C4::Output;
37 use C4::Koha;
38 use C4::Auth;
39 use C4::Input;
40 use C4::Debug;
42 my $input = new CGI;
43 #### $input
45 my $dbh = C4::Context->dbh;
47 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
48 { template_name => "admin/aqplan.tt",
49 query => $input,
50 type => "intranet",
51 authnotrequired => 0,
52 flagsrequired => { acquisition => 'planning_manage' },
53 debug => 0,
57 my $budget_period_id = $input->param('budget_period_id');
58 # ' ------- get periods stuff ------------------'
59 # IF PERIOD_ID IS DEFINED, GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
60 my $period = GetBudgetPeriod($budget_period_id);
61 my $count = GetPeriodsCount();
62 my $cur = GetCurrency;
63 $template->param( symbol => $cur->{symbol},
64 currency => $cur->{currency}
66 $template->param( period_button_only => 1 ) if $count == 0;
70 # authcats_loop populates the YUI planning button
71 my $auth_cats_loop = GetBudgetAuthCats($budget_period_id);
72 my $budget_period_id = $period->{'budget_period_id'};
73 my $budget_period_startdate = $period->{'budget_period_startdate'};
74 my $budget_period_enddate = $period->{'budget_period_enddate'};
75 my $budget_period_locked = $period->{'budget_period_locked'};
76 my $budget_period_description = $period->{'budget_period_description'};
79 $template->param(
80 budget_period_id => $budget_period_id,
81 budget_period_locked => $budget_period_locked,
82 budget_period_description => $budget_period_description,
83 auth_cats_loop => $auth_cats_loop,
86 # ------- get periods stuff ------------------
88 my $borrower_id = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
89 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
91 my $periods;
92 my $authcat = $input->param('authcat');
93 my $show_active = $input->param('show_active');
94 my $show_actual = $input->param('show_actual');
95 my $show_percent = $input->param('show_percent');
96 my $output = $input->param("output");
97 my $basename = $input->param("basename");
98 my $del = $input->param("sep");
100 my $show_mine = $input->param('show_mine') ;
102 my @hide_cols = $input->param('hide_cols');
104 my $cur_format = C4::Context->preference("CurrencyFormat");
105 my $num;
107 if ( $cur_format eq 'FR' ) {
108 $num = new Number::Format(
109 'decimal_fill' => '2',
110 'decimal_point' => ',',
111 'int_curr_symbol' => '',
112 'mon_thousands_sep' => ' ',
113 'thousands_sep' => ' ',
114 'mon_decimal_point' => ','
116 } else { # US by default..
117 $num = new Number::Format(
118 'int_curr_symbol' => '',
119 'mon_thousands_sep' => ',',
120 'mon_decimal_point' => '.'
124 if ( $budget_period_locked == 1 && not defined $show_actual ) {
125 $show_actual = 1;
128 $authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given
130 my $budget_id = $input->param('budget_id');
131 my $op = $input->param("op");
133 my $budget_branchcode;
135 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
137 # build categories list
138 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
139 $sth->execute;
141 # the list
142 my @category_list;
144 # a hash, to check that some hardcoded categories exist.
145 my %categories;
146 while ( my ($category) = $sth->fetchrow_array ) {
147 push( @category_list, $category );
148 $categories{$category} = 1;
151 # push koha system categories
152 push( @category_list, 'MONTHS' );
153 push( @category_list, 'ITEMTYPES' );
154 push( @category_list, 'BRANCHES' );
155 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
157 #reorder the list
158 @category_list = sort { $a cmp $b } @category_list;
160 $template->param( authcat_dropbox => {
161 values => \@category_list,
162 default => $authcat,
165 my @budgets = @$budgets_ref;
166 my $CGISort;
167 my @authvals;
168 my %labels;
170 my @names = $input->param();
171 # ------------------------------------------------------------
172 if ( $op eq 'save' ) {
173 #get budgets
174 my ( @buds, @auth_values );
175 foreach my $n (@names) {
176 next if $n =~ m/^[^0-9]/;
177 my @moo = split( ',', $n );
178 push @buds, $moo[0];
179 push @auth_values, $moo[1];
182 #uniq buds and auth
183 my %seen;
184 @buds = grep { !$seen{$_}++ } @buds;
185 @auth_values = grep { !$seen{$_}++ } @auth_values;
186 my @budget_ids;
187 my @budget_lines;
189 foreach my $budget (@buds) {
190 my %budget_line;
191 my @cells_line;
192 my %cell_hash;
194 foreach my $authvalue (@auth_values) {
195 # get actual stats
196 my $cell_name = "$budget,$authvalue";
197 my $estimated_amount = $input->param("$cell_name");
198 my %cell_hash = (
199 estimated_amount => $estimated_amount,
200 authvalue => $authvalue,
201 authcat => $authcat,
202 budget_id => $budget,
203 budget_period_id => $budget_period_id,
205 push( @cells_line, \%cell_hash );
208 %budget_line = (
209 lines => \@cells_line,
211 push( @budget_lines, \%budget_line );
213 my $plan = \@budget_lines;
214 ModBudgetPlan( $plan, $budget_period_id, $authcat );
216 HideCols($authcat, @hide_cols);
220 # ------------------------------------------------------------
221 if ( $authcat =~ m/^Asort/ ) {
222 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
223 my $sth = $dbh->prepare($query);
224 $sth->execute($authcat );
225 if ( $sth->rows > 0 ) {
226 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
227 my $results = $sth->fetchrow_hashref;
228 push @authvals, $results->{authorised_value};
229 $labels{ $results->{authorised_value} } = $results->{lib};
232 $sth->finish;
233 @authvals = sort { $a <=> $b } @authvals;
235 elsif ( $authcat eq 'MONTHS' ) {
237 # build months
238 my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
239 my @end_date = UnixDate( $budget_period_enddate, ( '%Y', '%m', '%d' ) );
241 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
243 #calc number of months between
244 my $months = ( $Dy * 12 ) + $Dm;
245 my $start_month = @start_date[1];
246 my $end_month = ( $Dy * 12 ) + $Dm;
248 for my $mth ( 0 ... $months ) {
249 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
250 $mth = UnixDate( $mth, "%Y-%m" );
251 push( @authvals, $mth );
253 foreach my $vv (@authvals) {
254 $labels{$vv} = $vv;
258 elsif ( $authcat eq 'ITEMTYPES' ) {
259 my $query = qq| SELECT itemtype, description FROM itemtypes |;
260 my $sth = $dbh->prepare($query);
261 $sth->execute( );
263 if ( $sth->rows > 0 ) {
264 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
265 my $results = $sth->fetchrow_hashref;
266 push @authvals, $results->{itemtype};
267 $labels{ $results->{itemtype} } = $results->{description};
270 $sth->finish;
272 } elsif ( $authcat eq 'BRANCHES' ) {
274 my $query = qq| SELECT branchcode, branchname FROM branches |;
275 my $sth = $dbh->prepare($query);
276 $sth->execute();
278 if ( $sth->rows > 0 ) {
279 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
280 my $results = $sth->fetchrow_hashref;
281 push @authvals, $results->{branchcode};
282 $labels{ $results->{branchcode} } = $results->{branchname};
285 $sth->finish;
286 } elsif ($authcat) {
287 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
288 my $sth = $dbh->prepare($query);
289 $sth->execute($authcat);
290 if ( $sth->rows > 0 ) {
291 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
292 my $results = $sth->fetchrow_hashref;
293 push @authvals, $results->{authorised_value};
294 $labels{ $results->{authorised_value} } = $results->{lib};
297 $sth->finish;
300 my @authvals_row;
301 my $i=1;
302 foreach my $val (@authvals) {
303 my %auth_hash;
304 $auth_hash{val} = $labels{$val};
305 $auth_hash{code} = $val;
306 $auth_hash{colnum} = $i++;
308 # display lookup
309 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
311 push( @authvals_row, \%auth_hash );
314 #get budgets
315 my ( @buds, @auth_values );
316 foreach my $n (@names) {
317 next if $n =~ m/^[^0-9]/;
318 $n =~ m/(\d*),(.*)/;
319 push @buds, $1;
320 push @auth_values, $2;
324 # ------------------------------------------------------------
325 # DEFAULT DISPLAY BEGINS
327 my $CGIextChoice = ( 'CSV' ); # FIXME translation
328 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
330 my ( @budget_lines, %cell_hash );
333 foreach my $budget (@budgets) {
334 my $budget_lock;
336 unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
337 $budget_lock = 1
340 # check budget permission
341 if ( $period->{budget_period_locked} == 1 ) {
342 $budget_lock = 1;
343 } elsif ( $budget->{budget_permission} == 1 ) {
344 $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
345 } elsif ( $budget->{budget_permission} == 2 ) {
346 $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
349 # allow hard-coded itemtype and branch planning
350 unless ( $authcat eq 'ITEMTYPES'
351 or $authcat eq 'BRANCHES'
352 or $authcat eq 'MONTHS' ) {
354 # but skip budgets that dont match the current auth-category
355 next if ( $budget->{'sort1_authcat'} ne $authcat
356 && $budget->{'sort2_authcat'} ne $authcat );
359 my %budget_line; # each row of the table
360 my @cells_line;
361 my $actual_spent;
362 my $estimated_spent;
364 my $i = 0;
365 foreach my $authvalue (@authvals) {
367 # get actual stats
368 my %cell = (
369 budget_id => $budget->{'budget_id'},
370 budget_period_id => $budget->{'budget_period_id'},
371 cell_name => $budget->{'budget_id'} . ',' . $authvalue,
372 authvalue => $authvalue,
373 authcat => $authcat,
374 cell_authvalue => $authvalue,
375 budget_lock => $budget_lock,
378 my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
379 $cell{actual_amount} = sprintf( "%.2f", $actual );
380 $cell{estimated_amount} = sprintf( "%.2f", $estimated );
381 $cell{display} = $authvals_row[$i]{display};
382 $cell{colnum} = $i;
384 $actual_spent += $cell{actual_amount};
385 $estimated_spent += $cell{estimated_amount};
388 push( @cells_line, \%cell );
389 $i++;
392 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
393 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
395 %budget_line = (
396 lines => \@cells_line,
397 budget_name_indent => $budget->{budget_name_indent},
398 budget_amount_formatted => $num->format_price( $budget->{budget_amount} ),
399 budget_amount => $budget->{budget_amount},
400 budget_alloc => $budget->{budget_alloc},
401 budget_act_remain => sprintf( "%.2f", $budget_act_remain ),
402 budget_est_remain => sprintf( "%.2f", $budget_est_remain ),
403 budget_id => $budget->{budget_id},
404 budget_lock => $budget_lock,
409 $budget_line{est_negative} = '1' if $budget_est_remain < 0;
410 $budget_line{est_positive} = '1' if $budget_est_remain > 0;
411 $budget_line{act_negative} = '1' if $budget_act_remain < 0;
412 $budget_line{act_positive} = '1' if $budget_act_remain > 0;
414 # skip if active set , and spent == 0
415 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
417 push( @budget_lines, \%budget_line );
420 if ( $output eq "file" ) {
421 _print_to_csv(\@authvals_row, \@budget_lines);
422 exit(1);
425 $template->param(
426 authvals_row => \@authvals_row,
427 budget_lines => \@budget_lines,
428 budget_period_description => $period->{'budget_period_description'},
429 budget_period_locked => $period->{'budget_period_locked'},
430 budget_period_id => $budget_period_id,
431 authcat => $authcat,
432 show_active => $show_active,
433 show_actual => $show_actual,
434 show_percent => $show_percent,
435 show_mine => $show_mine,
436 cur_format => $cur_format,
437 CGIextChoice => $CGIextChoice,
438 CGIsepChoice => $CGIsepChoice,
440 authvals => \@authvals_row,
441 hide_cols_loop => \@hide_cols
444 output_html_with_http_headers $input, $cookie, $template->output;
446 sub _print_to_csv {
447 my ( $header, $results ) = @_;
449 binmode STDOUT, ':encoding(UTF-8)';
451 my $csv = Text::CSV_XS->new(
452 { sep_char => $del,
453 always_quote => 'TRUE',
456 print $input->header(
457 -type => 'application/vnd.sun.xml.calc',
458 -encoding => 'utf-8',
459 -attachment => "$basename.csv",
460 -name => "$basename.csv"
462 my @col = ( 'Budget name', 'Budget total' );
463 foreach my $row (@$header) {
464 push @col, $row->{'val'};
466 push @col, 'Budget remaining';
468 $csv->combine(@col);
469 my $str = $csv->string;
470 print "$str\n";
472 foreach my $row (@$results) {
473 $row->{'budget_name_indent'} =~ s/&nbsp;/ /g;
474 my @col = ( $row->{'budget_name_indent'}, $row->{'budget_amount'} );
475 my $l = $row->{'lines'};
476 foreach my $line (@$l) {
477 push @col, $line->{'estimated_amount'};
479 push @col, $row->{'budget_est_remain'};
480 $csv->combine(@col);
481 my $str = $csv->string;
482 print "$str\n";