Bug 11232: NORMARC facet definition and updated XSL file for DOM
[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 Koha::Database;
29 use C4::Auth qw/get_user_subpermissions/;
30 use C4::Branch; # GetBranches
31 use C4::Dates qw/format_date format_date_in_iso/;
32 use C4::Auth;
33 use C4::Acquisition;
34 use C4::Budgets;
35 use C4::Members;  # calls GetSortDetails()
36 use C4::Context;
37 use C4::Output;
38 use C4::Koha;
39 use C4::Debug;
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.tt",
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( symbol => $cur->{symbol},
56                   currency => $cur->{currency}
57                );
58
59 my $op = $input->param('op') || 'list';
60
61 # see if the user want to see all budgets or only owned ones by default
62 my $show_mine = $input->param('show_mine') // 1;
63
64 # IF USER DOESNT HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
65 if (not defined $template->{VARS}->{'CAN_user_acquisition_budget_add_del'}
66     and $op eq 'add_form')
67 {
68     $op = 'list';
69 }
70 my $num=FormatNumber;
71
72 # get only the columns of aqbudgets in budget_hash
73 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
74 my $budget_hash = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $input->param($_) )  : () } keys( %{$input->Vars()}) } ;
75
76 my $budget_id                 = $input->param('budget_id');
77 my $budget_period_id          = $input->param('budget_period_id');
78 my $budget_permission         = $input->param('budget_permission');
79 my $budget_users_ids          = $input->param('budget_users_ids');
80 my $filter_budgetbranch       = $input->param('filter_budgetbranch') // '';
81 my $filter_budgetname         = $input->param('filter_budgetname');
82
83
84 # ' ------- get periods stuff ------------------'
85 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
86 my $period;
87 if ( $budget_period_id ) {
88     $period = GetBudgetPeriod( $budget_period_id );
89 }
90
91 # ------- get periods stuff ------------------
92
93 # USED FOR PERMISSION COMPARISON LATER
94 my $borrower_id         = $template->{VARS}->{'USER_INFO'}[0]->{'borrowernumber'};
95 my $user                = GetMemberDetails($borrower_id);
96 my $user_branchcode     = $user->{'branchcode'};
97
98 $template->param(
99     show_mine   => $show_mine,
100     op  => $op,
101 );
102
103 my $budget;
104
105 my $branches = GetBranches($show_mine);
106 my @branchloop2;
107 foreach my $thisbranch (keys %$branches) {
108     my %row = (
109         value      => $thisbranch,
110         branchname => $branches->{$thisbranch}->{'branchname'},
111     );
112     $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
113     push @branchloop2, \%row;
114 }
115
116 $template->param(auth_cats_loop => GetBudgetAuthCats( $budget_period_id ))
117     if $budget_period_id;
118
119 # Used to create form to add or  modify a record
120 if ($op eq 'add_form') {
121 #### ------------------- ADD_FORM -------------------------
122     # if no buget_id is passed then its an add
123     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
124     my $dropbox_disabled;
125     if (defined $budget_id ) {    ### MOD
126         $budget = GetBudget($budget_id);
127         if (!CanUserModifyBudget($borrowernumber, $budget, $staffflags)) {
128             $template->param(error_not_authorised_to_modify => 1);
129             output_html_with_http_headers $input, $cookie, $template->output;
130             exit;
131         }
132         $dropbox_disabled = BudgetHasChildren($budget_id);
133         my $borrower = &GetMember( borrowernumber=>$budget->{budget_owner_id} );
134         $budget->{budget_owner_name} = ( $borrower ? $borrower->{'firstname'} . ' ' . $borrower->{'surname'} : '' );
135         $$budget{$_}= sprintf("%.2f", $budget->{$_}) for grep{ /amount|encumb|expend/ } keys %$budget;
136     }
137
138     # build budget hierarchy
139     my %labels;
140     my @values;
141     my $hier = GetBudgetHierarchy($$period{budget_period_id});
142     foreach my $r (@$hier) {
143         $r->{budget_code_indent} =~ s/ /\~/g;    #
144         $labels{"$r->{budget_id}"} = $r->{budget_code_indent};
145         push @values, $r->{budget_id};
146     }
147     push @values, '';
148     # if no buget_id is passed then its an add
149     my $budget_parent;
150     my $budget_parent_id;
151     if ($budget){
152         $budget_parent_id = $budget->{'budget_parent_id'} ;
153     }else{
154         $budget_parent_id = $input->param('budget_parent_id');
155     }
156     $budget_parent = GetBudget($budget_parent_id);
157
158     # build branches select
159     my $branches = GetBranches;
160     my @branchloop_select;
161     foreach my $thisbranch ( sort keys %$branches ) {
162         my %row = (
163             value      => $thisbranch,
164             branchname => $branches->{$thisbranch}->{'branchname'},
165         );
166         $row{selected} = 1 if $budget and $thisbranch eq $budget->{'budget_branchcode'};
167         push @branchloop_select, \%row;
168     }
169     
170     # populates the YUI planning button
171     my $categories = GetAuthorisedValueCategories();
172     my @auth_cats_loop1 = ();
173     foreach my $category (@$categories) {
174         my $entry = { category => $category,
175                         selected => ( $budget and $budget->{sort1_authcat} eq $category ? 1 : 0 ),
176                     };
177         push @auth_cats_loop1, $entry;
178     }
179     my @auth_cats_loop2 = ();
180     foreach my $category (@$categories) {
181         my $entry = { category => $category,
182                         selected => ( $budget and $budget->{sort2_authcat} eq $category ? 1 : 0 ),
183                     };
184         push @auth_cats_loop2, $entry;
185     }
186     $template->param(authorised_value_categories1 => \@auth_cats_loop1);
187     $template->param(authorised_value_categories2 => \@auth_cats_loop2);
188
189     if($budget->{'budget_permission'}){
190         my $budget_permission = "budget_perm_".$budget->{'budget_permission'};
191         $template->param($budget_permission => 1);
192     }
193
194     if ($budget) {
195         my @budgetusers = GetBudgetUsers($budget->{budget_id});
196         my @budgetusers_loop;
197         foreach my $borrowernumber (@budgetusers) {
198             my $member = C4::Members::GetMember(
199                 borrowernumber => $borrowernumber);
200             push @budgetusers_loop, {
201                 firstname => $member->{firstname},
202                 surname => $member->{surname},
203                 borrowernumber => $borrowernumber
204             };
205         }
206         $template->param(
207             budget_users => \@budgetusers_loop,
208             budget_users_ids => join ':', @budgetusers
209         );
210     }
211
212     # if no buget_id is passed then its an add
213     $template->param(
214         budget_parent_id                  => $budget_parent->{'budget_id'},
215         budget_parent_name                => $budget_parent->{'budget_name'},
216         branchloop_select         => \@branchloop_select,
217                 %$period,
218                 %$budget,
219     );
220                                                     # END $OP eq ADD_FORM
221 #---------------------- DEFAULT DISPLAY BELOW ---------------------
222
223 # called by default form, used to confirm deletion of data in DB
224 } elsif ($op eq 'delete_confirm') {
225
226     my $budget = GetBudget($budget_id);
227     $template->param(
228         budget_id     => $budget->{'budget_id'},
229         budget_code   => $budget->{'budget_code'},
230         budget_name   => $budget->{'budget_name'},
231         budget_amount => $num->format_price(  $budget->{'budget_amount'} ),
232     );
233                                                     # END $OP eq DELETE_CONFIRM
234 # called by delete_confirm, used to effectively confirm deletion of data in DB
235 } elsif ( $op eq 'delete_confirmed' ) {
236     my $rc = DelBudget($budget_id);
237     $op = 'list';
238 } elsif( $op eq 'add_validate' ) {
239     my @budgetusersid;
240     if (defined $budget_users_ids){
241         @budgetusersid = split(':', $budget_users_ids);
242     }
243
244     if (defined $budget_id) {
245         if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id},
246             $staffflags)
247         ) {
248             ModBudget( $budget_hash );
249             ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
250         }
251         else {
252             $template->param(error_not_authorised_to_modify => 1);
253         }
254     } else {
255         AddBudget( $budget_hash );
256         ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid);
257     }
258     $op = 'list';
259 }
260
261 if ( $op eq 'list' ) {
262     my $branches = GetBranches();
263     $template->param(
264         budget_id => $budget_id,
265         %$period,
266     );
267
268     my @budgets = @{
269         GetBudgetHierarchy($$period{budget_period_id},
270             C4::Context->userenv->{branchcode}, $show_mine ? $borrower_id : '')
271     };
272
273     my $period_total = 0;
274     my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0);
275
276         #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 ?
277
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 doesnt 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         if ($budget->{depth} == 0) {
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 dont display...
306         delete $budget->{'budget_unalloc_sublevel'}
307             if (!defined $budget->{'budget_unalloc_sublevel'}
308             or $budget->{'budget_unalloc_sublevel'} == 0);
309
310         for (grep {/total_spent|budget_spent|total_ordered|budget_ordered|budget_amount/} keys %$budget){
311             $budget->{$_}               = $num->format_price( $budget->{$_} ) if defined($budget->{$_})
312                 }
313         for (qw/budget_remaining total_remaining/) {
314             if (defined $budget->{$_}) {
315                 $budget->{$_.'_display'} = $num->format_price($budget->{$_});
316             }
317         }
318
319         # Value of budget_spent equals 0 instead of undefined value
320         $budget->{"budget_spent"} = $num->format_price(0) unless defined($budget->{"budget_spent"});
321         $budget->{budget_ordered} = $num->format_price(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
338     my $budget_period_total = $period->{budget_period_total};
339
340     foreach ($budget_period_total, $period_alloc_total, $spent_total, $ordered_total, $available_total) {
341         $_ = $num->format_price($_);
342     }
343
344     my $periods = GetBudgetPeriods();
345
346     $template->param(
347         op                     => 'list',
348         budgets                => \@budgets,
349         periods                => $periods,
350         budget_period_total    => $budget_period_total,
351         period_alloc_total     => $period_alloc_total,
352         spent_total            => $spent_total,
353         ordered_total          => $ordered_total,
354         available_total        => $available_total,
355         branchloop             => \@branchloop2,
356     );
357
358 } #---- END list
359
360 output_html_with_http_headers $input, $cookie, $template->output;