Bug 13021: guarantor search - guarantor_search.tt is useless
[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     }
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         $labels{"$r->{budget_id}"} = $r->{budget_code};
141         push @values, $r->{budget_id};
142     }
143     push @values, '';
144     # if no buget_id is passed then its an add
145     my $budget_parent;
146     my $budget_parent_id;
147     if ($budget){
148         $budget_parent_id = $budget->{'budget_parent_id'} ;
149     }else{
150         $budget_parent_id = $input->param('budget_parent_id');
151     }
152     $budget_parent = GetBudget($budget_parent_id);
153
154     # build branches select
155     my $branches = GetBranches;
156     my @branchloop_select;
157     foreach my $thisbranch ( sort keys %$branches ) {
158         my %row = (
159             value      => $thisbranch,
160             branchname => $branches->{$thisbranch}->{'branchname'},
161         );
162         $row{selected} = 1 if $budget and $thisbranch eq $budget->{'budget_branchcode'};
163         push @branchloop_select, \%row;
164     }
165     
166     # populates the YUI planning button
167     my $categories = GetAuthorisedValueCategories();
168     my @auth_cats_loop1 = ();
169     foreach my $category (@$categories) {
170         my $entry = { category => $category,
171                         selected => ( $budget and $budget->{sort1_authcat} eq $category ? 1 : 0 ),
172                     };
173         push @auth_cats_loop1, $entry;
174     }
175     my @auth_cats_loop2 = ();
176     foreach my $category (@$categories) {
177         my $entry = { category => $category,
178                         selected => ( $budget and $budget->{sort2_authcat} eq $category ? 1 : 0 ),
179                     };
180         push @auth_cats_loop2, $entry;
181     }
182     $template->param(authorised_value_categories1 => \@auth_cats_loop1);
183     $template->param(authorised_value_categories2 => \@auth_cats_loop2);
184
185     if($budget->{'budget_permission'}){
186         my $budget_permission = "budget_perm_".$budget->{'budget_permission'};
187         $template->param($budget_permission => 1);
188     }
189
190     if ($budget) {
191         my @budgetusers = GetBudgetUsers($budget->{budget_id});
192         my @budgetusers_loop;
193         foreach my $borrowernumber (@budgetusers) {
194             my $member = C4::Members::GetMember(
195                 borrowernumber => $borrowernumber);
196             push @budgetusers_loop, {
197                 firstname => $member->{firstname},
198                 surname => $member->{surname},
199                 borrowernumber => $borrowernumber
200             };
201         }
202         $template->param(
203             budget_users => \@budgetusers_loop,
204             budget_users_ids => join ':', @budgetusers
205         );
206     }
207
208     # if no buget_id is passed then its an add
209     $template->param(
210         budget_has_children => BudgetHasChildren( $budget->{budget_id} ),
211         budget_parent_id                  => $budget_parent->{'budget_id'},
212         budget_parent_name                => $budget_parent->{'budget_name'},
213         branchloop_select         => \@branchloop_select,
214                 %$period,
215                 %$budget,
216     );
217                                                     # END $OP eq ADD_FORM
218 #---------------------- DEFAULT DISPLAY BELOW ---------------------
219
220 # called by default form, used to confirm deletion of data in DB
221 } elsif ($op eq 'delete_confirm') {
222
223     my $budget = GetBudget($budget_id);
224     $template->param(
225         budget_id     => $budget->{'budget_id'},
226         budget_code   => $budget->{'budget_code'},
227         budget_name   => $budget->{'budget_name'},
228         budget_amount => $budget->{'budget_amount'},
229     );
230                                                     # END $OP eq DELETE_CONFIRM
231 # called by delete_confirm, used to effectively confirm deletion of data in DB
232 } elsif ( $op eq 'delete_confirmed' ) {
233     if ( BudgetHasChildren( $budget_id ) ) {
234         # We should never be here, the interface does not provide this action.
235         die("Delete a fund with children is not possible");
236     }
237     my $rc = DelBudget($budget_id);
238     $op = 'list';
239 } elsif( $op eq 'add_validate' ) {
240     my @budgetusersid;
241     if (defined $budget_users_ids){
242         @budgetusersid = split(':', $budget_users_ids);
243     }
244
245     my $budget_modified = 0;
246     if (defined $budget_id) {
247         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
248             $staffflags)
249         ) {
250             ModBudget( $budget_hash );
251             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
252             $budget_modified = 1;
253         }
254         else {
255             $template->param(error_not_authorised_to_modify => 1);
256         }
257     } else {
258         $budget_hash->{budget_id} = AddBudget( $budget_hash );
259         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
260         $budget_modified = 1;
261     }
262
263     my $set_owner_to_children = $input->param('set_owner_to_children');
264     if ( $set_owner_to_children and $budget_modified ) {
265         C4::Budgets::SetOwnerToFundHierarchy( $budget_hash->{budget_id}, $budget_hash->{budget_owner_id} );
266     }
267     $op = 'list';
268 }
269
270 if ( $op eq 'list' ) {
271     my $branches = GetBranches();
272     $template->param(
273         budget_id => $budget_id,
274         %$period,
275     );
276
277     my @budgets = @{
278         GetBudgetHierarchy($$period{budget_period_id},
279             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
280     };
281
282     my $period_total = 0;
283     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
284
285         #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 ?
286
287     foreach my $budget (@budgets) {
288         # PERMISSIONS
289         unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
290             $budget->{'budget_lock'} = 1;
291         }
292
293         # if a budget search doesnt match, next
294         if ($filter_budgetname) {
295             next
296               unless $budget->{budget_code} =~ m/$filter_budgetname/i
297                   || $budget->{budget_name} =~ m/$filter_budgetname/i;
298         }
299         if ($filter_budgetbranch ) {
300             next unless  $budget->{budget_branchcode} eq $filter_budgetbranch;
301         }
302
303 ## TOTALS
304         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered};
305         $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered};
306         # adds to total  - only if budget is a 'top-level' budget
307         unless ( defined $budget->{budget_parent_id} ) {
308             $period_alloc_total += $budget->{'budget_amount'};
309             $spent_total += $budget->{total_spent};
310             $ordered_total += $budget->{total_ordered};
311             $available_total += $budget->{total_remaining};
312         }
313
314 # if amount == 0 dont display...
315         delete $budget->{'budget_unalloc_sublevel'}
316             if (!defined $budget->{'budget_unalloc_sublevel'}
317             or $budget->{'budget_unalloc_sublevel'} == 0);
318
319         # Value of budget_spent equals 0 instead of undefined value
320         $budget->{budget_spent} = 0 unless defined($budget->{budget_spent});
321         $budget->{budget_ordered} = 0 unless defined($budget->{budget_ordered});
322
323         #Make a list of parents of the bugdet
324         my @budget_hierarchy;
325         push  @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} };
326         my $parent_id = $budget->{"budget_parent_id"};
327         while ($parent_id) {
328             my $parent = GetBudget($parent_id);
329             push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} };
330             $parent_id = $parent->{"budget_parent_id"};
331         }
332         push  @budget_hierarchy, { element_name => $period->{"budget_period_description"} };
333         @budget_hierarchy = reverse(@budget_hierarchy);
334
335         $budget->{budget_hierarchy} = \@budget_hierarchy;
336
337         $budget->{budget_has_children} = BudgetHasChildren( $budget->{budget_id} );
338     }
339
340     my $budget_period_total = $period->{budget_period_total};
341
342     my $periods = GetBudgetPeriods();
343
344     $template->param(
345         op                     => 'list',
346         budgets                => \@budgets,
347         periods                => $periods,
348         budget_period_total    => $budget_period_total,
349         period_alloc_total     => $period_alloc_total,
350         spent_total            => $spent_total,
351         ordered_total          => $ordered_total,
352         available_total        => $available_total,
353         branchloop             => \@branchloop2,
354     );
355
356 } #---- END list
357
358 output_html_with_http_headers $input, $cookie, $template->output;