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