budgfixing budgets & planning and code cleaning
[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 ####  @hide_cols
104
105
106
107 =c
108 my $show_mine    = 1; #SHOW BY DEFAULT
109 my $show         = $input->param('show'); # SET TO 1, BY A FORM SUMBIT
110 $show_mine       = $input->param('show_mine') if $show == 1;
111 =cut
112
113 my $cur_format = C4::Context->preference("CurrencyFormat");
114 my $num;
115
116 if ( $cur_format eq 'FR' ) {
117     $num = new Number::Format(
118         'decimal_fill'      => '2',
119         'decimal_point'     => ',',
120         'int_curr_symbol'   => '',
121         'mon_thousands_sep' => ' ',
122         'thousands_sep'     => ' ',
123         'mon_decimal_point' => ','
124     );
125 } else {  # US by default..
126     $num = new Number::Format(
127         'int_curr_symbol'   => '',
128         'mon_thousands_sep' => ',',
129         'mon_decimal_point' => '.'
130     );
131 }
132
133 if ( $budget_period_locked == 1  && not defined  $show_actual ) {
134      $show_actual  = 1;
135 }
136
137 $authcat = 'Asort1' if  not defined $authcat; # defaults to Asort if no authcat given
138
139 my $budget_id = $input->param('budget_id');
140 my $op        = $input->param("op");
141
142 my $budget_branchcode;
143
144
145 #my $budgets_ref = GetBudgetHierarchy( $budget_period_id, $budget_branchcode );
146 ## ##  $budgets_ref
147
148 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'}:'' );
149
150 # build categories list
151 my $sth = $dbh->prepare("select distinct category from authorised_values where category like 'A%' ");
152 $sth->execute;
153
154 # the list
155 my @category_list;
156
157 # a hash, to check that some hardcoded categories exist.
158 my %categories;
159 while ( my ($category) = $sth->fetchrow_array ) {
160     push( @category_list, $category );
161     $categories{$category} = 1;
162 }
163
164 push( @category_list, 'MONTHS' );
165 push( @category_list, 'ITEMTYPES' );
166 push( @category_list, 'BRANCHES' );
167
168 # push koha system categories
169
170 #reorder the list
171 @category_list = sort { $a cmp $b } @category_list;
172 my $tab_list = CGI::scrolling_list(
173     -name     => 'authcat',
174     -id       => 'authcat',
175     -values   => \@category_list,
176     -default  => $authcat,
177     -size     => 1,
178     -tabindex => '',
179     -multiple => 0,
180 );
181
182 $template->param( authcat_dropbox => $tab_list );
183
184 my @budgets = @$budgets_ref;
185 my $CGISort;
186 my @authvals;
187 my %labels;
188
189
190     my @names = $input->param();
191
192 # ------------------------------------------------------------
193 if ( $op eq 'save' ) {
194
195
196     ### ---------------------  save
197
198     ####  @names
199
200
201     #get budgets
202     my ( @buds, @auth_values );
203     foreach my $n (@names) {
204         next if $n =~ m/^[^0-9]/;
205         my @moo = split( ',', $n );
206         push @buds, $moo[0];
207         push @auth_values, $moo[1];
208     }
209
210     #uniq buds and auth
211     my %seen;
212     @buds        = grep { !$seen{$_}++ } @buds;
213     @auth_values = grep { !$seen{$_}++ } @auth_values;
214     my @budget_ids;
215     my @budget_lines;
216
217     foreach my $budget (@buds) {
218         my %budget_line;
219         my @cells_line;
220         my %cell_hash;
221
222         foreach my $authvalue (@auth_values) {
223             # get actual stats
224             my $cell_name        = "$budget,$authvalue";
225             my $estimated_amount = $input->param("$cell_name");
226             my %cell_hash = (
227                 estimated_amount => $estimated_amount,
228                 authvalue        => $authvalue,
229                 authcat          => $authcat,
230                 budget_id        => $budget,
231                 budget_period_id => $budget_period_id,
232             );
233             push( @cells_line, \%cell_hash );
234         }
235
236         %budget_line = (
237             lines => \@cells_line,
238         );
239         push( @budget_lines, \%budget_line );
240     }
241     my $plan = \@budget_lines;
242     ModBudgetPlan( $plan, $budget_period_id, $authcat );
243
244 #### iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
245 HideCols($authcat, @hide_cols);
246
247
248 }
249
250
251 # ------------------------------------------------------------
252
253
254 if ( $authcat =~ m/^Asort/ ) {
255
256 #### eeeee
257     # ----------- copied from C4::Input::buildCGIsort()
258    my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib };
259     my $sth   = $dbh->prepare($query);
260 #### $query
261 #    $sth->{TraceLevel} = 2;
262     $sth->execute($authcat  );
263
264 =c
265     my $query = qq{ 
266
267 SELECT * FROM authorised_values
268 JOIN aqbudgets_planning  ON
269     (aqbudgets_planning.authvalue = authorised_values.authorised_value )
270 WHERE (authcat = ?
271 AND category = ?
272 AND budget_period_id = ?
273 AND display = 1 ) 
274 ORDER BY lib   };
275
276
277     my $sth   = $dbh->prepare($query);
278 #### $query
279     $sth->{TraceLevel} = 2;
280
281     $sth->execute($authcat, $authcat, $budget_period_id  );
282 =cut
283
284
285 #### qq
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->{authorised_value};
291             $labels{ $results->{authorised_value} } = $results->{lib};
292  #          $labels{ $results->{display} } = 1 ;
293
294         }
295     }
296     $sth->finish;
297     @authvals = sort { $a <=> $b } @authvals;
298
299
300 ####  @authvals
301
302
303
304
305 }
306 elsif ( $authcat eq 'MONTHS' ) {
307
308     # build months
309     my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) );
310     my @end_date   = UnixDate( $budget_period_enddate,   ( '%Y', '%m', '%d' ) );
311
312     my ( $Dy, $Dm, $Dd ) = Delta_YMD( @start_date, @end_date );
313
314     #calc number of months between
315     my $months      = ( $Dy * 12 ) + $Dm;
316     my $start_month = @start_date[1];
317     my $end_month   = ( $Dy * 12 ) + $Dm;
318
319     for my $mth ( 0 ... $months ) {
320         $mth = DateCalc( $budget_period_startdate, "+ $mth months" );
321         $mth = UnixDate( $mth, "%Y-%m" );
322         push( @authvals, $mth );
323     }
324     foreach my $vv (@authvals) {
325         $labels{$vv} = $vv;
326     }
327 }
328
329 elsif ( $authcat eq 'ITEMTYPES' ) {
330 #### aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
331
332     my $query = qq| SELECT itemtype, description FROM itemtypes |;
333 =c
334     my $query = qq| SELECT * FROM aqbudgets_planning
335                     JOIN itemtypes ON (aqbudgets_planning.authvalue = itemtypes.itemtype)
336                     WHERE (authcat = 'itemtypes'
337                             AND budget_period_id = ? )     |;
338 =cut
339
340
341     my $sth   = $dbh->prepare($query);
342     $sth->{TraceLevel} = 3;
343
344
345     #$sth->execute( $budget_period_id  );
346     $sth->execute(  );
347
348     if ( $sth->rows > 0 ) {
349         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
350             my $results = $sth->fetchrow_hashref;
351             push @authvals, $results->{itemtype};
352             $labels{ $results->{itemtype} } = $results->{description};
353         }
354     }
355     $sth->finish;
356
357
358             ####  @authvals
359
360
361
362
363
364
365 } elsif ( $authcat eq 'BRANCHES' ) {
366
367     my $query = qq| SELECT branchcode, branchname FROM branches |;
368     my $sth   = $dbh->prepare($query);
369     $sth->execute();
370
371     if ( $sth->rows > 0 ) {
372         for ( my $i = 0 ; $i < $sth->rows ; $i++ ) {
373             my $results = $sth->fetchrow_hashref;
374             push @authvals, $results->{branchcode};
375             $labels{ $results->{branchcode} } = $results->{branchname};
376         }
377     }
378     $sth->finish;
379 }
380
381 ####     @authvals
382 ####     %labels
383
384
385
386 my @authvals_row;
387 my $i=1;
388 foreach my $val (@authvals) {
389     my %auth_hash;
390     $auth_hash{val} =   $labels{$val};
391     $auth_hash{code} =   $val;
392     $auth_hash{colnum} =   $i++;
393
394     # display lookup
395     $auth_hash{display} = GetCols( $authcat,  $auth_hash{code});
396
397     push( @authvals_row, \%auth_hash );
398 }
399 #### ddddddddddddd
400 #### @authvals_row
401
402
403
404
405
406
407
408
409
410
411     #get budgets
412     my ( @buds, @auth_values );
413     foreach my $n (@names) {
414         next if $n =~ m/^[^0-9]/;
415         $n =~ m/(\d*),(.*)/;
416         push @buds, $1;
417         push @auth_values, $2;
418     }
419
420
421 # ------------------------------------------------------------
422 #         DEFAULT DISPLAY BEGINS
423
424 my @mime = ( C4::Context->preference("MIME") );
425 foreach my $mime (@mime) {
426     #               warn "".$mime;
427 }
428
429 my $CGIextChoice = CGI::scrolling_list(
430     -name     => 'MIME',
431     -id       => 'MIME',
432     -values   => \@mime,
433     -size     => 1,
434     -multiple => 0
435 );
436
437 my @dels         = ( C4::Context->preference("delimiter") );
438 my $CGIsepChoice = CGI::scrolling_list(
439     -name     => 'sep',
440     -id       => 'sep',
441     -values   => \@dels,
442     -size     => 1,
443     -multiple => 0
444 );
445
446 my ( @budget_lines, %cell_hash );
447
448
449
450
451
452 foreach my $budget (@budgets) {
453     my $budget_lock;
454
455     # check budget permission
456     if ( $period->{budget_period_locked} == 1 ) {
457         $budget_lock = 1;
458     } elsif ( $budget->{budget_permission} == 1 ) {
459         $budget_lock = 1 if $borrower_id != $budget->{'budget_owner_id'};
460     } elsif ( $budget->{budget_permission} == 2 ) {
461         $budget_lock = 1 if $borrower_branchcode ne $budget->{budget_branchcode};
462     }
463
464     # allow hard-coded itemtype and branch planning
465     unless ( $authcat eq 'ITEMTYPES'
466         or  $authcat eq 'BRANCHES'
467         or  $authcat eq 'MONTHS' ) {
468
469         # but skip budgets that dont match the current auth-category
470         next if ( $budget->{'sort1_authcat'} ne $authcat
471             && $budget->{'sort2_authcat'} ne $authcat );
472     }
473
474     my %budget_line; # each row of the  table
475     my @cells_line;
476     my $actual_spent;
477     my $estimated_spent;
478
479     my $i = 0;
480     foreach my $authvalue (@authvals) {
481
482         # get actual stats
483         my %cell = (
484             budget_id        => $budget->{'budget_id'},
485             budget_period_id => $budget->{'budget_period_id'},
486             cell_name        => $budget->{'budget_id'} . ',' . $authvalue,
487             authvalue        => $authvalue,
488             authcat          => $authcat,
489             cell_authvalue   => $authvalue,
490             budget_lock      => $budget_lock,
491         );
492
493         my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget );
494         $cell{actual_amount}    = sprintf( "%.2f", $actual );
495         $cell{estimated_amount} = sprintf( "%.2f", $estimated );
496         $cell{display}          = $authvals_row[$i]{display};
497         $cell{colnum}           = $i;
498
499         $actual_spent    += $cell{actual_amount};
500         $estimated_spent += $cell{estimated_amount};
501
502
503         push( @cells_line, \%cell );
504         $i++;
505     }
506
507
508
509     #     lines => \@cells_line,
510     my $budget_act_remain = $budget->{budget_amount} - $actual_spent;
511     my $budget_est_remain = $budget->{budget_amount} - $estimated_spent;
512
513     %budget_line = (
514         lines                   => \@cells_line,
515         budget_name_indent      => $budget->{budget_name_indent},
516         budget_amount_formatted => $num->format_price( $budget->{budget_amount} ),
517         budget_amount           => $budget->{budget_amount},
518         budget_alloc            => $budget->{budget_alloc},
519         budget_act_remain       => sprintf( "%.2f", $budget_act_remain ),
520         budget_est_remain       => sprintf( "%.2f", $budget_est_remain ),
521         budget_id               => $budget->{budget_id},
522         budget_lock             => $budget_lock,
523     );
524
525
526
527     $budget_line{est_negative} = '1' if $budget_est_remain < 0;
528     $budget_line{est_positive} = '1' if $budget_est_remain > 0;
529     $budget_line{act_negative} = '1' if $budget_act_remain < 0;
530     $budget_line{act_positive} = '1' if $budget_act_remain > 0;
531
532     # skip if active set , and spent == 0
533     next if ( $show_active == '1' && ( $actual_spent == 0 ) );
534
535
536     ### %budget_lin
537
538     push( @budget_lines, \%budget_line );
539 }
540
541 if ( $output eq "file" ) {
542     _print_to_csv(\@authvals_row, \@budget_lines);
543     exit(1);
544 }
545
546     ## ## @budget_lines
547
548 $template->param(
549     authvals_row              => \@authvals_row,
550     budget_lines              => \@budget_lines,
551     budget_period_description => $period->{'budget_period_description'},
552     budget_period_locked      => $period->{'budget_period_locked'},
553     budget_period_id          => $budget_period_id,
554     authcat                   => $authcat,
555     show_active               => $show_active,
556     show_actual               => $show_actual,
557     show_percent              => $show_percent,
558     show_mine                 => $show_mine,
559     cur                       => $cur->{symbol},
560     cur_format                => $cur_format,
561     CGIextChoice              => $CGIextChoice,
562     CGIsepChoice              => $CGIsepChoice,
563
564     authvals              => \@authvals_row,
565     hide_cols_loop              => \@hide_cols
566 );
567 #### uuuuuuuuuuu
568
569
570
571 output_html_with_http_headers $input, $cookie, $template->output;
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588 sub _print_to_csv {
589     my ( $header, $results ) = @_;
590
591     my $csv = Text::CSV_XS->new(
592         {   sep_char     => $del,
593             always_quote => 'TRUE',
594         }
595     );
596     print $input->header(
597         -type       => 'application/vnd.sun.xml.calc',
598         -encoding   => 'utf-8',
599         -attachment => "$basename.csv",
600         -name       => "$basename.csv"
601     );
602     my @col = ( 'Budget name', 'Budget total' );
603     foreach my $row (@$header) {
604         push @col, $row->{'val'};
605     }
606     push @col, 'Budget remaining';
607
608     $csv->combine(@col);
609     my $str = $csv->string;
610     print "$str\n";
611
612     foreach my $row (@$results) {
613         my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} );
614         my $l = $row->{'lines'};
615         foreach my $line (@$l) {
616             push @col, $line->{'estimated_amount'};
617         }
618         push @col, $row->{'budget_est_remain'};
619         $csv->combine(@col);
620         my $str = $csv->string;
621         print "$str\n";
622     }
623 }
624