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