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