Bug 7143 about.tt indentation fixes
[koha.git] / admin / aqplan.pl
blobffb11456060a81e6e73ab51826cf9890e08c5a1c
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.tmpl",
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;
159 my $tab_list = CGI::scrolling_list(
160 -name => 'authcat',
161 -id => 'authcat',
162 -values => \@category_list,
163 -default => $authcat,
164 -size => 1,
165 -tabindex => '',
166 -multiple => 0,
169 $template->param( authcat_dropbox => $tab_list );
171 my @budgets = @$budgets_ref;
172 my $CGISort;
173 my @authvals;
174 my %labels;
176 my @names = $input->param();
177 # ------------------------------------------------------------
178 if ( $op eq 'save' ) {
179 #get budgets
180 my ( @buds, @auth_values );
181 foreach my $n (@names) {
182 next if $n =~ m/^[^0-9]/;
183 my @moo = split( ',', $n );
184 push @buds, $moo[0];
185 push @auth_values, $moo[1];
188 #uniq buds and auth
189 my %seen;
190 @buds = grep { !$seen{$_}++ } @buds;
191 @auth_values = grep { !$seen{$_}++ } @auth_values;
192 my @budget_ids;
193 my @budget_lines;
195 foreach my $budget (@buds) {
196 my %budget_line;
197 my @cells_line;
198 my %cell_hash;
200 foreach my $authvalue (@auth_values) {
201 # get actual stats
202 my $cell_name = "$budget,$authvalue";
203 my $estimated_amount = $input->param("$cell_name");
204 my %cell_hash = (
205 estimated_amount => $estimated_amount,
206 authvalue => $authvalue,
207 authcat => $authcat,
208 budget_id => $budget,
209 budget_period_id => $budget_period_id,
211 push( @cells_line, \%cell_hash );
214 %budget_line = (
215 lines => \@cells_line,
217 push( @budget_lines, \%budget_line );
219 my $plan = \@budget_lines;
220 ModBudgetPlan( $plan, $budget_period_id, $authcat );
222 HideCols($authcat, @hide_cols);
226 # ------------------------------------------------------------
227 if ( $authcat =~ m/^Asort/ ) {
228 # ----------- copied from C4::Input::buildCGIsort()
229 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
230 my $sth = $dbh->prepare($query);
231 $sth->execute($authcat );
232 if ( $sth->rows > 0 ) {
233 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
234 my $results = $sth->fetchrow_hashref;
235 push @authvals, $results->{authorised_value};
236 $labels{ $results->{authorised_value} } = $results->{lib};
239 $sth->finish;
240 @authvals = sort { $a <=> $b } @authvals;
242 elsif ( $authcat eq 'MONTHS' ) {
244 # build months
245 my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
246 my @end_date = UnixDate( $budget_period_enddate, ( '%Y', '%m', '%d' ) );
248 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
250 #calc number of months between
251 my $months = ( $Dy * 12 ) + $Dm;
252 my $start_month = @start_date[1];
253 my $end_month = ( $Dy * 12 ) + $Dm;
255 for my $mth ( 0 ... $months ) {
256 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
257 $mth = UnixDate( $mth, "%Y-%m" );
258 push( @authvals, $mth );
260 foreach my $vv (@authvals) {
261 $labels{$vv} = $vv;
265 elsif ( $authcat eq 'ITEMTYPES' ) {
266 my $query = qq| SELECT itemtype, description FROM itemtypes |;
267 my $sth = $dbh->prepare($query);
268 $sth->execute( );
270 if ( $sth->rows > 0 ) {
271 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
272 my $results = $sth->fetchrow_hashref;
273 push @authvals, $results->{itemtype};
274 $labels{ $results->{itemtype} } = $results->{description};
277 $sth->finish;
279 } elsif ( $authcat eq 'BRANCHES' ) {
281 my $query = qq| SELECT branchcode, branchname FROM branches |;
282 my $sth = $dbh->prepare($query);
283 $sth->execute();
285 if ( $sth->rows > 0 ) {
286 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
287 my $results = $sth->fetchrow_hashref;
288 push @authvals, $results->{branchcode};
289 $labels{ $results->{branchcode} } = $results->{branchname};
292 $sth->finish;
293 } elsif ($authcat) {
294 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
295 my $sth = $dbh->prepare($query);
296 $sth->execute($authcat);
297 if ( $sth->rows > 0 ) {
298 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
299 my $results = $sth->fetchrow_hashref;
300 push @authvals, $results->{authorised_value};
301 $labels{ $results->{authorised_value} } = $results->{lib};
304 $sth->finish;
307 my @authvals_row;
308 my $i=1;
309 foreach my $val (@authvals) {
310 my %auth_hash;
311 $auth_hash{val} = $labels{$val};
312 $auth_hash{code} = $val;
313 $auth_hash{colnum} = $i++;
315 # display lookup
316 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
318 push( @authvals_row, \%auth_hash );
321 #get budgets
322 my ( @buds, @auth_values );
323 foreach my $n (@names) {
324 next if $n =~ m/^[^0-9]/;
325 $n =~ m/(\d*),(.*)/;
326 push @buds, $1;
327 push @auth_values, $2;
331 # ------------------------------------------------------------
332 # DEFAULT DISPLAY BEGINS
334 my $CGIextChoice = CGI::scrolling_list(
335 -name => 'MIME',
336 -id => 'MIME',
337 -values => ['CSV'], # FIXME translation
338 -size => 1,
339 -multiple => 0
342 my @dels = ( C4::Context->preference("delimiter") );
343 my $CGIsepChoice = CGI::scrolling_list(
344 -name => 'sep',
345 -id => 'sep',
346 -values => \@dels,
347 -size => 1,
348 -multiple => 0
351 my ( @budget_lines, %cell_hash );
354 foreach my $budget (@budgets) {
355 my $budget_lock;
357 # check budget permission
358 if ( $period->{budget_period_locked} == 1 ) {
359 $budget_lock = 1;
360 } elsif ( $budget->{budget_permission} == 1 ) {
361 $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
362 } elsif ( $budget->{budget_permission} == 2 ) {
363 $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
366 # allow hard-coded itemtype and branch planning
367 unless ( $authcat eq 'ITEMTYPES'
368 or $authcat eq 'BRANCHES'
369 or $authcat eq 'MONTHS' ) {
371 # but skip budgets that dont match the current auth-category
372 next if ( $budget->{'sort1_authcat'} ne $authcat
373 && $budget->{'sort2_authcat'} ne $authcat );
376 my %budget_line; # each row of the table
377 my @cells_line;
378 my $actual_spent;
379 my $estimated_spent;
381 my $i = 0;
382 foreach my $authvalue (@authvals) {
384 # get actual stats
385 my %cell = (
386 budget_id => $budget->{'budget_id'},
387 budget_period_id => $budget->{'budget_period_id'},
388 cell_name => $budget->{'budget_id'} . ',' . $authvalue,
389 authvalue => $authvalue,
390 authcat => $authcat,
391 cell_authvalue => $authvalue,
392 budget_lock => $budget_lock,
395 my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
396 $cell{actual_amount} = sprintf( "%.2f", $actual );
397 $cell{estimated_amount} = sprintf( "%.2f", $estimated );
398 $cell{display} = $authvals_row[$i]{display};
399 $cell{colnum} = $i;
401 $actual_spent += $cell{actual_amount};
402 $estimated_spent += $cell{estimated_amount};
405 push( @cells_line, \%cell );
406 $i++;
409 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
410 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
412 %budget_line = (
413 lines => \@cells_line,
414 budget_name_indent => $budget->{budget_name_indent},
415 budget_amount_formatted => $num->format_price( $budget->{budget_amount} ),
416 budget_amount => $budget->{budget_amount},
417 budget_alloc => $budget->{budget_alloc},
418 budget_act_remain => sprintf( "%.2f", $budget_act_remain ),
419 budget_est_remain => sprintf( "%.2f", $budget_est_remain ),
420 budget_id => $budget->{budget_id},
421 budget_lock => $budget_lock,
426 $budget_line{est_negative} = '1' if $budget_est_remain < 0;
427 $budget_line{est_positive} = '1' if $budget_est_remain > 0;
428 $budget_line{act_negative} = '1' if $budget_act_remain < 0;
429 $budget_line{act_positive} = '1' if $budget_act_remain > 0;
431 # skip if active set , and spent == 0
432 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
434 push( @budget_lines, \%budget_line );
437 if ( $output eq "file" ) {
438 _print_to_csv(\@authvals_row, \@budget_lines);
439 exit(1);
442 $template->param(
443 authvals_row => \@authvals_row,
444 budget_lines => \@budget_lines,
445 budget_period_description => $period->{'budget_period_description'},
446 budget_period_locked => $period->{'budget_period_locked'},
447 budget_period_id => $budget_period_id,
448 authcat => $authcat,
449 show_active => $show_active,
450 show_actual => $show_actual,
451 show_percent => $show_percent,
452 show_mine => $show_mine,
453 cur_format => $cur_format,
454 CGIextChoice => $CGIextChoice,
455 CGIsepChoice => $CGIsepChoice,
457 authvals => \@authvals_row,
458 hide_cols_loop => \@hide_cols
461 output_html_with_http_headers $input, $cookie, $template->output;
463 sub _print_to_csv {
464 my ( $header, $results ) = @_;
466 binmode STDOUT, ':encoding(UTF-8)';
468 my $csv = Text::CSV_XS->new(
469 { sep_char => $del,
470 always_quote => 'TRUE',
473 print $input->header(
474 -type => 'application/vnd.sun.xml.calc',
475 -encoding => 'utf-8',
476 -attachment => "$basename.csv",
477 -name => "$basename.csv"
479 my @col = ( 'Budget name', 'Budget total' );
480 foreach my $row (@$header) {
481 push @col, $row->{'val'};
483 push @col, 'Budget remaining';
485 $csv->combine(@col);
486 my $str = $csv->string;
487 print "$str\n";
489 foreach my $row (@$results) {
490 $row->{'budget_name_indent'} =~ s/&nbsp;/ /g;
491 my @col = ( $row->{'budget_name_indent'}, $row->{'budget_amount'} );
492 my $l = $row->{'lines'};
493 foreach my $line (@$l) {
494 push @col, $line->{'estimated_amount'};
496 push @col, $row->{'budget_est_remain'};
497 $csv->combine(@col);
498 my $str = $csv->string;
499 print "$str\n";