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