(BUG #4388) aqbudgets.pl: add a column in the table for display the total spent of...
[koha.git] / admin / aqbudgets.pl
1 #!/usr/bin/perl
2
3 #script to administer the aqbudget table
4
5 # Copyright 2008-2009 BibLibre SARL
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use strict;
23 use CGI;
24 use List::Util qw/min/;
25 use Number::Format qw(format_price);
26
27 use C4::Auth qw/get_user_subpermissions/;
28 use C4::Branch; # GetBranches
29 use C4::Dates qw/format_date format_date_in_iso/;
30 use C4::Auth;
31 use C4::Acquisition;
32 use C4::Budgets;   #
33 use C4::Members;  # calls GetSortDetails()
34 use C4::Context;
35 use C4::Output;
36 use C4::Koha;
37 use C4::Debug;
38 #use POSIX qw(locale_h);
39
40 my $input = new CGI;
41 my $dbh     = C4::Context->dbh;
42
43 my ($template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
44     {   template_name   => "admin/aqbudgets.tmpl",
45         query           => $input,
46         type            => "intranet",
47         authnotrequired => 0,
48         flagsrequired   => { acquisition => 'budget_manage' },
49         debug           => 0,
50     }
51 );
52
53 my $cur = GetCurrency();
54 $template->param( cur => $cur->{symbol} );
55
56 my $op = $input->param('op');
57
58 # see if the user want to see all budgets or only owned ones
59 my $show_mine    = 1; #SHOW BY DEFAULT
60 my $show         = $input->param('show'); # SET TO 1, BY A FORM SUMBIT
61 $show_mine       = $input->param('show_mine') if $show == 1;
62
63 # IF USER DOESNT HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
64 if  (  not defined $template->{param_map}->{'CAN_user_acquisition_budget_add_del'}  &&  $op ==  'add_form'  )   {
65     $op = '';
66 }
67
68 my $num=FormatNumber;
69
70 my $script_name               = "/cgi-bin/koha/admin/aqbudgets.pl";
71 my $budget_hash               = $input->Vars;
72 my $budget_id                 = $$budget_hash{budget_id};
73 my $budget_permission         = $input->param('budget_permission');
74 my $budget_period_dropbox     = $input->param('budget_period_dropbox');
75 #filtering non budget keys
76 delete $$budget_hash{$_} foreach grep {/filter|^op$|show/} keys %$budget_hash;
77 my $filter_budgetbranch       = $input->param('filter_budgetbranch');
78 my $filter_budgetname         = $input->param('filter_budgetname');
79 $template->param(
80     notree => ($filter_budgetbranch or $show_mine)
81 );
82 # ' ------- get periods stuff ------------------'
83 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
84 my $period = GetBudgetPeriod($$budget_hash{budget_period_id});
85
86 $template->param(
87         %$period
88 );
89 # ------- get periods stuff ------------------
90
91 # USED FOR PERMISSION COMPARISON LATER
92 my $borrower_id         = $template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'};
93 my $user                = GetMemberDetails($borrower_id);
94 my $user_branchcode     = $user->{'branchcode'};
95
96 $template->param(
97     action      => $script_name,
98     script_name => $script_name,
99     show_mine   => $show_mine,
100     $op || else => 1,
101 );
102
103
104 # retrieve branches
105 my ( $budget, );
106
107 my $branches = GetBranches($show_mine);
108 my @branchloop2;
109 foreach my $thisbranch (keys %$branches) {
110     my %row = (
111         value      => $thisbranch,
112         branchname => $branches->{$thisbranch}->{'branchname'},
113     );
114     $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
115     push @branchloop2, \%row;
116 }
117
118 $template->param(auth_cats_loop => GetBudgetAuthCats($$period{budget_period_id}) );
119
120 # Used to create form to add or  modify a record
121 if ($op eq 'add_form') {
122 #### ------------------- ADD_FORM -------------------------
123
124     # if no buget_id is passed then its an add
125     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
126     my $dropbox_disabled;
127     if (defined $budget_id ) {    ### MOD
128         $budget           = GetBudget($budget_id);
129         $dropbox_disabled = BudgetHasChildren($budget_id);
130         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
131         $budget->{budget_owner_name} = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
132         $$budget{$_}= sprintf("%.2f", $budget->{$_}) for grep{/amount/} keys %$budget;
133     }
134
135     # build budget hierarchy
136     my %labels;
137     my @values;
138     my $hier = GetBudgetHierarchy($$period{budget_period_id});
139     foreach my $r (@$hier) {
140         $r->{budget_code_indent} =~ s/ /\~/g;    #
141         $labels{"$r->{budget_id}"} = $r->{budget_code_indent};
142         push @values, $r->{budget_id};
143     }
144     push @values, '';
145     # if no buget_id is passed then its an add
146     my $budget_parent;
147     my $budget_parent_id;
148     if ($budget){
149         $budget_parent_id = $budget->{'budget_parent_id'} ;
150     }else{
151         $budget_parent_id = $input->param('budget_parent_id');
152     }
153     $budget_parent = GetBudget($budget_parent_id);
154
155     # build branches select
156     my $branches = GetBranches;
157     my @branchloop_select;
158     foreach my $thisbranch ( sort keys %$branches ) {
159         my %row = (
160             value      => $thisbranch,
161             branchname => $branches->{$thisbranch}->{'branchname'},
162         );
163         $row{selected} = 1 if $thisbranch eq $budget->{'budget_branchcode'};
164         push @branchloop_select, \%row;
165     }
166     
167     # populates the YUI planning button
168     my $categories = GetAuthorisedValueCategories();
169     my @auth_cats_loop1 = ();
170     foreach my $category (@$categories) {
171         my $entry = { category => $category,
172                         selected => $budget->{sort1_authcat} eq $category ?1:0,
173                     };
174         push @auth_cats_loop1, $entry;
175     }
176     my @auth_cats_loop2 = ();
177     foreach my $category (@$categories) {
178         my $entry = { category => $category,
179                         selected => $budget->{sort2_authcat} eq $category ?1:0,
180                     };
181         push @auth_cats_loop2, $entry;
182     }
183     $template->param(authorised_value_categories1 => \@auth_cats_loop1);
184     $template->param(authorised_value_categories2 => \@auth_cats_loop2);
185
186     my $budget_perm_dropbox =
187     GetBudgetPermDropbox($budget->{'budget_permission'});
188     
189     # if no buget_id is passed then its an add
190     $template->param(
191         add_validate                  => 1,
192         dateformat                => C4::Dates->new()->visual(),
193         budget_parent_id                  => $budget_parent->{'budget_id'},
194         budget_parent_name                => $budget_parent->{'budget_name'},
195         budget_perm_dropbox       => $budget_perm_dropbox,
196         branchloop_select         => \@branchloop_select,
197                 %$period,
198                 %$budget,
199     );
200                                                     # END $OP eq ADD_FORM
201 #---------------------- DEFAULT DISPLAY BELOW ---------------------
202
203 # called by default form, used to confirm deletion of data in DB
204 } elsif ($op eq 'delete_confirm') {
205
206     my $budget = GetBudget($budget_id);
207     $template->param(
208         budget_id     => $budget->{'budget_id'},
209         budget_code   => $budget->{'budget_code'},
210         budget_name   => $budget->{'budget_name'},
211         budget_amount => $num->format_price(  $budget->{'budget_amount'} ),
212     );
213                                                     # END $OP eq DELETE_CONFIRM
214 # called by delete_confirm, used to effectively confirm deletion of data in DB
215 }  else{
216     if ( $op eq 'delete_confirmed' ) {
217         my $rc = DelBudget($budget_id);
218     }elsif( $op eq 'add_validate' ) {
219         if ( defined $$budget_hash{budget_id} ) {
220             ModBudget( $budget_hash );
221         } else {
222             AddBudget( $budget_hash );
223         }
224     }
225     my $branches = GetBranches();
226     my $budget_period_dropbox = GetBudgetPeriodsDropbox($$period{budget_period_id} );
227     $template->param(
228         budget_period_dropbox     => $budget_period_dropbox,
229         budget_id                 => $budget_id,
230         %$period,
231     );
232
233     my $moo = GetBudgetHierarchy($$period{budget_period_id}, C4::Context->userenv->{branchcode}, $show_mine?$borrower_id:'');
234     my @budgets = @$moo; #FIXME
235
236     my $toggle = 0;
237     my @loop;
238     my $period_total = 0;
239     my ( $period_alloc_total, $base_spent_total );
240
241         use YAML;
242         $debug && warn Dump(@budgets);
243         #This Looks WEIRD to me : should budgets be filtered in such a way ppl who donot own it would not see the amount spent on the budget by others ?
244
245     foreach my $budget (@budgets) {
246         #Level and sublevels total spent
247         $budget->{'total_levels_spent'} = GetChildBudgetsSpent($budget->{"budget_id"});
248
249         # PERMISSIONS
250         unless($staffflags->{'superlibrarian'} % 2   == 1 ) {
251             #IF NO PERMS, THEN DISABLE EDIT/DELETE
252             unless ( $template->{param_map}->{'CAN_user_acquisition_budget_modify'} ) {
253                 $budget->{'budget_lock'} = 1;
254             }
255             # check budget permission
256             if ( $$period{budget_period_locked} == 1 ) {
257                 $budget->{'budget_lock'} = 1;
258
259             } elsif ( $budget->{budget_permission} == 1 ) {
260
261                 if ( $borrower_id != $budget->{'budget_owner_id'} ) {
262                     $budget->{'budget_lock'} = 1;
263                 }
264                 # check parent perms too
265                 my $parents_perm = 0;
266                 if ( $budget->{depth} > 0 ) {
267                     $parents_perm = CheckBudgetParentPerm( $budget, $borrower_id );
268                     delete $budget->{'budget_lock'} if $parents_perm == '1';
269                 }
270             } elsif ( $budget->{budget_permission} == 2 ) {
271
272                 $budget->{'budget_lock'} = 1 if $user_branchcode ne $budget->{budget_branchcode};
273             }
274         }    # ...SUPER_LIB END
275
276         # if a budget search doesnt match, next
277         if ($filter_budgetname ) {
278             next unless  $budget->{budget_code}  =~ m/$filter_budgetname/  ||
279             $budget->{name}  =~ m/$filter_budgetname/ ;
280         }
281         if ($filter_budgetbranch ) {
282             next unless  $budget->{budget_branchcode}  =~ m/$filter_budgetbranch/;
283         }
284
285 ## TOTALS
286         # adds to total  - only if budget is a 'top-level' budget
287         $period_alloc_total += $budget->{'budget_amount_total'} if $budget->{'depth'} == 0;
288         $base_spent_total += $budget->{'budget_spent'};
289         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'total_levels_spent'};
290
291 # if amount == 0 dont display...
292         delete  $budget->{'budget_unalloc_sublevel'} if  $budget->{'budget_unalloc_sublevel'} == 0 ;
293
294         $budget->{'remaining_pos'} = 1 if $budget->{'budget_remaining'} > 0;
295         $budget->{'remaining_neg'} = 1 if $budget->{'budget_remaining'} < 0;
296                 for (grep {/total_levels_spent|budget_spent|budget_amount|budget_remaining|budget_unalloc/} keys %$budget){
297         $$budget{$_}               = $num->format_price( $$budget{$_} ) if defined($$budget{$_})
298                 }
299
300         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
301         $budget->{"budget_owner_name"}     = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
302         $budget->{"budget_borrowernumber"} = $borrower->{'borrowernumber'};
303
304         #Make a list of parents of the bugdet
305         my @budget_hierarchy;
306         push  @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} };
307         my $parent_id = $budget->{"budget_parent_id"};
308         while ($parent_id) {
309             my $parent = GetBudget($parent_id);
310             push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} };
311             $parent_id = $parent->{"budget_parent_id"};
312         }
313         push  @budget_hierarchy, { element_name => $period->{"budget_period_description"} }; 
314         @budget_hierarchy = reverse(@budget_hierarchy);
315
316         push( @loop, {  %{$budget},
317                         branchname  => $branches->{ $budget->{branchcode} }->{branchname},
318                         budget_hierarchy => \@budget_hierarchy,
319                     }
320         );
321     }
322
323     my $budget_period_total = $num->format_price($$period{budget_period_total}) if $$period{budget_period_total};
324     $template->param(
325         else                   => 1,
326         budget                 => \@loop,
327         budget_period_total    => $budget_period_total,
328         period_alloc_total     => $num->format_price($period_alloc_total),
329         base_spent_total       => $num->format_price($base_spent_total),
330         branchloop             => \@branchloop2,
331     );
332
333 } #---- END $OP eq DEFAULT
334
335 output_html_with_http_headers $input, $cookie, $template->output;