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