Bug 25596: DBRev 20.06.00.054
[koha.git] / admin / aqplan.pl
blob95ddb3652004edf42d6a4bffc53df19ab5c47bd9
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 Modern::Perl;
24 use CGI qw ( -utf8 );
25 use List::Util qw/min/;
26 use Date::Calc qw/Delta_YMD Easter_Sunday Today Decode_Date_EU/;
27 use Date::Manip qw/ ParseDate UnixDate DateCalc/;
28 use Text::CSV_XS;
30 use C4::Acquisition;
31 use C4::Budgets;
32 use C4::Context;
33 use C4::Output;
34 use C4::Koha;
35 use C4::Auth;
36 use C4::Debug;
37 use Koha::Acquisition::Currencies;
39 our $input = CGI->new;
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 flagsrequired => { acquisition => 'planning_manage' },
49 debug => 0,
53 my $budget_period_id = $input->param('budget_period_id');
54 # ' ------- get periods stuff ------------------'
55 # IF PERIOD_ID IS DEFINED, GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
56 my $period = GetBudgetPeriod($budget_period_id);
57 my $count = GetPeriodsCount();
58 my $active_currency = Koha::Acquisition::Currencies->get_active;
59 if ( $active_currency ) {
60 $template->param( symbol => $active_currency->symbol,
61 currency => $active_currency->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 $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 ------------------
87 my $borrower_branchcode = my $branch_code = C4::Context->userenv->{'branch'};
89 my $authcat = $input->param('authcat');
90 my $show_active = $input->param('show_active') // 0;
91 my $show_actual = $input->param('show_actual');
92 my $show_percent = $input->param('show_percent');
93 my $output = $input->param("output") // q{};
94 our $basename = $input->param("basename");
95 our $del = $input->param("sep");
97 my $show_mine = $input->param('show_mine') ;
99 my @hide_cols = $input->multi_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") // q{};
110 my $budgets_ref = GetBudgetHierarchy(
111 $budget_period_id,
112 $show_mine ? $borrower_branchcode : '',
113 $show_mine ? $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, $_ ) 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 @authvals;
146 my %labels;
148 my @names = $input->multi_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_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' && $budget_period_startdate && $budget_period_enddate ) {
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 $borrowernumber != $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 // 0 );
357 $cell{estimated_amount} = sprintf( "%.2f", $estimated // 0 );
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 $template->param(
402 authvals_row => \@authvals_row,
403 budget_lines => \@budget_lines,
404 budget_period_description => $period->{'budget_period_description'},
405 budget_period_locked => $period->{'budget_period_locked'},
406 budget_period_id => $budget_period_id,
407 authcat => $authcat,
408 show_active => $show_active,
409 show_actual => $show_actual,
410 show_percent => $show_percent,
411 show_mine => $show_mine,
412 CGIextChoice => $CGIextChoice,
413 CGIsepChoice => $CGIsepChoice,
415 authvals => \@authvals_row,
416 hide_cols_loop => \@hide_cols,
419 output_html_with_http_headers $input, $cookie, $template->output;
421 sub _print_to_csv {
422 my ( $header, $results ) = @_;
424 binmode STDOUT, ':encoding(UTF-8)';
426 my $csv = Text::CSV_XS->new(
427 { sep_char => $del,
428 always_quote => 'TRUE',
431 print $input->header(
432 -type => 'application/vnd.sun.xml.calc',
433 -encoding => 'utf-8',
434 -attachment => "$basename.csv",
435 -name => "$basename.csv"
437 my @col = ( 'Budget name', 'Budget total' );
438 foreach my $row (@$header) {
439 push @col, $row->{'val'};
441 push @col, 'Budget remaining';
443 $csv->combine(@col);
444 my $str = $csv->string;
445 print "$str\n";
447 foreach my $row (@$results) {
448 my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
449 my $l = $row->{'lines'};
450 foreach my $line (@$l) {
451 push @col, $line->{'estimated_amount'};
453 push @col, $row->{'budget_est_remain'};
454 $csv->combine(@col);
455 my $str = $csv->string;
456 print "$str\n";