Bug 9811: Patron search improvement
[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 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
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') // 1;
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 my $num=FormatNumber;
70
71 my $budget_hash               = $input->Vars;
72 my $budget_id                 = $$budget_hash{budget_id};
73 my $budget_period_id          = $input->param('budget_period_id');
74 my $budget_permission         = $input->param('budget_permission');
75 my $filter_budgetbranch       = $input->param('filter_budgetbranch') // '';
76 my $filter_budgetname         = $input->param('filter_budgetname');
77 #filtering non budget keys
78 delete $$budget_hash{$_} foreach grep {/filter|^op$|show/} keys %$budget_hash;
79
80 # ' ------- get periods stuff ------------------'
81 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
82 my $period;
83 if ( $budget_period_id ) {
84     $period = GetBudgetPeriod( $budget_period_id );
85 }
86
87 # ------- get periods stuff ------------------
88
89 # USED FOR PERMISSION COMPARISON LATER
90 my $borrower_id         = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
91 my $user                = GetMemberDetails($borrower_id);
92 my $user_branchcode     = $user->{'branchcode'};
93
94 $template->param(
95     show_mine   => $show_mine,
96     op  => $op,
97 );
98
99 # retrieve branches
100 my ( $budget, );
101
102 my $branches = GetBranches($show_mine);
103 my @branchloop2;
104 foreach my $thisbranch (keys %$branches) {
105     my %row = (
106         value      => $thisbranch,
107         branchname => $branches->{$thisbranch}->{'branchname'},
108     );
109     $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
110     push @branchloop2, \%row;
111 }
112
113 $template->param(auth_cats_loop => GetBudgetAuthCats( $budget_period_id ))
114     if $budget_period_id;
115
116 # Used to create form to add or  modify a record
117 if ($op eq 'add_form') {
118 #### ------------------- ADD_FORM -------------------------
119     # if no buget_id is passed then its an add
120     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
121     my $dropbox_disabled;
122     if (defined $budget_id ) {    ### MOD
123         $budget = GetBudget($budget_id);
124         if (!CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
125             $template->param(error_not_authorised_to_modify => 1);
126             output_html_with_http_headers $input, $cookie, $template->output;
127             exit;
128         }
129         $dropbox_disabled = BudgetHasChildren($budget_id);
130         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
131         $budget->{budget_owner_name} = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
132         $$budget{$_}= sprintf("%.2f", $budget->{$_}) for grep{ /amount|encumb|expend/ } keys %$budget;
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         $r->{budget_code_indent} =~ s/ /\~/g;    #
141         $labels{"$r->{budget_id}"} = $r->{budget_code_indent};
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 $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->{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->{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_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 => $num->format_price(  $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     my $rc = DelBudget($budget_id);
234     $op = 'list';
235 } elsif( $op eq 'add_validate' ) {
236     my @budgetusersid;
237     if (defined $$budget_hash{'budget_users_ids'}){
238         @budgetusersid = split(':', $budget_hash->{'budget_users_ids'});
239     }
240
241     if ( defined $$budget_hash{budget_id} ) {
242         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
243             $staffflags)
244         ) {
245             ModBudget( $budget_hash );
246             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
247         }
248         else {
249             $template->param(error_not_authorised_to_modify => 1);
250         }
251     } else {
252         AddBudget( $budget_hash );
253         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
254     }
255     $op = 'list';
256 }
257
258 if ( $op eq 'list' ) {
259     my $branches = GetBranches();
260     $template->param(
261         budget_id => $budget_id,
262         %$period,
263     );
264
265     my @budgets = @{
266         GetBudgetHierarchy($$period{budget_period_id},
267             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
268     };
269
270     my $period_total = 0;
271     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
272
273         #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 ?
274
275     foreach my $budget (@budgets) {
276         # PERMISSIONS
277         unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
278             $budget->{'budget_lock'} = 1;
279         }
280
281         # if a budget search doesnt match, next
282         if ($filter_budgetname) {
283             next
284               unless $budget->{budget_code} =~ m/$filter_budgetname/i
285                   || $budget->{budget_name} =~ m/$filter_budgetname/i;
286         }
287         if ($filter_budgetbranch ) {
288             next unless  $budget->{budget_branchcode} eq $filter_budgetbranch;
289         }
290
291 ## TOTALS
292         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered};
293         $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered};
294         # adds to total  - only if budget is a 'top-level' budget
295         if ($budget->{depth} == 0) {
296             $period_alloc_total += $budget->{'budget_amount'};
297             $spent_total += $budget->{total_spent};
298             $ordered_total += $budget->{total_ordered};
299             $available_total += $budget->{total_remaining};
300         }
301
302 # if amount == 0 dont display...
303         delete $budget->{'budget_unalloc_sublevel'}
304             if (!defined $budget->{'budget_unalloc_sublevel'}
305             or $budget->{'budget_unalloc_sublevel'} == 0);
306
307         for (grep {/total_spent|budget_spent|total_ordered|budget_ordered|budget_amount/} keys %$budget){
308             $budget->{$_}               = $num->format_price( $budget->{$_} ) if defined($budget->{$_})
309                 }
310         for (qw/budget_remaining total_remaining/) {
311             if (defined $budget->{$_}) {
312                 $budget->{$_.'_display'} = $num->format_price($budget->{$_});
313             }
314         }
315
316         # Value of budget_spent equals 0 instead of undefined value
317         $budget->{"budget_spent"} = $num->format_price(0) unless defined($budget->{"budget_spent"});
318         $budget->{budget_ordered} = $num->format_price(0) unless defined($budget->{"budget_ordered"});
319
320         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
321         $budget->{"budget_owner_name"}     = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
322         $budget->{"budget_borrowernumber"} = $borrower->{'borrowernumber'};
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->{branchname} = $branches->{ $budget->{branchcode} }->{branchname};
337         $budget->{budget_hierarchy} = \@budget_hierarchy;
338     }
339
340     my $budget_period_total = $period->{budget_period_total};
341
342     foreach ($budget_period_total, $period_alloc_total, $spent_total, $ordered_total, $available_total) {
343         $_ = $num->format_price($_);
344     }
345
346     my $periods = GetBudgetPeriods();
347
348     $template->param(
349         op                     => 'list',
350         budgets                => \@budgets,
351         periods                => $periods,
352         budget_period_total    => $budget_period_total,
353         period_alloc_total     => $period_alloc_total,
354         spent_total            => $spent_total,
355         ordered_total          => $ordered_total,
356         available_total        => $available_total,
357         branchloop             => \@branchloop2,
358     );
359
360 } #---- END list
361
362 output_html_with_http_headers $input, $cookie, $template->output;