Merge commit 'koha-biblibre/master' into bl-acq
[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 with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 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 CGI;
25 use List::Util qw/min/;
26 use Date::Calc qw/Delta_YMD Easter_Sunday Today Decode_Date_EU/;
27 use Date::Manip qw/ ParseDate UnixDate DateCalc/;
28 use C4::Dates qw/format_date format_date_in_iso/;
29 use Number::Format qw(format_price);
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.tmpl",
48         query           => $input,
49         type            => "intranet",
50         authnotrequired => 1,
51         flagsrequired   => { acquisition => 'planning_manage' },
52         debug           => 1,
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
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 my $budget_period_dropbox     = GetBudgetPeriodsDropbox($budget_period_id );
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     budget_period_dropbox     => $budget_period_dropbox,
82     auth_cats_loop            => $auth_cats_loop,
83 );
84
85 # ------- get periods stuff ------------------
86
87 my $borrower_id         = $template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'};
88 my $borrower_branchcode = $template->{param_map}->{'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 $mime         = $input->param("MIME");
98 my $del          = $input->param("sep");
99
100 my $show_mine       = $input->param('show_mine') ;
101
102 my @hide_cols      = $input->param('hide_cols');
103
104 my $cur_format = C4::Context->preference("CurrencyFormat");
105 my $num;
106
107 if ( $cur_format eq 'FR' ) {
108     $num = new Number::Format(
109         'decimal_fill'      => '2',
110         'decimal_point'     => ',',
111         'int_curr_symbol'   => '',
112         'mon_thousands_sep' => ' ',
113         'thousands_sep'     => ' ',
114         'mon_decimal_point' => ','
115     );
116 } else {  # US by default..
117     $num = new Number::Format(
118         'int_curr_symbol'   => '',
119         'mon_thousands_sep' => ',',
120         'mon_decimal_point' => '.'
121     );
122 }
123
124 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
125      $show_actual  = 1;
126 }
127
128 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
129
130 my $budget_id = $input->param('budget_id');
131 my $op        = $input->param("op");
132
133 my $budget_branchcode;
134
135 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'}:'' );
136
137 # build categories list
138 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
139 $sth->execute;
140
141 # the list
142 my @category_list;
143
144 # a hash, to check that some hardcoded categories exist.
145 my %categories;
146 while ( my ($category) = $sth->fetchrow_array ) {
147     push( @category_list, $category );
148     $categories{$category} = 1;
149 }
150
151 # push koha system categories
152 push( @category_list, 'MONTHS' );
153 push( @category_list, 'ITEMTYPES' );
154 push( @category_list, 'BRANCHES' );
155
156 #reorder the list
157 @category_list = sort { $a cmp $b } @category_list;
158 my $tab_list = CGI::scrolling_list(
159     -name     => 'authcat',
160     -id       => 'authcat',
161     -values   => \@category_list,
162     -default  => $authcat,
163     -size     => 1,
164     -tabindex => '',
165     -multiple => 0,
166 );
167
168 $template->param( authcat_dropbox => $tab_list );
169
170 my @budgets = @$budgets_ref;
171 my $CGISort;
172 my @authvals;
173 my %labels;
174
175
176     my @names = $input->param();
177
178 # ------------------------------------------------------------
179 if ( $op eq 'save' ) {
180     #get budgets
181     my ( @buds, @auth_values );
182     foreach my $n (@names) {
183         next if $n =~ m/^[^0-9]/;
184         my @moo = split( ',', $n );
185         push @buds, $moo[0];
186         push @auth_values, $moo[1];
187     }
188
189     #uniq buds and auth
190     my %seen;
191     @buds        = grep { !$seen{$_}++ } @buds;
192     @auth_values = grep { !$seen{$_}++ } @auth_values;
193     my @budget_ids;
194     my @budget_lines;
195
196     foreach my $budget (@buds) {
197         my %budget_line;
198         my @cells_line;
199         my %cell_hash;
200
201         foreach my $authvalue (@auth_values) {
202             # get actual stats
203             my $cell_name        = "$budget,$authvalue";
204             my $estimated_amount = $input->param("$cell_name");
205             my %cell_hash = (
206                 estimated_amount => $estimated_amount,
207                 authvalue        => $authvalue,
208                 authcat          => $authcat,
209                 budget_id        => $budget,
210                 budget_period_id => $budget_period_id,
211             );
212             push( @cells_line, \%cell_hash );
213         }
214
215         %budget_line = (
216             lines => \@cells_line,
217         );
218         push( @budget_lines, \%budget_line );
219     }
220     my $plan = \@budget_lines;
221     ModBudgetPlan( $plan, $budget_period_id, $authcat );
222
223 HideCols($authcat, @hide_cols);
224
225
226 }
227 # ------------------------------------------------------------
228 if ( $authcat =~ m/^Asort/ ) {
229     # ----------- copied from C4::Input::buildCGIsort()
230    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
231     my $sth   = $dbh->prepare($query);
232     $sth->execute($authcat  );
233     if ( $sth->rows > 0 ) {
234         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
235             my $results = $sth->fetchrow_hashref;
236             push @authvals, $results->{authorised_value};
237             $labels{ $results->{authorised_value} } = $results->{lib};
238         }
239     }
240     $sth->finish;
241     @authvals = sort { $a <=> $b } @authvals;
242 }
243 elsif ( $authcat eq 'MONTHS' ) {
244
245     # build months
246     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
247     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
248
249     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
250
251     #calc number of months between
252     my $months      = ( $Dy * 12 ) + $Dm;
253     my $start_month = @start_date[1];
254     my $end_month   = ( $Dy * 12 ) + $Dm;
255
256     for my $mth ( 0 ... $months ) {
257         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
258         $mth = UnixDate( $mth, "%Y-%m" );
259         push( @authvals, $mth );
260     }
261     foreach my $vv (@authvals) {
262         $labels{$vv} = $vv;
263     }
264 }
265
266 elsif ( $authcat eq 'ITEMTYPES' ) {
267     my $query = qq| SELECT itemtype, description FROM itemtypes |;
268     my $sth   = $dbh->prepare($query);
269     $sth->execute(  );
270
271     if ( $sth->rows > 0 ) {
272         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
273             my $results = $sth->fetchrow_hashref;
274             push @authvals, $results->{itemtype};
275             $labels{ $results->{itemtype} } = $results->{description};
276         }
277     }
278     $sth->finish;
279
280 } elsif ( $authcat eq 'BRANCHES' ) {
281
282     my $query = qq| SELECT branchcode, branchname FROM branches |;
283     my $sth   = $dbh->prepare($query);
284     $sth->execute();
285
286     if ( $sth->rows > 0 ) {
287         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
288             my $results = $sth->fetchrow_hashref;
289             push @authvals, $results->{branchcode};
290             $labels{ $results->{branchcode} } = $results->{branchname};
291         }
292     }
293     $sth->finish;
294 }
295
296 my @authvals_row;
297 my $i=1;
298 foreach my $val (@authvals) {
299     my %auth_hash;
300     $auth_hash{val} =   $labels{$val};
301     $auth_hash{code} =   $val;
302     $auth_hash{colnum} =   $i++;
303
304     # display lookup
305     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
306
307     push( @authvals_row, \%auth_hash );
308 }
309
310 #get budgets
311 my ( @buds, @auth_values );
312 foreach my $n (@names) {
313     next if $n =~ m/^[^0-9]/;
314     $n =~ m/(\d*),(.*)/;
315     push @buds, $1;
316     push @auth_values, $2;
317 }
318
319
320 # ------------------------------------------------------------
321 #         DEFAULT DISPLAY BEGINS
322
323 my @mime = ( C4::Context->preference("MIME") );
324 my $CGIextChoice = CGI::scrolling_list(
325     -name     => 'MIME',
326     -id       => 'MIME',
327     -values   => \@mime,
328     -size     => 1,
329     -multiple => 0
330 );
331
332 my @dels         = ( C4::Context->preference("delimiter") );
333 my $CGIsepChoice = CGI::scrolling_list(
334     -name     => 'sep',
335     -id       => 'sep',
336     -values   => \@dels,
337     -size     => 1,
338     -multiple => 0
339 );
340
341 my ( @budget_lines, %cell_hash );
342
343
344 foreach my $budget (@budgets) {
345     my $budget_lock;
346
347     # check budget permission
348     if ( $period->{budget_period_locked} == 1 ) {
349         $budget_lock = 1;
350     } elsif ( $budget->{budget_permission} == 1 ) {
351         $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
352     } elsif ( $budget->{budget_permission} == 2 ) {
353         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
354     }
355
356     # allow hard-coded itemtype and branch planning
357     unless ( $authcat eq 'ITEMTYPES'
358         or  $authcat eq 'BRANCHES'
359         or  $authcat eq 'MONTHS' ) {
360
361         # but skip budgets that dont match the current auth-category
362         next if ( $budget->{'sort1_authcat'} ne $authcat
363             && $budget->{'sort2_authcat'} ne $authcat );
364     }
365
366     my %budget_line; # each row of the  table
367     my @cells_line;
368     my $actual_spent;
369     my $estimated_spent;
370
371     my $i = 0;
372     foreach my $authvalue (@authvals) {
373
374         # get actual stats
375         my %cell = (
376             budget_id        => $budget->{'budget_id'},
377             budget_period_id => $budget->{'budget_period_id'},
378             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
379             authvalue        => $authvalue,
380             authcat          => $authcat,
381             cell_authvalue   => $authvalue,
382             budget_lock      => $budget_lock,
383         );
384
385         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
386         $cell{actual_amount}    = sprintf( "%.2f", $actual );
387         $cell{estimated_amount} = sprintf( "%.2f", $estimated );
388         $cell{display}          = $authvals_row[$i]{display};
389         $cell{colnum}           = $i;
390
391         $actual_spent    += $cell{actual_amount};
392         $estimated_spent += $cell{estimated_amount};
393
394
395         push( @cells_line, \%cell );
396         $i++;
397     }
398
399     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
400     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
401
402     %budget_line = (
403         lines                   => \@cells_line,
404         budget_name_indent      => $budget->{budget_name_indent},
405         budget_amount_formatted => $num->format_price( $budget->{budget_amount} ),
406         budget_amount           => $budget->{budget_amount},
407         budget_alloc            => $budget->{budget_alloc},
408         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
409         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
410         budget_id               => $budget->{budget_id},
411         budget_lock             => $budget_lock,
412     );
413
414
415
416     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
417     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
418     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
419     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
420
421     # skip if active set , and spent == 0
422     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
423
424     push( @budget_lines, \%budget_line );
425 }
426
427 if ( $output eq "file" ) {
428     _print_to_csv(\@authvals_row, \@budget_lines);
429     exit(1);
430 }
431
432 $template->param(
433     authvals_row              => \@authvals_row,
434     budget_lines              => \@budget_lines,
435     budget_period_description => $period->{'budget_period_description'},
436     budget_period_locked      => $period->{'budget_period_locked'},
437     budget_period_id          => $budget_period_id,
438     authcat                   => $authcat,
439     show_active               => $show_active,
440     show_actual               => $show_actual,
441     show_percent              => $show_percent,
442     show_mine                 => $show_mine,
443     cur                       => $cur->{symbol},
444     cur_format                => $cur_format,
445     CGIextChoice              => $CGIextChoice,
446     CGIsepChoice              => $CGIsepChoice,
447
448     authvals              => \@authvals_row,
449     hide_cols_loop              => \@hide_cols
450 );
451
452 output_html_with_http_headers $input, $cookie, $template->output;
453
454 sub _print_to_csv {
455     my ( $header, $results ) = @_;
456
457     my $csv = Text::CSV_XS->new(
458         {   sep_char     => $del,
459             always_quote => 'TRUE',
460         }
461     );
462     print $input->header(
463         -type       => 'application/vnd.sun.xml.calc',
464         -encoding   => 'utf-8',
465         -attachment => "$basename.csv",
466         -name       => "$basename.csv"
467     );
468     my @col = ( 'Budget name', 'Budget total' );
469     foreach my $row (@$header) {
470         push @col, $row->{'val'};
471     }
472     push @col, 'Budget remaining';
473
474     $csv->combine(@col);
475     my $str = $csv->string;
476     print "$str\n";
477
478     foreach my $row (@$results) {
479         my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
480         my $l = $row->{'lines'};
481         foreach my $line (@$l) {
482             push @col, $line->{'estimated_amount'};
483         }
484         push @col, $row->{'budget_est_remain'};
485         $csv->combine(@col);
486         my $str = $csv->string;
487         print "$str\n";
488     }
489 }