Bug 4502: Catch software error if no active budget defined
[koha.git] / admin / aqplan.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008-2009 BibLibre SARL
4 # This file is part of Koha.
5 #
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.
10 #
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.
15 #
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>.
18
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)
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use CGI qw ( -utf8 );
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;
31
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;
40
41 my $input = new CGI;
42 ####  $input
43
44 my $dbh = C4::Context->dbh;
45
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,
53     }
54 );
55
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}
64                );
65 $template->param( period_button_only => 1 ) if $count == 0;
66
67
68
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'};
76
77
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,
83 );
84
85 # ------- get periods stuff ------------------
86
87 my $borrower_id         = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
88 my $borrower_branchcode = $template->{VARS}->{'USER_INFO'}[0]->{'branchcode'};
89
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");
98
99 my $show_mine       = $input->param('show_mine') ;
100
101 my @hide_cols      = $input->param('hide_cols');
102
103 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
104      $show_actual  = 1;
105 }
106
107 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
108
109 # If no active budget is defined, budget_period_id is undef
110 # This is the behavior of GetBudgetPeriod
111 $authcat = '' unless $budget_period_id;
112
113 my $budget_id = $input->param('budget_id');
114 my $op        = $input->param("op");
115
116 my $budget_branchcode;
117
118 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
119
120 # build categories list
121 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
122 $sth->execute;
123
124 # the list
125 my @category_list;
126
127 # a hash, to check that some hardcoded categories exist.
128 my %categories;
129 while ( my ($category) = $sth->fetchrow_array ) {
130     push( @category_list, $category );
131     $categories{$category} = 1;
132 }
133
134 # push koha system categories
135 push( @category_list, 'MONTHS' );
136 push( @category_list, 'ITEMTYPES' );
137 push( @category_list, 'BRANCHES' );
138 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
139
140 #reorder the list
141 @category_list = sort { $a cmp $b } @category_list;
142
143 $template->param( authcat_dropbox => {
144         values => \@category_list,
145         default => $authcat,
146     });
147
148 my @budgets = @$budgets_ref;
149 my $CGISort;
150 my @authvals;
151 my %labels;
152
153 my @names = $input->param();
154 # ------------------------------------------------------------
155 if ( $op eq 'save' ) {
156     #get budgets
157     my ( @buds, @auth_values );
158     foreach my $n (@names) {
159         next if $n =~ m/^[^0-9]/;
160         my @moo = split( ',', $n );
161         push @buds, $moo[0];
162         push @auth_values, $moo[1];
163     }
164
165     #uniq buds and auth
166     my %seen;
167     @buds        = grep { !$seen{$_}++ } @buds;
168     @auth_values = grep { !$seen{$_}++ } @auth_values;
169     my @budget_ids;
170     my @budget_lines;
171
172     foreach my $budget (@buds) {
173         my %budget_line;
174         my @cells_line;
175         my %cell_hash;
176
177         foreach my $authvalue (@auth_values) {
178             # get actual stats
179             my $cell_name        = "$budget,$authvalue";
180             my $estimated_amount = $input->param("$cell_name");
181             my %cell_hash = (
182                 estimated_amount => $estimated_amount,
183                 authvalue        => $authvalue,
184                 authcat          => $authcat,
185                 budget_id        => $budget,
186                 budget_period_id => $budget_period_id,
187             );
188             push( @cells_line, \%cell_hash );
189         }
190
191         %budget_line = (
192             lines => \@cells_line,
193         );
194         push( @budget_lines, \%budget_line );
195     }
196     my $plan = \@budget_lines;
197     ModBudgetPlan( $plan, $budget_period_id, $authcat );
198
199 HideCols($authcat, @hide_cols);
200
201
202 }
203 # ------------------------------------------------------------
204 if ( $authcat =~ m/^Asort/ ) {
205    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
206     my $sth   = $dbh->prepare($query);
207     $sth->execute($authcat  );
208     if ( $sth->rows > 0 ) {
209         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
210             my $results = $sth->fetchrow_hashref;
211             push @authvals, $results->{authorised_value};
212             $labels{ $results->{authorised_value} } = $results->{lib};
213         }
214     }
215     $sth->finish;
216     @authvals = sort { $a <=> $b } @authvals;
217 }
218 elsif ( $authcat eq 'MONTHS' ) {
219
220     # build months
221     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
222     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
223
224     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
225
226     #calc number of months between
227     my $months      = ( $Dy * 12 ) + $Dm;
228     my $start_month = @start_date[1];
229     my $end_month   = ( $Dy * 12 ) + $Dm;
230
231     for my $mth ( 0 ... $months ) {
232         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
233         $mth = UnixDate( $mth, "%Y-%m" );
234         push( @authvals, $mth );
235     }
236     foreach my $vv (@authvals) {
237         $labels{$vv} = $vv;
238     }
239 }
240
241 elsif ( $authcat eq 'ITEMTYPES' ) {
242     my $query = qq| SELECT itemtype, description FROM itemtypes |;
243     my $sth   = $dbh->prepare($query);
244     $sth->execute(  );
245
246     if ( $sth->rows > 0 ) {
247         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
248             my $results = $sth->fetchrow_hashref;
249             push @authvals, $results->{itemtype};
250             $labels{ $results->{itemtype} } = $results->{description};
251         }
252     }
253     $sth->finish;
254
255 } elsif ( $authcat eq 'BRANCHES' ) {
256
257     my $query = qq| SELECT branchcode, branchname FROM branches |;
258     my $sth   = $dbh->prepare($query);
259     $sth->execute();
260
261     if ( $sth->rows > 0 ) {
262         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
263             my $results = $sth->fetchrow_hashref;
264             push @authvals, $results->{branchcode};
265             $labels{ $results->{branchcode} } = $results->{branchname};
266         }
267     }
268     $sth->finish;
269 } elsif ($authcat) {
270     my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
271     my $sth   = $dbh->prepare($query);
272     $sth->execute($authcat);
273     if ( $sth->rows > 0 ) {
274         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
275             my $results = $sth->fetchrow_hashref;
276             push @authvals, $results->{authorised_value};
277             $labels{ $results->{authorised_value} } = $results->{lib};
278         }
279     }
280     $sth->finish;
281 }
282
283 my @authvals_row;
284 my $i=1;
285 foreach my $val (@authvals) {
286     my %auth_hash;
287     $auth_hash{val} =   $labels{$val};
288     $auth_hash{code} =   $val;
289     $auth_hash{colnum} =   $i++;
290
291     # display lookup
292     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
293
294     push( @authvals_row, \%auth_hash );
295 }
296
297 #get budgets
298 my ( @buds, @auth_values );
299 foreach my $n (@names) {
300     next if $n =~ m/^[^0-9]/;
301     $n =~ m/(\d*),(.*)/;
302     push @buds, $1;
303     push @auth_values, $2;
304 }
305
306
307 # ------------------------------------------------------------
308 #         DEFAULT DISPLAY BEGINS
309
310 my $CGIextChoice = ( 'CSV' ); # FIXME translation
311 my $CGIsepChoice = ( C4::Context->preference("delimiter") );
312
313 my ( @budget_lines, %cell_hash );
314
315
316 foreach my $budget (@budgets) {
317     my $budget_lock;
318
319     unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) {
320         $budget_lock = 1
321     }
322
323     # check budget permission
324     if ( $period->{budget_period_locked} == 1 ) {
325         $budget_lock = 1;
326     } elsif ( $budget->{budget_permission} == 1 ) {
327         $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
328     } elsif ( $budget->{budget_permission} == 2 ) {
329         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
330     }
331
332     # allow hard-coded itemtype and branch planning
333     unless ( $authcat eq 'ITEMTYPES'
334         or  $authcat eq 'BRANCHES'
335         or  $authcat eq 'MONTHS' ) {
336
337         # but skip budgets that dont match the current auth-category
338         next if ( $budget->{'sort1_authcat'} ne $authcat
339             && $budget->{'sort2_authcat'} ne $authcat );
340     }
341
342     my %budget_line; # each row of the  table
343     my @cells_line;
344     my $actual_spent;
345     my $estimated_spent;
346
347     my $i = 0;
348     foreach my $authvalue (@authvals) {
349
350         # get actual stats
351         my %cell = (
352             budget_id        => $budget->{'budget_id'},
353             budget_period_id => $budget->{'budget_period_id'},
354             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
355             authvalue        => $authvalue,
356             authcat          => $authcat,
357             cell_authvalue   => $authvalue,
358             budget_lock      => $budget_lock,
359         );
360
361         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
362         $cell{actual_amount}    = sprintf( "%.2f", $actual );
363         $cell{estimated_amount} = sprintf( "%.2f", $estimated );
364         $cell{display}          = $authvals_row[$i]{display};
365         $cell{colnum}           = $i;
366
367         $actual_spent    += $cell{actual_amount};
368         $estimated_spent += $cell{estimated_amount};
369
370
371         push( @cells_line, \%cell );
372         $i++;
373     }
374
375     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
376     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
377
378     %budget_line = (
379         lines                   => \@cells_line,
380         budget_name             => $budget->{budget_name},
381         budget_amount           => $budget->{budget_amount},
382         budget_alloc            => $budget->{budget_alloc},
383         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
384         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
385         budget_id               => $budget->{budget_id},
386         budget_lock             => $budget_lock,
387     );
388
389
390
391     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
392     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
393     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
394     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
395
396     # skip if active set , and spent == 0
397     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
398
399     push( @budget_lines, \%budget_line );
400 }
401
402 if ( $output eq "file" ) {
403     _print_to_csv(\@authvals_row, \@budget_lines);
404     exit(1);
405 }
406
407 my $branchloop = C4::Branch::GetBranchesLoop();
408 $template->param(
409     authvals_row              => \@authvals_row,
410     budget_lines              => \@budget_lines,
411     budget_period_description => $period->{'budget_period_description'},
412     budget_period_locked      => $period->{'budget_period_locked'},
413     budget_period_id          => $budget_period_id,
414     authcat                   => $authcat,
415     show_active               => $show_active,
416     show_actual               => $show_actual,
417     show_percent              => $show_percent,
418     show_mine                 => $show_mine,
419     CGIextChoice              => $CGIextChoice,
420     CGIsepChoice              => $CGIsepChoice,
421
422     authvals              => \@authvals_row,
423     hide_cols_loop              => \@hide_cols,
424     branchloop                => $branchloop,
425 );
426
427 output_html_with_http_headers $input, $cookie, $template->output;
428
429 sub _print_to_csv {
430     my ( $header, $results ) = @_;
431
432     binmode STDOUT, ':encoding(UTF-8)';
433
434     my $csv = Text::CSV_XS->new(
435         {   sep_char     => $del,
436             always_quote => 'TRUE',
437         }
438     );
439     print $input->header(
440         -type       => 'application/vnd.sun.xml.calc',
441         -encoding   => 'utf-8',
442         -attachment => "$basename.csv",
443         -name       => "$basename.csv"
444     );
445     my @col = ( 'Budget name', 'Budget total' );
446     foreach my $row (@$header) {
447         push @col, $row->{'val'};
448     }
449     push @col, 'Budget remaining';
450
451     $csv->combine(@col);
452     my $str = $csv->string;
453     print "$str\n";
454
455     foreach my $row (@$results) {
456         my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
457         my $l = $row->{'lines'};
458         foreach my $line (@$l) {
459             push @col, $line->{'estimated_amount'};
460         }
461         push @col, $row->{'budget_est_remain'};
462         $csv->combine(@col);
463         my $str = $csv->string;
464         print "$str\n";
465     }
466 }