Merge remote branch 'kc/new/bug_5175' into kcmaster
[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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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;
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 Number::Format qw(format_price);
31 use Text::CSV_XS;
32
33 use C4::Acquisition;
34 use C4::Budgets;
35 use C4::Context;
36 use C4::Output;
37 use C4::Koha;
38 use C4::Auth;
39 use C4::Input;
40 use C4::Debug;
41
42 my $input = new CGI;
43 ####  $input
44
45 my $dbh = C4::Context->dbh;
46
47 my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user(
48     {   template_name   => "admin/aqplan.tmpl",
49         query           => $input,
50         type            => "intranet",
51         authnotrequired => 0,
52         flagsrequired   => { acquisition => 'planning_manage' },
53         debug           => 0,
54     }
55 );
56
57 my $budget_period_id = $input->param('budget_period_id');
58 # ' ------- get periods stuff ------------------'
59 # IF PERIOD_ID IS DEFINED,  GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT
60 my $period = GetBudgetPeriod($budget_period_id);
61 my $count  = GetPeriodsCount();
62 my $cur    = GetCurrency;
63 $template->param( symbol => $cur->{symbol},
64                   currency => $cur->{currency}
65                );
66 $template->param( period_button_only => 1 ) if $count == 0;
67
68
69
70 # authcats_loop populates the YUI planning button
71 my $auth_cats_loop            = GetBudgetAuthCats($budget_period_id);
72 my $budget_period_id          = $period->{'budget_period_id'};
73 my $budget_period_startdate   = $period->{'budget_period_startdate'};
74 my $budget_period_enddate     = $period->{'budget_period_enddate'};
75 my $budget_period_locked      = $period->{'budget_period_locked'};
76 my $budget_period_description = $period->{'budget_period_description'};
77 my $budget_period_dropbox     = GetBudgetPeriodsDropbox($budget_period_id );
78
79
80 $template->param(
81     budget_period_id          => $budget_period_id,
82     budget_period_locked      => $budget_period_locked,
83     budget_period_description => $budget_period_description,
84     budget_period_dropbox     => $budget_period_dropbox,
85     auth_cats_loop            => $auth_cats_loop,
86 );
87
88 # ------- get periods stuff ------------------
89
90 my $borrower_id         = $template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'};
91 my $borrower_branchcode = $template->{param_map}->{'USER_INFO'}[0]->{'branchcode'};
92
93 my $periods;
94 my $authcat      = $input->param('authcat');
95 my $show_active  = $input->param('show_active');
96 my $show_actual  = $input->param('show_actual');
97 my $show_percent = $input->param('show_percent');
98 my $output       = $input->param("output");
99 my $basename     = $input->param("basename");
100 my $del          = $input->param("sep");
101
102 my $show_mine       = $input->param('show_mine') ;
103
104 my @hide_cols      = $input->param('hide_cols');
105
106 my $cur_format = C4::Context->preference("CurrencyFormat");
107 my $num;
108
109 if ( $cur_format eq 'FR' ) {
110     $num = new Number::Format(
111         'decimal_fill'      => '2',
112         'decimal_point'     => ',',
113         'int_curr_symbol'   => '',
114         'mon_thousands_sep' => ' ',
115         'thousands_sep'     => ' ',
116         'mon_decimal_point' => ','
117     );
118 } else {  # US by default..
119     $num = new Number::Format(
120         'int_curr_symbol'   => '',
121         'mon_thousands_sep' => ',',
122         'mon_decimal_point' => '.'
123     );
124 }
125
126 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
127      $show_actual  = 1;
128 }
129
130 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
131
132 my $budget_id = $input->param('budget_id');
133 my $op        = $input->param("op");
134
135 my $budget_branchcode;
136
137 my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $show_mine?$template->{param_map}->{'USER_INFO'}[0]->{'branchcode'}:'', $show_mine?$template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'}:'' );
138
139 # build categories list
140 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
141 $sth->execute;
142
143 # the list
144 my @category_list;
145
146 # a hash, to check that some hardcoded categories exist.
147 my %categories;
148 while ( my ($category) = $sth->fetchrow_array ) {
149     push( @category_list, $category );
150     $categories{$category} = 1;
151 }
152
153 # push koha system categories
154 push( @category_list, 'MONTHS' );
155 push( @category_list, 'ITEMTYPES' );
156 push( @category_list, 'BRANCHES' );
157 push( @category_list, $$_{'authcat'} ) foreach @$auth_cats_loop;
158
159 #reorder the list
160 @category_list = sort { $a cmp $b } @category_list;
161 my $tab_list = CGI::scrolling_list(
162     -name     => 'authcat',
163     -id       => 'authcat',
164     -values   => \@category_list,
165     -default  => $authcat,
166     -size     => 1,
167     -tabindex => '',
168     -multiple => 0,
169 );
170
171 $template->param( authcat_dropbox => $tab_list );
172
173 my @budgets = @$budgets_ref;
174 my $CGISort;
175 my @authvals;
176 my %labels;
177
178 my @names = $input->param();
179 # ------------------------------------------------------------
180 if ( $op eq 'save' ) {
181     #get budgets
182     my ( @buds, @auth_values );
183     foreach my $n (@names) {
184         next if $n =~ m/^[^0-9]/;
185         my @moo = split( ',', $n );
186         push @buds, $moo[0];
187         push @auth_values, $moo[1];
188     }
189
190     #uniq buds and auth
191     my %seen;
192     @buds        = grep { !$seen{$_}++ } @buds;
193     @auth_values = grep { !$seen{$_}++ } @auth_values;
194     my @budget_ids;
195     my @budget_lines;
196
197     foreach my $budget (@buds) {
198         my %budget_line;
199         my @cells_line;
200         my %cell_hash;
201
202         foreach my $authvalue (@auth_values) {
203             # get actual stats
204             my $cell_name        = "$budget,$authvalue";
205             my $estimated_amount = $input->param("$cell_name");
206             my %cell_hash = (
207                 estimated_amount => $estimated_amount,
208                 authvalue        => $authvalue,
209                 authcat          => $authcat,
210                 budget_id        => $budget,
211                 budget_period_id => $budget_period_id,
212             );
213             push( @cells_line, \%cell_hash );
214         }
215
216         %budget_line = (
217             lines => \@cells_line,
218         );
219         push( @budget_lines, \%budget_line );
220     }
221     my $plan = \@budget_lines;
222     ModBudgetPlan( $plan, $budget_period_id, $authcat );
223
224 HideCols($authcat, @hide_cols);
225
226
227 }
228 # ------------------------------------------------------------
229 if ( $authcat =~ m/^Asort/ ) {
230     # ----------- copied from C4::Input::buildCGIsort()
231    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
232     my $sth   = $dbh->prepare($query);
233     $sth->execute($authcat  );
234     if ( $sth->rows > 0 ) {
235         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
236             my $results = $sth->fetchrow_hashref;
237             push @authvals, $results->{authorised_value};
238             $labels{ $results->{authorised_value} } = $results->{lib};
239         }
240     }
241     $sth->finish;
242     @authvals = sort { $a <=> $b } @authvals;
243 }
244 elsif ( $authcat eq 'MONTHS' ) {
245
246     # build months
247     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
248     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
249
250     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
251
252     #calc number of months between
253     my $months      = ( $Dy * 12 ) + $Dm;
254     my $start_month = @start_date[1];
255     my $end_month   = ( $Dy * 12 ) + $Dm;
256
257     for my $mth ( 0 ... $months ) {
258         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
259         $mth = UnixDate( $mth, "%Y-%m" );
260         push( @authvals, $mth );
261     }
262     foreach my $vv (@authvals) {
263         $labels{$vv} = $vv;
264     }
265 }
266
267 elsif ( $authcat eq 'ITEMTYPES' ) {
268     my $query = qq| SELECT itemtype, description FROM itemtypes |;
269     my $sth   = $dbh->prepare($query);
270     $sth->execute(  );
271
272     if ( $sth->rows > 0 ) {
273         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
274             my $results = $sth->fetchrow_hashref;
275             push @authvals, $results->{itemtype};
276             $labels{ $results->{itemtype} } = $results->{description};
277         }
278     }
279     $sth->finish;
280
281 } elsif ( $authcat eq 'BRANCHES' ) {
282
283     my $query = qq| SELECT branchcode, branchname FROM branches |;
284     my $sth   = $dbh->prepare($query);
285     $sth->execute();
286
287     if ( $sth->rows > 0 ) {
288         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
289             my $results = $sth->fetchrow_hashref;
290             push @authvals, $results->{branchcode};
291             $labels{ $results->{branchcode} } = $results->{branchname};
292         }
293     }
294     $sth->finish;
295 } elsif ($authcat) {
296     my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
297     my $sth   = $dbh->prepare($query);
298     $sth->execute($authcat);
299     if ( $sth->rows > 0 ) {
300         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
301             my $results = $sth->fetchrow_hashref;
302             push @authvals, $results->{authorised_value};
303             $labels{ $results->{authorised_value} } = $results->{lib};
304         }
305     }
306     $sth->finish;
307 }
308
309 my @authvals_row;
310 my $i=1;
311 foreach my $val (@authvals) {
312     my %auth_hash;
313     $auth_hash{val} =   $labels{$val};
314     $auth_hash{code} =   $val;
315     $auth_hash{colnum} =   $i++;
316
317     # display lookup
318     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
319
320     push( @authvals_row, \%auth_hash );
321 }
322
323 #get budgets
324 my ( @buds, @auth_values );
325 foreach my $n (@names) {
326     next if $n =~ m/^[^0-9]/;
327     $n =~ m/(\d*),(.*)/;
328     push @buds, $1;
329     push @auth_values, $2;
330 }
331
332
333 # ------------------------------------------------------------
334 #         DEFAULT DISPLAY BEGINS
335
336 my $CGIextChoice = CGI::scrolling_list(
337     -name     => 'MIME',
338     -id       => 'MIME',
339     -values   => ['CSV'], # FIXME translation
340     -size     => 1,
341     -multiple => 0
342 );
343
344 my @dels         = ( C4::Context->preference("delimiter") );
345 my $CGIsepChoice = CGI::scrolling_list(
346     -name     => 'sep',
347     -id       => 'sep',
348     -values   => \@dels,
349     -size     => 1,
350     -multiple => 0
351 );
352
353 my ( @budget_lines, %cell_hash );
354
355
356 foreach my $budget (@budgets) {
357     my $budget_lock;
358
359     # check budget permission
360     if ( $period->{budget_period_locked} == 1 ) {
361         $budget_lock = 1;
362     } elsif ( $budget->{budget_permission} == 1 ) {
363         $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
364     } elsif ( $budget->{budget_permission} == 2 ) {
365         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
366     }
367
368     # allow hard-coded itemtype and branch planning
369     unless ( $authcat eq 'ITEMTYPES'
370         or  $authcat eq 'BRANCHES'
371         or  $authcat eq 'MONTHS' ) {
372
373         # but skip budgets that dont match the current auth-category
374         next if ( $budget->{'sort1_authcat'} ne $authcat
375             && $budget->{'sort2_authcat'} ne $authcat );
376     }
377
378     my %budget_line; # each row of the  table
379     my @cells_line;
380     my $actual_spent;
381     my $estimated_spent;
382
383     my $i = 0;
384     foreach my $authvalue (@authvals) {
385
386         # get actual stats
387         my %cell = (
388             budget_id        => $budget->{'budget_id'},
389             budget_period_id => $budget->{'budget_period_id'},
390             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
391             authvalue        => $authvalue,
392             authcat          => $authcat,
393             cell_authvalue   => $authvalue,
394             budget_lock      => $budget_lock,
395         );
396
397         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
398         $cell{actual_amount}    = sprintf( "%.2f", $actual );
399         $cell{estimated_amount} = sprintf( "%.2f", $estimated );
400         $cell{display}          = $authvals_row[$i]{display};
401         $cell{colnum}           = $i;
402
403         $actual_spent    += $cell{actual_amount};
404         $estimated_spent += $cell{estimated_amount};
405
406
407         push( @cells_line, \%cell );
408         $i++;
409     }
410
411     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
412     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
413
414     %budget_line = (
415         lines                   => \@cells_line,
416         budget_name_indent      => $budget->{budget_name_indent},
417         budget_amount_formatted => $num->format_price( $budget->{budget_amount} ),
418         budget_amount           => $budget->{budget_amount},
419         budget_alloc            => $budget->{budget_alloc},
420         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
421         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
422         budget_id               => $budget->{budget_id},
423         budget_lock             => $budget_lock,
424     );
425
426
427
428     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
429     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
430     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
431     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
432
433     # skip if active set , and spent == 0
434     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
435
436     push( @budget_lines, \%budget_line );
437 }
438
439 if ( $output eq "file" ) {
440     _print_to_csv(\@authvals_row, \@budget_lines);
441     exit(1);
442 }
443
444 $template->param(
445     authvals_row              => \@authvals_row,
446     budget_lines              => \@budget_lines,
447     budget_period_description => $period->{'budget_period_description'},
448     budget_period_locked      => $period->{'budget_period_locked'},
449     budget_period_id          => $budget_period_id,
450     authcat                   => $authcat,
451     show_active               => $show_active,
452     show_actual               => $show_actual,
453     show_percent              => $show_percent,
454     show_mine                 => $show_mine,
455     cur_format                => $cur_format,
456     CGIextChoice              => $CGIextChoice,
457     CGIsepChoice              => $CGIsepChoice,
458
459     authvals              => \@authvals_row,
460     hide_cols_loop              => \@hide_cols
461 );
462
463 output_html_with_http_headers $input, $cookie, $template->output;
464
465 sub _print_to_csv {
466     my ( $header, $results ) = @_;
467
468     binmode STDOUT, ":utf8";
469
470     my $csv = Text::CSV_XS->new(
471         {   sep_char     => $del,
472             always_quote => 'TRUE',
473         }
474     );
475     print $input->header(
476         -type       => 'application/vnd.sun.xml.calc',
477         -encoding   => 'utf-8',
478         -attachment => "$basename.csv",
479         -name       => "$basename.csv"
480     );
481     my @col = ( 'Budget name', 'Budget total' );
482     foreach my $row (@$header) {
483         push @col, $row->{'val'};
484     }
485     push @col, 'Budget remaining';
486
487     $csv->combine(@col);
488     my $str = $csv->string;
489     print "$str\n";
490
491     foreach my $row (@$results) {
492         $row->{'budget_name_indent'} =~ s/&nbsp;/ /g;
493         my @col = ( $row->{'budget_name_indent'}, $row->{'budget_amount'} );
494         my $l = $row->{'lines'};
495         foreach my $line (@$l) {
496             push @col, $line->{'estimated_amount'};
497         }
498         push @col, $row->{'budget_est_remain'};
499         $csv->combine(@col);
500         my $str = $csv->string;
501         print "$str\n";
502     }
503 }