Bug 12979: Price formatting should only be defined at one place
[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;
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     my $rc = DelBudget($budget_id);
235     $op = 'list';
236 } elsif( $op eq 'add_validate' ) {
237     my @budgetusersid;
238     if (defined $budget_users_ids){
239         @budgetusersid = split(':', $budget_users_ids);
240     }
241
242     my $budget_modified = 0;
243     if (defined $budget_id) {
244         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
245             $staffflags)
246         ) {
247             ModBudget( $budget_hash );
248             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
249             $budget_modified = 1;
250         }
251         else {
252             $template->param(error_not_authorised_to_modify => 1);
253         }
254     } else {
255         $budget_hash->{budget_id} = AddBudget( $budget_hash );
256         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
257         $budget_modified = 1;
258     }
259
260     my $set_owner_to_children = $input->param('set_owner_to_children');
261     if ( $set_owner_to_children and $budget_modified ) {
262         C4::Budgets::SetOwnerToFundHierarchy( $budget_hash->{budget_id}, $budget_hash->{budget_owner_id} );
263     }
264     $op = 'list';
265 }
266
267 if ( $op eq 'list' ) {
268     my $branches = GetBranches();
269     $template->param(
270         budget_id => $budget_id,
271         %$period,
272     );
273
274     my @budgets = @{
275         GetBudgetHierarchy($$period{budget_period_id},
276             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
277     };
278
279     my $period_total = 0;
280     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
281
282         #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 ?
283
284     foreach my $budget (@budgets) {
285         # PERMISSIONS
286         unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
287             $budget->{'budget_lock'} = 1;
288         }
289
290         # if a budget search doesnt match, next
291         if ($filter_budgetname) {
292             next
293               unless $budget->{budget_code} =~ m/$filter_budgetname/i
294                   || $budget->{budget_name} =~ m/$filter_budgetname/i;
295         }
296         if ($filter_budgetbranch ) {
297             next unless  $budget->{budget_branchcode} eq $filter_budgetbranch;
298         }
299
300 ## TOTALS
301         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered};
302         $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered};
303         # adds to total  - only if budget is a 'top-level' budget
304         unless ( defined $budget->{budget_parent_id} ) {
305             $period_alloc_total += $budget->{'budget_amount'};
306             $spent_total += $budget->{total_spent};
307             $ordered_total += $budget->{total_ordered};
308             $available_total += $budget->{total_remaining};
309         }
310
311 # if amount == 0 dont display...
312         delete $budget->{'budget_unalloc_sublevel'}
313             if (!defined $budget->{'budget_unalloc_sublevel'}
314             or $budget->{'budget_unalloc_sublevel'} == 0);
315
316         # Value of budget_spent equals 0 instead of undefined value
317         $budget->{budget_spent} = 0 unless defined($budget->{budget_spent});
318         $budget->{budget_ordered} = 0 unless defined($budget->{budget_ordered});
319
320         #Make a list of parents of the bugdet
321         my @budget_hierarchy;
322         push  @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} };
323         my $parent_id = $budget->{"budget_parent_id"};
324         while ($parent_id) {
325             my $parent = GetBudget($parent_id);
326             push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} };
327             $parent_id = $parent->{"budget_parent_id"};
328         }
329         push  @budget_hierarchy, { element_name => $period->{"budget_period_description"} };
330         @budget_hierarchy = reverse(@budget_hierarchy);
331
332         $budget->{budget_hierarchy} = \@budget_hierarchy;
333     }
334
335     my $budget_period_total = $period->{budget_period_total};
336
337     my $periods = GetBudgetPeriods();
338
339     $template->param(
340         op                     => 'list',
341         budgets                => \@budgets,
342         periods                => $periods,
343         budget_period_total    => $budget_period_total,
344         period_alloc_total     => $period_alloc_total,
345         spent_total            => $spent_total,
346         ordered_total          => $ordered_total,
347         available_total        => $available_total,
348         branchloop             => \@branchloop2,
349     );
350
351 } #---- END list
352
353 output_html_with_http_headers $input, $cookie, $template->output;