Bug 12905: funds with children could not be deleted
[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 Modern::Perl;
23
24 use CGI qw ( -utf8 );
25 use List::Util qw/min/;
26
27 use Koha::Database;
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
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.tt",
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( symbol => $cur->{symbol},
55                   currency => $cur->{currency}
56                );
57
58 my $op = $input->param('op') || 'list';
59
60 # see if the user want to see all budgets or only owned ones by default
61 my $show_mine = $input->param('show_mine') // 0;
62
63 # IF USER DOESNT HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
64 if (not defined $template->{VARS}->{'CAN_user_acquisition_budget_add_del'}
65     and $op eq 'add_form')
66 {
67     $op = 'list';
68 }
69
70 # get only the columns of aqbudgets in budget_hash
71 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
72 my $budget_hash = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $input->param($_) )  : () } keys( %{$input->Vars()}) } ;
73
74 my $budget_id                 = $input->param('budget_id');
75 my $budget_period_id          = $input->param('budget_period_id');
76 my $budget_permission         = $input->param('budget_permission');
77 my $budget_users_ids          = $input->param('budget_users_ids');
78 my $filter_budgetbranch       = $input->param('filter_budgetbranch') // '';
79 my $filter_budgetname         = $input->param('filter_budgetname');
80
81
82 # ' ------- get periods stuff ------------------'
83 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
84 my $period;
85 if ( $budget_period_id ) {
86     $period = GetBudgetPeriod( $budget_period_id );
87 }
88
89 # ------- get periods stuff ------------------
90
91 # USED FOR PERMISSION COMPARISON LATER
92 my $borrower_id         = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
93 my $user                = GetMemberDetails($borrower_id);
94 my $user_branchcode     = $user->{'branchcode'};
95
96 $template->param(
97     show_mine   => $show_mine,
98     op  => $op,
99 );
100
101 my $budget;
102
103 my $branches = GetBranches($show_mine);
104 my @branchloop2;
105 foreach my $thisbranch (keys %$branches) {
106     my %row = (
107         value      => $thisbranch,
108         branchname => $branches->{$thisbranch}->{'branchname'},
109     );
110     $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
111     push @branchloop2, \%row;
112 }
113
114 $template->param(auth_cats_loop => GetBudgetAuthCats( $budget_period_id ))
115     if $budget_period_id;
116
117 # Used to create form to add or  modify a record
118 if ($op eq 'add_form') {
119 #### ------------------- ADD_FORM -------------------------
120     # if no buget_id is passed then its an add
121     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
122     my $dropbox_disabled;
123     if (defined $budget_id ) {    ### MOD
124         $budget = GetBudget($budget_id);
125         if (!CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
126             $template->param(error_not_authorised_to_modify => 1);
127             output_html_with_http_headers $input, $cookie, $template->output;
128             exit;
129         }
130         $dropbox_disabled = BudgetHasChildren($budget_id);
131         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
132         $budget->{budget_owner_name} = ( $borrower ? $borrower->{'firstname'} . ' ' . $borrower->{'surname'} : '' );
133         $$budget{$_}= sprintf("%.2f", $budget->{$_}) for grep{ /amount|encumb|expend/ } keys %$budget;
134     }
135
136     # build budget hierarchy
137     my %labels;
138     my @values;
139     my $hier = GetBudgetHierarchy($$period{budget_period_id});
140     foreach my $r (@$hier) {
141         $labels{"$r->{budget_id}"} = $r->{budget_code};
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 $budget and $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 and $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 and $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     if($budget->{'budget_permission'}){
187         my $budget_permission = "budget_perm_".$budget->{'budget_permission'};
188         $template->param($budget_permission => 1);
189     }
190
191     if ($budget) {
192         my @budgetusers = GetBudgetUsers($budget->{budget_id});
193         my @budgetusers_loop;
194         foreach my $borrowernumber (@budgetusers) {
195             my $member = C4::Members::GetMember(
196                 borrowernumber => $borrowernumber);
197             push @budgetusers_loop, {
198                 firstname => $member->{firstname},
199                 surname => $member->{surname},
200                 borrowernumber => $borrowernumber
201             };
202         }
203         $template->param(
204             budget_users => \@budgetusers_loop,
205             budget_users_ids => join ':', @budgetusers
206         );
207     }
208
209     # if no buget_id is passed then its an add
210     $template->param(
211         budget_has_children => BudgetHasChildren( $budget->{budget_id} ),
212         budget_parent_id                  => $budget_parent->{'budget_id'},
213         budget_parent_name                => $budget_parent->{'budget_name'},
214         branchloop_select         => \@branchloop_select,
215                 %$period,
216                 %$budget,
217     );
218                                                     # END $OP eq ADD_FORM
219 #---------------------- DEFAULT DISPLAY BELOW ---------------------
220
221 # called by default form, used to confirm deletion of data in DB
222 } elsif ($op eq 'delete_confirm') {
223
224     my $budget = GetBudget($budget_id);
225     $template->param(
226         budget_id     => $budget->{'budget_id'},
227         budget_code   => $budget->{'budget_code'},
228         budget_name   => $budget->{'budget_name'},
229         budget_amount => $budget->{'budget_amount'},
230     );
231                                                     # END $OP eq DELETE_CONFIRM
232 # called by delete_confirm, used to effectively confirm deletion of data in DB
233 } elsif ( $op eq 'delete_confirmed' ) {
234     if ( BudgetHasChildren( $budget_id ) ) {
235         # We should never be here, the interface does not provide this action.
236         die("Delete a fund with children is not possible");
237     }
238     my $rc = DelBudget($budget_id);
239     $op = 'list';
240 } elsif( $op eq 'add_validate' ) {
241     my @budgetusersid;
242     if (defined $budget_users_ids){
243         @budgetusersid = split(':', $budget_users_ids);
244     }
245
246     my $budget_modified = 0;
247     if (defined $budget_id) {
248         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
249             $staffflags)
250         ) {
251             ModBudget( $budget_hash );
252             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
253             $budget_modified = 1;
254         }
255         else {
256             $template->param(error_not_authorised_to_modify => 1);
257         }
258     } else {
259         $budget_hash->{budget_id} = AddBudget( $budget_hash );
260         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
261         $budget_modified = 1;
262     }
263
264     my $set_owner_to_children = $input->param('set_owner_to_children');
265     if ( $set_owner_to_children and $budget_modified ) {
266         C4::Budgets::SetOwnerToFundHierarchy( $budget_hash->{budget_id}, $budget_hash->{budget_owner_id} );
267     }
268     $op = 'list';
269 }
270
271 if ( $op eq 'list' ) {
272     my $branches = GetBranches();
273     $template->param(
274         budget_id => $budget_id,
275         %$period,
276     );
277
278     my @budgets = @{
279         GetBudgetHierarchy($$period{budget_period_id},
280             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
281     };
282
283     my $period_total = 0;
284     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
285
286         #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 ?
287
288     foreach my $budget (@budgets) {
289         # PERMISSIONS
290         unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
291             $budget->{'budget_lock'} = 1;
292         }
293
294         # if a budget search doesnt match, next
295         if ($filter_budgetname) {
296             next
297               unless $budget->{budget_code} =~ m/$filter_budgetname/i
298                   || $budget->{budget_name} =~ m/$filter_budgetname/i;
299         }
300         if ($filter_budgetbranch ) {
301             next unless  $budget->{budget_branchcode} eq $filter_budgetbranch;
302         }
303
304 ## TOTALS
305         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered};
306         $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered};
307         # adds to total  - only if budget is a 'top-level' budget
308         unless ( defined $budget->{budget_parent_id} ) {
309             $period_alloc_total += $budget->{'budget_amount'};
310             $spent_total += $budget->{total_spent};
311             $ordered_total += $budget->{total_ordered};
312             $available_total += $budget->{total_remaining};
313         }
314
315 # if amount == 0 dont display...
316         delete $budget->{'budget_unalloc_sublevel'}
317             if (!defined $budget->{'budget_unalloc_sublevel'}
318             or $budget->{'budget_unalloc_sublevel'} == 0);
319
320         # Value of budget_spent equals 0 instead of undefined value
321         $budget->{budget_spent} = 0 unless defined($budget->{budget_spent});
322         $budget->{budget_ordered} = 0 unless defined($budget->{budget_ordered});
323
324         #Make a list of parents of the bugdet
325         my @budget_hierarchy;
326         push  @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} };
327         my $parent_id = $budget->{"budget_parent_id"};
328         while ($parent_id) {
329             my $parent = GetBudget($parent_id);
330             push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} };
331             $parent_id = $parent->{"budget_parent_id"};
332         }
333         push  @budget_hierarchy, { element_name => $period->{"budget_period_description"} };
334         @budget_hierarchy = reverse(@budget_hierarchy);
335
336         $budget->{budget_hierarchy} = \@budget_hierarchy;
337
338         $budget->{budget_has_children} = BudgetHasChildren( $budget->{budget_id} );
339     }
340
341     my $budget_period_total = $period->{budget_period_total};
342
343     my $periods = GetBudgetPeriods();
344
345     $template->param(
346         op                     => 'list',
347         budgets                => \@budgets,
348         periods                => $periods,
349         budget_period_total    => $budget_period_total,
350         period_alloc_total     => $period_alloc_total,
351         spent_total            => $spent_total,
352         ordered_total          => $ordered_total,
353         available_total        => $available_total,
354         branchloop             => \@branchloop2,
355     );
356
357 } #---- END list
358
359 output_html_with_http_headers $input, $cookie, $template->output;