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