budgfixing budgets & planning and code cleaning
[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 with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use strict;
23 use CGI;
24 use List::Util qw/min/;
25 use Number::Format qw(format_price);
26
27 use C4::Auth qw/get_user_subpermissions/;
28 use C4::Branch; # GetBranches
29 use C4::Dates qw/format_date format_date_in_iso/;
30 use C4::Auth;
31 use C4::Acquisition;
32 use C4::Budgets;   #
33 use C4::Members;  # calls GetSortDetails()
34 use C4::Context;
35 use C4::Output;
36 use C4::Koha;
37 use C4::Debug;
38 #use POSIX qw(locale_h);
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.tmpl",
45         query           => $input,
46         type            => "intranet",
47         authnotrequired => 0,
48         flagsrequired   => { acquisition => 'budget_manage' },
49         debug           => 0,
50     }
51 );
52
53 my $op = $input->param('op');
54
55 # see if the user want to see all budgets or only owned ones
56 my $show_mine    = 1; #SHOW BY DEFAULT
57 my $show         = $input->param('show'); # SET TO 1, BY A FORM SUMBIT
58 $show_mine       = $input->param('show_mine') if $show == 1;
59
60 # IF USER DOESNT HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
61 if  (  not defined $template->{param_map}->{'CAN_user_acquisition_budget_add_del'}  &&  $op ==  'add_form'  )   {
62     $op = '';
63 }
64
65 my $cur  =  GetCurrency;
66 my $cur_format = C4::Context->preference("CurrencyFormat");
67 my $num;
68
69 if ( $cur_format eq 'FR' ) {
70     $num = new Number::Format(
71         'decimal_fill'      => '2',
72         'decimal_point'     => ',',
73         'int_curr_symbol'   => '',
74         'mon_thousands_sep' => ' ',
75         'thousands_sep'     => ' ',
76         'mon_decimal_point' => ','
77     );
78 } else {  # US by default..
79     $num = new Number::Format(
80         'int_curr_symbol'   => '',
81         'mon_thousands_sep' => ',',
82         'mon_decimal_point' => '.'
83     );
84 }
85
86 my $script_name               = "/cgi-bin/koha/admin/aqbudgets.pl";
87 my $budget_id                 = $input->param('budget_id');
88 my $budget_code               = $input->param('budget_code');
89 my $budget_name               = $input->param('budget_name');
90 my $budget_amount             = $input->param('budget_amount');
91 my $budget_amount_sublevel    = $input->param('budget_amount_sublevel');
92 my $budget_encumb             = $input->param('budget_encumb');
93 my $budget_expend             = $input->param('budget_expend');
94 my $budget_notes              = $input->param('budget_notes');
95 my $sort1_authcat             = $input->param('sort1_authcat');
96 my $sort2_authcat             = $input->param('sort2_authcat');
97 my $budget_description        = $input->param('budget_description');
98 my $budget_branchcode         = $input->param('budget_branchcode');
99 my $budget_owner_id           = $input->param('budget_owner_id');
100 my $budget_parent_id          = $input->param('budget_parent_id');
101 my $budget_permission         = $input->param('budget_permission');
102 my $budget_period_dropbox     = $input->param('budget_period_dropbox');
103 my $filter_budgetname         = $input->param('filter_budgetname');
104 my $filter_budgetbranch       = $input->param('filter_budgetbranch');
105
106 # ' ------- get periods stuff ------------------'
107 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
108 my $budget_period_id  = $input->param('budget_period_id');
109 my $period = GetBudgetPeriod($budget_period_id);
110 my $budget_period_id          = $period->{'budget_period_id'};
111 my $budget_period_locked      = $period->{'budget_period_locked'};
112 my $budget_period_description = $period->{'budget_period_description'};
113 my $budget_period_total       = $period->{'budget_period_total'};
114
115 $template->param(
116     budget_period_id          => $budget_period_id,
117     budget_period_locked      => $budget_period_locked,
118     budget_period_description => $budget_period_description,
119 );
120 # ------- get periods stuff ------------------
121
122 # USED FOR PERMISSION COMPARISON LATER
123 my $borrower_id         = $template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'};
124 my $user                = GetMemberDetails($borrower_id);
125 my $user_branchcode     = $user->{'branchcode'};
126
127 $template->param(
128     action      => $script_name,
129     script_name => $script_name,
130     show_mine   => $show_mine,
131     $op || else => 1,
132 );
133
134
135 # retrieve branches
136 my ( $budget, $period, $query, $sth );
137
138 my $branches = GetBranches;
139 my @branchloop2;
140 foreach my $thisbranch (keys %$branches) {
141     my %row = (
142         value      => $thisbranch,
143         branchname => $branches->{$thisbranch}->{'branchname'},
144     );
145     $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
146     push @branchloop2, \%row;
147 }
148
149 $template->param(auth_cats_loop => GetBudgetAuthCats($budget_period_id) );
150
151 # Used to create form to add or  modify a record
152 if ($op eq 'add_form') {
153 #### ------------------- ADD_FORM -------------------------
154
155     # if no buget_id is passed then its an add
156     #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
157     my $dropbox_disabled;
158     if ( defined $budget_id ) {    ### MOD
159         $budget           = GetBudget($budget_id);
160         $dropbox_disabled = BudgetHasChildren($budget_id);
161         my $borrower = &GetMember( $budget->{budget_owner_id} );
162         $budget->{budget_owner_name} = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
163     }
164
165     # build budget hierarchy
166     my %labels;
167     my @values;
168     my $hier = GetBudgetHierarchy($budget_period_id);
169     foreach my $r (@$hier) {
170         $r->{budget_code_indent} =~ s/ /\~/g;    #
171         $labels{"$r->{budget_id}"} = $r->{budget_code_indent};
172         push @values, $r->{budget_id};
173     }
174     push @values, '';
175     # if no buget_id is passed then its an add
176     my $budget_parent_dropbox;
177     my $budget_parent_id = $budget->{'budget_parent_id'} if $budget;
178     $budget_parent_dropbox = CGI::scrolling_list(
179         -name    => 'budget_parent_id',
180         -values  => \@values,
181         -default => $budget_parent_id ? $budget_parent_id : undef,
182         -size    => 10,
183         -style   => "min-width:100px;",
184         -labels  => \%labels,
185     );
186
187     # build branches select
188     my $branches = GetBranches;
189     my @branchloop_select;
190     foreach my $thisbranch ( keys %$branches ) {
191         my %row = (
192             value      => $thisbranch,
193             branchname => $branches->{$thisbranch}->{'branchname'},
194         );
195         $row{selected} = 1 if $thisbranch eq $budget->{'budget_branchcode'};
196         push @branchloop_select, \%row;
197     }
198     
199     # populates the YUI planning button
200     my $categories = GetAuthorisedValueCategories();
201     my @auth_cats_loop1 = ();
202     foreach my $category (@$categories) {
203         my $entry = { category => $category,
204                         selected => $budget->{sort1_authcat} eq $category ?1:0,
205                     };
206         push @auth_cats_loop1, $entry;
207     }
208     my @auth_cats_loop2 = ();
209     foreach my $category (@$categories) {
210         my $entry = { category => $category,
211                         selected => $budget->{sort2_authcat} eq $category ?1:0,
212                     };
213         push @auth_cats_loop2, $entry;
214     }
215     $template->param(authorised_value_categories1 => \@auth_cats_loop1);
216     $template->param(authorised_value_categories2 => \@auth_cats_loop2);
217
218     my $budget_perm_dropbox =
219     GetBudgetPermDropbox($budget->{'budget_permission'});
220     
221     # if no buget_id is passed then its an add
222     $template->param(
223         add_form                  => 1,
224         dateformat                => C4::Dates->new()->visual(),
225         budget_id                 => $budget->{'budget_id'},
226         budget_parent_id          => $budget->{'budget_parent_id'},
227         budget_dropbox     => $budget_dropbox,
228         budget_perm_dropbox       => $budget_perm_dropbox,
229         budget_code               => $budget->{'budget_code'},
230         budget_code_indent        => $budget->{'budget_code_indent'},
231         budget_name               => $budget->{'budget_name'},
232         budget_branchcode         => $budget->{'budget_branchcode'},
233         budget_amount             => sprintf("%.2f", $budget->{'budget_amount'}),
234         budget_amount_sublevel    => sprintf("%.2f", $budget->{'budget_amount_sublevel'}),
235         budget_encumb             => $budget->{'budget_encumb'},
236         budget_expend             => $budget->{'budget_expend'},
237         budget_notes              => $budget->{'budget_notes'},
238         budget_description        => $budget->{'budget_description'},
239         budget_owner_id           => $budget->{'budget_owner_id'},
240         budget_owner_name         => $budget->{'budget_owner_name'},
241         budget_permission         => $budget->{'budget_permission'},
242         budget_period_id          => $budget_period_id,
243         budget_period_description => $budget_period_description,
244         branchloop_select         => \@branchloop_select,
245     );
246                                                     # END $OP eq ADD_FORM
247 #---------------------- DEFAULT DISPLAY BELOW ---------------------
248
249 # called by default form, used to confirm deletion of data in DB
250 } elsif ($op eq 'delete_confirm') {
251
252     my $budget = GetBudget($budget_id);
253     $template->param(
254         budget_id     => $budget->{'budget_id'},
255         budget_code   => $budget->{'budget_code'},
256         budget_name   => $budget->{'budget_name'},
257         budget_amount => $num->format_price(  $budget->{'budget_amount'} ),
258     );
259                                                     # END $OP eq DELETE_CONFIRM
260 # called by delete_confirm, used to effectively confirm deletion of data in DB
261 }  else {
262     if ( $op eq 'delete_confirmed' ) {
263         my $rc = DelBudget($budget_id);
264     }
265     if ( $op eq 'add_validate' ) {
266         my %budget_hash = (
267             budget_id              => $budget_id,
268             budget_parent_id       => $budget_parent_id,
269             budget_period_id       => $budget_period_id,
270             budget_code            => $budget_code,
271             budget_name            => $budget_name,
272             budget_branchcode      => $budget_branchcode,
273             budget_amount          => $budget_amount,
274             budget_amount_sublevel => $budget_amount_sublevel,
275             budget_encumb          => $budget_encumb,
276             budget_expend          => $budget_expend,
277             budget_notes           => $budget_notes,
278             sort1_authcat          => $sort1_authcat,
279             sort2_authcat          => $sort2_authcat,
280             budget_description     => $budget_description,
281             budget_owner_id        => $budget_owner_id,
282             budget_permission      => $budget_permission,
283         );
284         if ( defined $budget_id ) {
285             ModBudget( \%budget_hash );
286         } else {
287             AddBudget( \%budget_hash );
288         }
289     }
290     my $branches = GetBranches();
291     my $budget_period_dropbox = GetBudgetPeriodsDropbox($budget_period_id );
292     $template->param(
293         budget_period_dropbox     => $budget_period_dropbox,
294         budget_id                 => $budget_id,
295         budget_period_startdate   => $period->{'budget_period_startdate'},
296         budget_period_enddate     => $period->{'budget_period_enddate'},
297     );
298     my $moo = GetBudgetHierarchy($budget_period_id, $template->{param_map}->{'USER_INFO'}[0]->{'branchcode'}, $show_mine?$borrower_id:'');
299     my @budgets = @$moo; #FIXME
300
301     my $toggle = 0;
302     my @loop;
303     my $period_total = 0;
304     my ( $period_alloc_total, $base_alloc_total, $sub_alloc_total, $base_spent_total, $base_remaining_total );
305
306     foreach my $budget (@budgets) {
307
308         # PERMISSIONS
309         unless($staffflags->{'superlibrarian'}   == 1 ) {
310             #IF NO PERMS, THEN DISABLE EDIT/DELETE
311             unless ( $template->{param_map}->{'CAN_user_acquisition_budget_modify'} ) {
312                 $budget->{'budget_lock'} = 1;
313             }
314             # check budget permission
315             if ( $budget_period_locked == 1 ) {
316                 $budget->{'budget_lock'} = 1;
317
318             } elsif ( $budget->{budget_permission} == 1 ) {
319
320                 if ( $borrower_id != $budget->{'budget_owner_id'} ) {
321                     $budget->{'budget_lock'} = 1;
322                 }
323                 # check parent perms too
324                 my $parents_perm = 0;
325                 if ( $budget->{depth} > 0 ) {
326                     $parents_perm = CheckBudgetParentPerm( $budget, $borrower_id );
327                     delete $budget->{'budget_lock'} if $parents_perm == '1';
328                 }
329             } elsif ( $budget->{budget_permission} == 2 ) {
330
331                 $budget->{'budget_lock'} = 1 if $user_branchcode ne $budget->{budget_branchcode};
332             }
333         }    # ...SUPER_LIB END
334
335         # if a budget search doesnt match, next
336         if ($filter_budgetname ) {
337             next unless  $budget->{budget_code}  =~ m/$filter_budgetname/  ||
338             $budget->{name}  =~ m/$filter_budgetname/ ;
339         }
340         if ($filter_budgetbranch ) {
341             next unless  $budget->{budget_branchcode}  =~ m/$filter_budgetbranch/;
342         }
343
344 ## TOTALS
345         # adds to total  - only if budget is a 'top-level' budget
346         $period_alloc_total += $budget->{'budget_amount_total'} if $budget->{'depth'} == 0;
347         $base_alloc_total += $budget->{'budget_amount'};
348         $sub_alloc_total  += $budget->{'budget_amount_sublevel'};
349         $base_spent_total += $budget->{'budget_spent'};
350         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'};
351         $base_remaining_total += $budget->{'budget_remaining'};
352
353 # if amount == 0 dont display...
354         delete  $budget->{'budget_unalloc_sublevel'} if  $budget->{'budget_unalloc_sublevel'} == 0 ;
355         delete  $budget->{'budget_amount_sublevel'} if  $budget->{'budget_amount_sublevel'} == 0 ;
356
357         $budget->{'remaining_pos'} = 1 if $budget->{'budget_remaining'} > 0;
358         $budget->{'remaining_neg'} = 1 if $budget->{'budget_remaining'} < 0;
359         $budget->{'budget_amount'}           = $num->format_price( $budget->{'budget_amount'} );
360         $budget->{'budget_spent'}            = $num->format_price( $budget->{'budget_spent'} );
361         $budget->{'budget_remaining'}        = $num->format_price( $budget->{'budget_remaining'} );
362         $budget->{'budget_amount_total'}     = $num->format_price( $budget->{'budget_amount_total'} );
363         $budget->{'budget_amount_sublevel'}  = $num->format_price( $budget->{'budget_amount_sublevel'} ) if defined $budget->{'budget_amount_sublevel'};
364         $budget->{'budget_unalloc_sublevel'} = $num->format_price( $budget->{'budget_unalloc_sublevel'} ) if defined $budget->{'budget_unalloc_sublevel'};
365
366         my $borrower = &GetMember( $budget->{budget_owner_id} );
367         $budget->{budget_owner_name}     = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
368         $budget->{budget_borrowernumber} = $borrower->{'borrowernumber'};
369
370         push( @loop, {  %{$budget},
371                         toggle      => $toggle++%2,
372                         branchname  => $branches->{ $budget->{branchcode} }->{branchname},
373                         startdate   => format_date($budget->{startdate}),
374                         enddate     => format_date($budget->{enddate}),
375                     }
376         );
377     }
378
379     $template->param(
380         else                   => 1,
381         budget                 => \@loop,
382         budget_period_total    => $num->format_price($budget_period_total),
383         period_alloc_total     => $num->format_price($period_alloc_total),
384         base_alloc_total       => $num->format_price($base_alloc_total),
385         sub_alloc_total        => $num->format_price($sub_alloc_total),
386         base_spent_total       => $num->format_price($base_spent_total),
387         base_remaining_total   => $num->format_price($base_remaining_total),
388         period_remaining_total => $num->format_price( $period_alloc_total - $base_alloc_total ),
389         branchloop             => \@branchloop2,
390         cur                    => $cur->{symbol},
391         cur_format             => $cur_format,
392     );
393
394 } #---- END $OP eq DEFAULT
395
396 output_html_with_http_headers $input, $cookie, $template->output;