Bug 9302: Use patron-title.inc
[koha.git] / admin / aqplan.pl
blobf01e5e8b131546a1dadf1d7df0788026372cf764
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 = 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 $active_currency = Koha::Acquisition::Currencies->get_active;
60 if ( $active_currency ) {
61 $template->param( symbol => $active_currency->symbol,
62 currency => $active_currency->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 $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'}->{'borrowernumber'};
88 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}->{'branchcode'};
90 my $authcat = $input->param('authcat');
91 my $show_active = $input->param('show_active') // 0;
92 my $show_actual = $input->param('show_actual');
93 my $show_percent = $input->param('show_percent');
94 my $output = $input->param("output") // q{};
95 our $basename = $input->param("basename");
96 our $del = $input->param("sep");
98 my $show_mine = $input->param('show_mine') ;
100 my @hide_cols = $input->multi_param('hide_cols');
102 if ( $budget_period_locked == 1 && not defined $show_actual ) {
103 $show_actual = 1;
106 $authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given
108 my $budget_id = $input->param('budget_id');
109 my $op = $input->param("op") // q{};
111 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}->{'borrowernumber'}:'' );
113 # build categories list
114 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
115 $sth->execute;
117 # the list
118 my @category_list;
120 # a hash, to check that some hardcoded categories exist.
121 my %categories;
122 while ( my ($category) = $sth->fetchrow_array ) {
123 push( @category_list, $category );
124 $categories{$category} = 1;
127 # push koha system categories
128 push( @category_list, 'MONTHS' );
129 push( @category_list, 'ITEMTYPES' );
130 push( @category_list, 'BRANCHES' );
131 push( @category_list, $_ ) foreach @$auth_cats_loop;
133 #reorder the list
134 @category_list = sort { $a cmp $b } @category_list;
136 $template->param( authcat_dropbox => {
137 values => \@category_list,
138 default => $authcat,
141 my @budgets = @$budgets_ref;
142 my @authvals;
143 my %labels;
145 my @names = $input->multi_param();
146 # ------------------------------------------------------------
147 if ( $op eq 'save' ) {
148 #get budgets
149 my ( @buds, @auth_values );
150 foreach my $n (@names) {
151 next if $n =~ m/^[^0-9]/;
152 my @moo = split( ',', $n );
153 push @buds, $moo[0];
154 push @auth_values, $moo[1];
157 #uniq buds and auth
158 my %seen;
159 @buds = grep { !$seen{$_}++ } @buds;
160 @auth_values = grep { !$seen{$_}++ } @auth_values;
161 my @budget_lines;
163 foreach my $budget (@buds) {
164 my %budget_line;
165 my @cells_line;
166 my %cell_hash;
168 foreach my $authvalue (@auth_values) {
169 # get actual stats
170 my $cell_name = "$budget,$authvalue";
171 my $estimated_amount = $input->param("$cell_name");
172 my %cell_hash = (
173 estimated_amount => $estimated_amount,
174 authvalue => $authvalue,
175 authcat => $authcat,
176 budget_id => $budget,
177 budget_period_id => $budget_period_id,
179 push( @cells_line, \%cell_hash );
182 %budget_line = (
183 lines => \@cells_line,
185 push( @budget_lines, \%budget_line );
187 my $plan = \@budget_lines;
188 ModBudgetPlan( $plan, $budget_period_id, $authcat );
190 HideCols($authcat, @hide_cols);
194 # ------------------------------------------------------------
195 if ( $authcat =~ m/^Asort/ ) {
196 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
197 my $sth = $dbh->prepare($query);
198 $sth->execute($authcat );
199 if ( $sth->rows > 0 ) {
200 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
201 my $results = $sth->fetchrow_hashref;
202 push @authvals, $results->{authorised_value};
203 $labels{ $results->{authorised_value} } = $results->{lib};
206 $sth->finish;
207 @authvals = sort { $a <=> $b } @authvals;
209 elsif ( $authcat eq 'MONTHS' && $budget_period_startdate && $budget_period_enddate ) {
211 # build months
212 my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
213 my @end_date = UnixDate( $budget_period_enddate, ( '%Y', '%m', '%d' ) );
215 my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
217 #calc number of months between
218 my $months = ( $Dy * 12 ) + $Dm;
219 my $start_month = $start_date[1];
220 my $end_month = ( $Dy * 12 ) + $Dm;
222 for my $mth ( 0 ... $months ) {
223 $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
224 $mth = UnixDate( $mth, "%Y-%m" );
225 push( @authvals, $mth );
227 foreach my $vv (@authvals) {
228 $labels{$vv} = $vv;
232 elsif ( $authcat eq 'ITEMTYPES' ) {
233 my $query = qq| SELECT itemtype, description FROM itemtypes |;
234 my $sth = $dbh->prepare($query);
235 $sth->execute( );
237 if ( $sth->rows > 0 ) {
238 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
239 my $results = $sth->fetchrow_hashref;
240 push @authvals, $results->{itemtype};
241 $labels{ $results->{itemtype} } = $results->{description};
244 $sth->finish;
246 } elsif ( $authcat eq 'BRANCHES' ) {
248 my $query = qq| SELECT branchcode, branchname FROM branches |;
249 my $sth = $dbh->prepare($query);
250 $sth->execute();
252 if ( $sth->rows > 0 ) {
253 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
254 my $results = $sth->fetchrow_hashref;
255 push @authvals, $results->{branchcode};
256 $labels{ $results->{branchcode} } = $results->{branchname};
259 $sth->finish;
260 } elsif ($authcat) {
261 my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
262 my $sth = $dbh->prepare($query);
263 $sth->execute($authcat);
264 if ( $sth->rows > 0 ) {
265 for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
266 my $results = $sth->fetchrow_hashref;
267 push @authvals, $results->{authorised_value};
268 $labels{ $results->{authorised_value} } = $results->{lib};
271 $sth->finish;
274 my @authvals_row;
275 my $i=1;
276 foreach my $val (@authvals) {
277 my %auth_hash;
278 $auth_hash{val} = $labels{$val};
279 $auth_hash{code} = $val;
280 $auth_hash{colnum} = $i++;
282 # display lookup
283 $auth_hash{display} = GetCols( $authcat, $auth_hash{code});
285 push( @authvals_row, \%auth_hash );
288 #get budgets
289 my ( @buds, @auth_values );
290 foreach my $n (@names) {
291 next if $n =~ m/^[^0-9]/;
292 $n =~ m/(\d*),(.*)/;
293 push @buds, $1;
294 push @auth_values, $2;
298 # ------------------------------------------------------------
299 # DEFAULT DISPLAY BEGINS
301 my $CGIextChoice = ( 'CSV' ); # FIXME translation
302 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
304 my ( @budget_lines, %cell_hash );
307 foreach my $budget (@budgets) {
308 my $budget_lock;
310 unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
311 $budget_lock = 1
314 # check budget permission
315 if ( $period->{budget_period_locked} == 1 ) {
316 $budget_lock = 1;
317 } elsif ( $budget->{budget_permission} == 1 ) {
318 $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
319 } elsif ( $budget->{budget_permission} == 2 ) {
320 $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
323 # allow hard-coded itemtype and branch planning
324 unless ( $authcat eq 'ITEMTYPES'
325 or $authcat eq 'BRANCHES'
326 or $authcat eq 'MONTHS' ) {
328 # but skip budgets that don't match the current auth-category
329 next if ( $budget->{'sort1_authcat'} ne $authcat
330 && $budget->{'sort2_authcat'} ne $authcat );
333 my %budget_line; # each row of the table
334 my @cells_line;
335 my $actual_spent;
336 my $estimated_spent;
338 my $i = 0;
339 foreach my $authvalue (@authvals) {
341 # get actual stats
342 my %cell = (
343 budget_id => $budget->{'budget_id'},
344 budget_period_id => $budget->{'budget_period_id'},
345 cell_name => $budget->{'budget_id'} . ',' . $authvalue,
346 authvalue => $authvalue,
347 authcat => $authcat,
348 cell_authvalue => $authvalue,
349 budget_lock => $budget_lock,
352 my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
353 $cell{actual_amount} = sprintf( "%.2f", $actual // 0 );
354 $cell{estimated_amount} = sprintf( "%.2f", $estimated // 0 );
355 $cell{display} = $authvals_row[$i]{display};
356 $cell{colnum} = $i;
358 $actual_spent += $cell{actual_amount};
359 $estimated_spent += $cell{estimated_amount};
362 push( @cells_line, \%cell );
363 $i++;
366 my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
367 my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
369 %budget_line = (
370 lines => \@cells_line,
371 budget_name => $budget->{budget_name},
372 budget_amount => $budget->{budget_amount},
373 budget_alloc => $budget->{budget_alloc},
374 budget_act_remain => sprintf( "%.2f", $budget_act_remain ),
375 budget_est_remain => sprintf( "%.2f", $budget_est_remain ),
376 budget_id => $budget->{budget_id},
377 budget_lock => $budget_lock,
382 $budget_line{est_negative} = '1' if $budget_est_remain < 0;
383 $budget_line{est_positive} = '1' if $budget_est_remain > 0;
384 $budget_line{act_negative} = '1' if $budget_act_remain < 0;
385 $budget_line{act_positive} = '1' if $budget_act_remain > 0;
387 # skip if active set , and spent == 0
388 next if ( $show_active == '1' && ( $actual_spent == 0 ) );
390 push( @budget_lines, \%budget_line );
393 if ( $output eq "file" ) {
394 _print_to_csv(\@authvals_row, \@budget_lines);
395 exit(1);
398 $template->param(
399 authvals_row => \@authvals_row,
400 budget_lines => \@budget_lines,
401 budget_period_description => $period->{'budget_period_description'},
402 budget_period_locked => $period->{'budget_period_locked'},
403 budget_period_id => $budget_period_id,
404 authcat => $authcat,
405 show_active => $show_active,
406 show_actual => $show_actual,
407 show_percent => $show_percent,
408 show_mine => $show_mine,
409 CGIextChoice => $CGIextChoice,
410 CGIsepChoice => $CGIsepChoice,
412 authvals => \@authvals_row,
413 hide_cols_loop => \@hide_cols,
416 output_html_with_http_headers $input, $cookie, $template->output;
418 sub _print_to_csv {
419 my ( $header, $results ) = @_;
421 binmode STDOUT, ':encoding(UTF-8)';
423 my $csv = Text::CSV_XS->new(
424 { sep_char => $del,
425 always_quote => 'TRUE',
428 print $input->header(
429 -type => 'application/vnd.sun.xml.calc',
430 -encoding => 'utf-8',
431 -attachment => "$basename.csv",
432 -name => "$basename.csv"
434 my @col = ( 'Budget name', 'Budget total' );
435 foreach my $row (@$header) {
436 push @col, $row->{'val'};
438 push @col, 'Budget remaining';
440 $csv->combine(@col);
441 my $str = $csv->string;
442 print "$str\n";
444 foreach my $row (@$results) {
445 my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
446 my $l = $row->{'lines'};
447 foreach my $line (@$l) {
448 push @col, $line->{'estimated_amount'};
450 push @col, $row->{'budget_est_remain'};
451 $csv->combine(@col);
452 my $str = $csv->string;
453 print "$str\n";