Bug 6679: (follow-up) fix 9 perlcritic violations in C4/TmplTokenType.pm
[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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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::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
39 my $input = new CGI;
40 my $dbh     = C4::Context->dbh;
41
42 my ($template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user(
43     {   template_name   => "admin/aqbudgets.tt",
44         query           => $input,
45         type            => "intranet",
46         authnotrequired => 0,
47         flagsrequired   => { acquisition => 'budget_manage' },
48         debug           => 0,
49     }
50 );
51
52 my $cur = GetCurrency();
53 $template->param( symbol => $cur->{symbol},
54                   currency => $cur->{currency}
55                );
56
57 my $op = $input->param('op') || 'list';
58
59 # see if the user want to see all budgets or only owned ones by default
60 my $show_mine = $input->param('show_mine') // 0;
61
62 # IF USER DOESN'T HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
63 if (not defined $template->{VARS}->{'CAN_user_acquisition_budget_add_del'}
64     and $op eq 'add_form')
65 {
66     $op = 'list';
67 }
68
69 # get only the columns of aqbudgets in budget_hash
70 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
71 my $budget_hash = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $input->param($_) )  : () } keys( %{$input->Vars()}) } ;
72
73 my $budget_id                 = $input->param('budget_id');
74 my $budget_period_id          = $input->param('budget_period_id');
75 my $budget_permission         = $input->param('budget_permission');
76 my $budget_users_ids          = $input->param('budget_users_ids');
77 my $filter_budgetbranch       = $input->param('filter_budgetbranch') // '';
78 my $filter_budgetname         = $input->param('filter_budgetname');
79
80
81 # ' ------- get periods stuff ------------------'
82 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
83 my $period;
84 if ( $budget_period_id ) {
85     $period = GetBudgetPeriod( $budget_period_id );
86 }
87
88 # ------- get periods stuff ------------------
89
90 # USED FOR PERMISSION COMPARISON LATER
91 my $borrower_id         = $template->{VARS}->{'USER_INFO'}->{'borrowernumber'};
92 my $user                = C4::Members::GetMember( borrowernumber => $borrower_id );
93 my $user_branchcode     = $user->{'branchcode'};
94
95 $template->param(
96     show_mine   => $show_mine,
97     op  => $op,
98 );
99
100 my $budget;
101
102 my $branchloop = C4::Branch::GetBranchesLoop($filter_budgetbranch);
103
104 $template->param(auth_cats_loop => GetBudgetAuthCats( $budget_period_id ))
105     if $budget_period_id;
106
107 # Used to create form to add or  modify a record
108 if ($op eq 'add_form') {
109 #### ------------------- ADD_FORM -------------------------
110     # if no buget_id is passed then its an add
111     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
112     my $dropbox_disabled;
113     if (defined $budget_id ) {    ### MOD
114         $budget = GetBudget($budget_id);
115         if (!CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
116             $template->param(error_not_authorised_to_modify => 1);
117             output_html_with_http_headers $input, $cookie, $template->output;
118             exit;
119         }
120         $dropbox_disabled = BudgetHasChildren($budget_id);
121         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
122         $budget->{budget_owner_name} = ( $borrower ? $borrower->{'firstname'} . ' ' . $borrower->{'surname'} : '' );
123     }
124
125     # build budget hierarchy
126     my %labels;
127     my @values;
128     my $hier = GetBudgetHierarchy($$period{budget_period_id});
129     foreach my $r (@$hier) {
130         $labels{"$r->{budget_id}"} = $r->{budget_code};
131         push @values, $r->{budget_id};
132     }
133     push @values, '';
134     # if no buget_id is passed then its an add
135     my $budget_parent;
136     my $budget_parent_id;
137     if ($budget){
138         $budget_parent_id = $budget->{'budget_parent_id'} ;
139     }else{
140         $budget_parent_id = $input->param('budget_parent_id');
141     }
142     $budget_parent = GetBudget($budget_parent_id);
143
144     # build branches select
145     my $branches = GetBranches;
146     my @branchloop_select;
147     foreach my $thisbranch ( sort keys %$branches ) {
148         my %row = (
149             value      => $thisbranch,
150             branchname => $branches->{$thisbranch}->{'branchname'},
151         );
152         $row{selected} = 1 if $budget and $thisbranch eq $budget->{'budget_branchcode'};
153         push @branchloop_select, \%row;
154     }
155     
156     # populates the YUI planning button
157     my $categories = GetAuthorisedValueCategories();
158     my @auth_cats_loop1 = ();
159     foreach my $category (@$categories) {
160         my $entry = { category => $category,
161                         selected => ( $budget and $budget->{sort1_authcat} eq $category ? 1 : 0 ),
162                     };
163         push @auth_cats_loop1, $entry;
164     }
165     my @auth_cats_loop2 = ();
166     foreach my $category (@$categories) {
167         my $entry = { category => $category,
168                         selected => ( $budget and $budget->{sort2_authcat} eq $category ? 1 : 0 ),
169                     };
170         push @auth_cats_loop2, $entry;
171     }
172     $template->param(authorised_value_categories1 => \@auth_cats_loop1);
173     $template->param(authorised_value_categories2 => \@auth_cats_loop2);
174
175     if($budget->{'budget_permission'}){
176         my $budget_permission = "budget_perm_".$budget->{'budget_permission'};
177         $template->param($budget_permission => 1);
178     }
179
180     if ($budget) {
181         my @budgetusers = GetBudgetUsers($budget->{budget_id});
182         my @budgetusers_loop;
183         foreach my $borrowernumber (@budgetusers) {
184             my $member = C4::Members::GetMember(
185                 borrowernumber => $borrowernumber);
186             push @budgetusers_loop, {
187                 firstname => $member->{firstname},
188                 surname => $member->{surname},
189                 borrowernumber => $borrowernumber
190             };
191         }
192         $template->param(
193             budget_users => \@budgetusers_loop,
194             budget_users_ids => join ':', @budgetusers
195         );
196     }
197
198     # if no buget_id is passed then its an add
199     $template->param(
200         budget_has_children => BudgetHasChildren( $budget->{budget_id} ),
201         budget_parent_id                  => $budget_parent->{'budget_id'},
202         budget_parent_name                => $budget_parent->{'budget_name'},
203         branchloop_select         => \@branchloop_select,
204                 %$period,
205                 %$budget,
206     );
207                                                     # END $OP eq ADD_FORM
208 #---------------------- DEFAULT DISPLAY BELOW ---------------------
209
210 # called by default form, used to confirm deletion of data in DB
211 } elsif ($op eq 'delete_confirm') {
212
213     my $budget = GetBudget($budget_id);
214     $template->param(
215         budget_id     => $budget->{'budget_id'},
216         budget_code   => $budget->{'budget_code'},
217         budget_name   => $budget->{'budget_name'},
218         budget_amount => $budget->{'budget_amount'},
219     );
220                                                     # END $OP eq DELETE_CONFIRM
221 # called by delete_confirm, used to effectively confirm deletion of data in DB
222 } elsif ( $op eq 'delete_confirmed' ) {
223     if ( BudgetHasChildren( $budget_id ) ) {
224         # We should never be here, the interface does not provide this action.
225         die("Delete a fund with children is not possible");
226     }
227     my $rc = DelBudget($budget_id);
228     $op = 'list';
229 } elsif( $op eq 'add_validate' ) {
230     my @budgetusersid;
231     if (defined $budget_users_ids){
232         @budgetusersid = split(':', $budget_users_ids);
233     }
234
235     my $budget_modified = 0;
236     if (defined $budget_id) {
237         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
238             $staffflags)
239         ) {
240             ModBudget( $budget_hash );
241             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
242             $budget_modified = 1;
243         }
244         else {
245             $template->param(error_not_authorised_to_modify => 1);
246         }
247     } else {
248         $budget_hash->{budget_id} = AddBudget( $budget_hash );
249         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
250         $budget_modified = 1;
251     }
252
253     my $set_owner_to_children = $input->param('set_owner_to_children');
254     if ( $set_owner_to_children and $budget_modified ) {
255         C4::Budgets::SetOwnerToFundHierarchy( $budget_hash->{budget_id}, $budget_hash->{budget_owner_id} );
256     }
257     $op = 'list';
258 }
259
260 if ( $op eq 'list' ) {
261     my $branches = GetBranches();
262     $template->param(
263         budget_id => $budget_id,
264         %$period,
265     );
266
267     my @budgets = @{
268         GetBudgetHierarchy($$period{budget_period_id},
269             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
270     };
271
272     my $period_total = 0;
273     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
274
275         #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 ?
276
277     my @budgets_to_display;
278     foreach my $budget (@budgets) {
279         # PERMISSIONS
280         unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
281             $budget->{'budget_lock'} = 1;
282         }
283
284         # if a budget search doesn't match, next
285         if ($filter_budgetname) {
286             next
287               unless $budget->{budget_code} =~ m/$filter_budgetname/i
288                   || $budget->{budget_name} =~ m/$filter_budgetname/i;
289         }
290         if ($filter_budgetbranch ) {
291             next unless  $budget->{budget_branchcode} eq $filter_budgetbranch;
292         }
293
294 ## TOTALS
295         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered};
296         $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered};
297         # adds to total  - only if budget is a 'top-level' budget
298         unless ( defined $budget->{budget_parent_id} ) {
299             $period_alloc_total += $budget->{'budget_amount'};
300             $spent_total += $budget->{total_spent};
301             $ordered_total += $budget->{total_ordered};
302             $available_total += $budget->{total_remaining};
303         }
304
305 # if amount == 0 don't display...
306         delete $budget->{'budget_unalloc_sublevel'}
307             if (!defined $budget->{'budget_unalloc_sublevel'}
308             or $budget->{'budget_unalloc_sublevel'} == 0);
309
310         # Value of budget_spent equals 0 instead of undefined value
311         $budget->{budget_spent} = 0 unless defined($budget->{budget_spent});
312         $budget->{budget_ordered} = 0 unless defined($budget->{budget_ordered});
313
314         #Make a list of parents of the bugdet
315         my @budget_hierarchy;
316         push  @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} };
317         my $parent_id = $budget->{"budget_parent_id"};
318         while ($parent_id) {
319             my $parent = GetBudget($parent_id);
320             push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} };
321             $parent_id = $parent->{"budget_parent_id"};
322         }
323         push  @budget_hierarchy, { element_name => $period->{"budget_period_description"} };
324         @budget_hierarchy = reverse(@budget_hierarchy);
325
326         $budget->{budget_hierarchy} = \@budget_hierarchy;
327
328         $budget->{budget_has_children} = BudgetHasChildren( $budget->{budget_id} );
329         push @budgets_to_display, $budget;
330     }
331
332     my $budget_period_total = $period->{budget_period_total};
333
334     my $periods = GetBudgetPeriods();
335
336     $template->param(
337         op                     => 'list',
338         budgets                => \@budgets_to_display,
339         periods                => $periods,
340         budget_period_total    => $budget_period_total,
341         period_alloc_total     => $period_alloc_total,
342         spent_total            => $spent_total,
343         ordered_total          => $ordered_total,
344         available_total        => $available_total,
345         branchloop             => $branchloop,
346         filter_budgetname      => $filter_budgetname,
347     );
348
349 } #---- END list
350
351 output_html_with_http_headers $input, $cookie, $template->output;