Budget management
[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;   #  1ST ADD
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
61 # IF USER DOESNT HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW...
62 if  (  not defined $template->{param_map}->{'CAN_user_acquisition_budget_add_del'}  &&  $op ==  'add_form'  )   {
63     $op = '';
64 }
65
66 my  $count  = GetPeriodsCount();
67 $template->param( period_button_only => 1 ) if $count == 0 ;
68 my $cur  =  GetCurrency;
69 my $cur_format = C4::Context->preference("CurrencyFormat");
70 my $num;
71
72 =c
73 # TODO: at some stage this currency handling should be done properly
74 with locales and POSIX.pm - and a proper 'locales' lookup and syspref
75
76     setlocale( LC_MONETARY , "french");
77     my $num = new Number::Format();
78     my $formatted_number =  $num->format_price('123456789.123'):
79
80 =cut
81
82 if ( $cur_format eq 'FR' ) {
83     $num = new Number::Format(
84         'decimal_fill'      => '2',
85         'decimal_point'     => ',',
86         'int_curr_symbol'   => '',
87         'mon_thousands_sep' => ' ',
88         'thousands_sep'     => ' ',
89         'mon_decimal_point' => ','
90     );
91 } else {  # US by default..
92     $num = new Number::Format(
93         'int_curr_symbol'   => '',
94         'mon_thousands_sep' => ',',
95         'mon_decimal_point' => '.'
96     );
97 }
98
99 # ' ------- get periods stuff ------------------'
100 # IF PERIODID IS DEFINED,  GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT
101 my $budget_period_id  = $input->param('budget_period_id');
102 my $period = GetBudgetPeriod($budget_period_id);
103
104 # authcats_loop populates the YUI planning button
105 my @auth_cats_loop  = GetBudgetAuthCats();
106
107 my $budget_period_id          = $period->{'budget_period_id'};
108 my $budget_period_locked      = $period->{'budget_period_locked'};
109 my $budget_period_description = $period->{'budget_period_description'};
110 my $budget_period_total       = $period->{'budget_period_total'};
111
112 $template->param(
113     budget_period_id          => $budget_period_id,
114     budget_period_locked      => $budget_period_locked,
115     budget_period_description => $budget_period_description,
116     auth_cats_loop            => \@auth_cats_loop,
117 );
118 # ------- get periods stuff ------------------
119
120 my $script_name               = "/cgi-bin/koha/admin/aqbudgets.pl";
121 my $budget_id                 = $input->param('budget_id');
122 my $budget_code               = $input->param('budget_code');
123 my $budget_name               = $input->param('budget_name');
124 my $budget_amount             = $input->param('budget_amount');
125 my $budget_amount_sublevel    = $input->param('budget_amount_sublevel');
126 my $budget_encumb             = $input->param('budget_encumb');
127 my $budget_expend             = $input->param('budget_expend');
128 my $budget_notes              = $input->param('budget_notes');
129 my $sort1_authcat             = $input->param('sort1_authcat');
130 my $sort2_authcat             = $input->param('sort2_authcat');
131 my $budget_description        = $input->param('budget_description');
132 my $budget_branchcode         = $input->param('budget_branchcode');
133 my $budget_owner_id           = $input->param('budget_owner_id');
134 my $budget_parent_id          = $input->param('budget_parent_id');
135 my $budget_permission         = $input->param('budget_permission');
136 my $budget_period_dropbox     = $input->param('budget_period_dropbox');
137 my $filter_budgetname         = $input->param('filter_budgetname');
138 my $filter_budgetbranch       = $input->param('filter_budgetbranch');
139
140 my $pagesize = 20; # del
141
142 # USED FOR PERMISSION COMPARSION LATER
143 my $borrower_id         = $template->{param_map}->{'USER_INFO'}[0]->{'borrowernumber'};
144 my $user                = GetMemberDetails($borrower_id);
145 my $user_branchcode     = $user->{'branchcode'};
146
147 $template->param(
148     action      => $script_name,
149     script_name => $script_name,
150     show_mine   => $show_mine,
151     $op || else => 1,
152 );
153
154 my $sthtemp = $dbh->prepare("Select flags, branchcode from borrowers where borrowernumber = ?");
155 $sthtemp->execute($borrowernumber);
156 my ( $flags, $homebranch ) = $sthtemp->fetchrow;
157
158 my ( $budget, $period, $query, $sth );
159
160 my $branches = GetBranches;
161 my @branchloop2;
162 foreach my $thisbranch (keys %$branches) {
163         my %row = (
164                 value      => $thisbranch,
165                 branchname => $branches->{$thisbranch}->{'branchname'},
166         );
167         $row{selected} = 1 if $thisbranch eq $filter_budgetbranch;
168         push @branchloop2, \%row;
169 }
170
171 #$template->param(
172 #       budget_id             => $budget->{'budget_id'}
173 #);
174
175 # Used to create form to add or  modify a record
176 if ($op eq 'add_form') {
177 #### ------------------- ADD_FORM -------------------------
178
179 #---- if primkey exists, it's a modify action, so read values to modify...
180 #  pass the period_id to build the dropbox - because we only want to show  budgets from this period
181
182     my $dropbox_disabled;
183     if ( defined $budget_id ) {    ### MOD
184         $budget           = GetBudget($budget_id);
185         $dropbox_disabled = BudgetHasChildren($budget_id);
186         my $borrower = &GetMember( $budget->{budget_owner_id} );
187         $budget->{budget_owner_name} = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
188     }
189
190     my $sort1_authcat_dropbox = GetAuthcatDropbox( 'sort1_authcat',  $budget->{'sort1_authcat'} );
191     my $sort2_authcat_dropbox = GetAuthcatDropbox( 'sort2_authcat',  $budget->{'sort2_authcat'} );
192     
193     my %labels;
194     my @values;
195     my $hier = GetBudgetHierarchy($budget_period_id);
196     foreach my $r (@$hier) {
197         $r->{budget_code_indent} =~ s/ /\~/g;    #
198         $labels{"$r->{budget_id}"} = $r->{budget_code_indent};
199         push @values, $r->{budget_id};
200     }
201     push @values, '';
202     # if no buget_id is passed then its an add
203     my $budget_dropbox;
204     my $budget_parent_id = $budget->{'budget_parent_id'} if $budget;
205     $budget_dropbox = CGI::scrolling_list(
206         -name    => 'budget_parent_id',
207         -values  => \@values,
208         -default => $budget_parent_id ? $budget_parent_id : undef,
209         -size    => 10,
210         -style   => "min-width:100px;",
211         -labels  => \%labels,
212     );
213     my $budget_parent_dropbox =~ s/\~/ /g;  #
214
215     my $branches = GetBranches;
216     my @branchloop_select;
217     foreach my $thisbranch ( keys %$branches ) {
218         my %row = (
219             value      => $thisbranch,
220             branchname => $branches->{$thisbranch}->{'branchname'},
221         );
222         $row{selected} = 1 if $thisbranch eq $budget->{'budget_branchcode'};
223         push @branchloop_select, \%row;
224     }
225
226 #       $period                    = GetBudgetPeriod($budget->{'budget_period_id'});
227 #       $budget_period_description = $period->{'budget_period_description'};
228
229         my $budget_perm_dropbox =
230           GetBudgetPermDropbox($budget->{'budget_permission'});
231
232         # if no buget_id is passed then its an add
233         $template->param(
234           add_form                  => 1,
235           dateformat                => C4::Dates->new()->visual(),
236           budget_id                 => $budget->{'budget_id'},
237           budget_parent_id          => $budget->{'budget_parent_id'},
238           budget_parent_dropbox     => $budget_parent_dropbox,
239           sort1_authcat_dropbox     => $sort1_authcat_dropbox,
240           sort2_authcat_dropbox     => $sort2_authcat_dropbox,
241           budget_perm_dropbox       => $budget_perm_dropbox,
242           budget_code               => $budget->{'budget_code'},
243           budget_code_indent        => $budget->{'budget_code_indent'},
244           budget_name               => $budget->{'budget_name'},
245           budget_branchcode         => $budget->{'budget_branchcode'},
246           budget_amount             => sprintf("%.2f", $budget->{'budget_amount'}),
247           budget_amount_sublevel    => sprintf("%.2f", $budget->{'budget_amount_sublevel'}),
248           budget_encumb             => $budget->{'budget_encumb'},
249           budget_expend             => $budget->{'budget_expend'},
250           budget_notes              => $budget->{'budget_notes'},
251           budget_description        => $budget->{'budget_description'},
252           budget_owner_id           => $budget->{'budget_owner_id'},
253           budget_owner_name         => $budget->{'budget_owner_name'},
254           budget_permission         => $budget->{'budget_permission'},
255           budget_period_id          => $budget_period_id,
256           budget_period_description => $budget_period_description,
257           branchloop_select         => \@branchloop_select,
258         );
259                                                                                                         # END $OP eq ADD_FORM
260 #---------------------- DEFAULT DISPLAPY BELOW ---------------------
261
262 # called by default form, used to confirm deletion of data in DB
263 } elsif ($op eq 'delete_confirm') {
264
265     my $budget = GetBudget($budget_id);
266         $template->param(
267                 budget_id     => $budget->{'budget_id'},
268                 budget_code   => $budget->{'budget_code'},
269                 budget_name   => $budget->{'budget_name'},
270                 budget_amount => $num->format_price(  $budget->{'budget_amount'} ),
271         );
272                                                                                                         # END $OP eq DELETE_CONFIRM
273 # called by delete_confirm, used to effectively confirm deletion of data in DB
274 }  else {
275     if ( $op eq 'delete_confirmed' ) {
276         my $rc = DelBudget($budget_id);
277     }
278     if ( $op eq 'add_validate' ) {
279         my %budget_hash = (
280             budget_id              => $budget_id,
281             budget_parent_id       => $budget_parent_id,
282             budget_period_id       => $budget_period_id,
283             budget_code            => $budget_code,
284             budget_name            => $budget_name,
285             budget_branchcode      => $budget_branchcode,
286             budget_amount          => $budget_amount,
287             budget_amount_sublevel => $budget_amount_sublevel,
288             budget_encumb          => $budget_encumb,
289             budget_expend          => $budget_expend,
290             budget_notes           => $budget_notes,
291             sort1_authcat          => $sort1_authcat,
292             sort2_authcat          => $sort2_authcat,
293             budget_description     => $budget_description,
294             budget_owner_id        => $budget_owner_id,
295             budget_permission      => $budget_permission,
296         );
297         if ( defined $budget_id ) {
298             ModBudget( \%budget_hash );
299         } else {
300             AddBudget( \%budget_hash );
301         }
302     }
303     my $branches = GetBranches();
304     my $budget_period_dropbox = GetBudgetPeriodsDropbox($budget_period_id );
305         $template->param(
306                 budget_period_dropbox     => $budget_period_dropbox,
307                 budget_id                 => $budget_id,
308                 budget_period_startdate   => $period->{'budget_period_startdate'},
309                 budget_period_enddate     => $period->{'budget_period_enddate'},
310         );
311     my $moo = GetBudgetHierarchy($budget_period_id, $template->{param_map}->{'USER_INFO'}[0]->{'branchcode'}, $show_mine?$borrower_id:'');
312     my @budgets = @$moo; #FIXME
313
314     my $toggle = 0;
315     my @loop;
316     my $period_total = 0;
317     my ( $period_alloc_total, $base_alloc_total, $sub_alloc_total, $base_spent_total, $base_remaining_total );
318
319     foreach my $budget (@budgets) {
320
321         # PERMISSIONS
322          unless($staffflags->{'superlibrarian'}   == 1 ) {
323             #IF NO PERMS, THEN DISABLE EDIT/DELETE
324             unless ( $template->{param_map}->{'CAN_user_acquisition_budget_modify'} ) {
325                 $budget->{'budget_lock'} = 1;
326             }
327             # check budget permission
328             if ( $budget_period_locked == 1 ) {
329                 $budget->{'budget_lock'} = 1;
330
331             } elsif ( $budget->{budget_permission} == 1 ) {
332
333                 if ( $borrower_id != $budget->{'budget_owner_id'} ) {
334                     $budget->{'budget_lock'} = 1;
335                 }
336                 # check parent perms too
337                 my $parents_perm = 0;
338                 if ( $budget->{depth} > 0 ) {
339                     $parents_perm = CheckBudgetParentPerm( $budget, $borrower_id );
340                     delete $budget->{'budget_lock'} if $parents_perm == '1';
341                 }
342             } elsif ( $budget->{budget_permission} == 2 ) {
343
344                 $budget->{'budget_lock'} = 1 if $user_branchcode ne $budget->{budget_branchcode};
345             }
346         }    # ...SUPER_LIB END
347
348         # if a budget search doesnt match, next
349         if ($filter_budgetname ) {
350             next unless  $budget->{budget_code}  =~ m/$filter_budgetname/  ||
351             $budget->{name}  =~ m/$filter_budgetname/ ;
352         }
353         if ($filter_budgetbranch ) {
354             next unless  $budget->{budget_branchcode}  =~ m/$filter_budgetbranch/;
355         }
356
357 ## TOTALS
358         # adds to total  - only if budget is a 'top-level' budget
359         $period_alloc_total += $budget->{'budget_amount_total'} if $budget->{'depth'} == 0;
360         $base_alloc_total += $budget->{'budget_amount'};
361         $sub_alloc_total  += $budget->{'budget_amount_sublevel'};
362         $base_spent_total += $budget->{'budget_spent'};
363         $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'};
364         $base_remaining_total += $budget->{'budget_remaining'};
365
366 # if amount == 0 dont display...
367         delete  $budget->{'budget_unalloc_sublevel'} if  $budget->{'budget_unalloc_sublevel'} == 0 ;
368         delete  $budget->{'budget_amount_sublevel'} if  $budget->{'budget_amount_sublevel'} == 0 ;
369
370         $budget->{'remaining_pos'} = 1 if $budget->{'budget_remaining'} > 0;
371         $budget->{'remaining_neg'} = 1 if $budget->{'budget_remaining'} < 0;
372         $budget->{'budget_amount'}           = $num->format_price( $budget->{'budget_amount'} );
373         $budget->{'budget_spent'}            = $num->format_price( $budget->{'budget_spent'} );
374         $budget->{'budget_remaining'}        = $num->format_price( $budget->{'budget_remaining'} );
375         $budget->{'budget_amount_total'}     = $num->format_price( $budget->{'budget_amount_total'} );
376         $budget->{'budget_amount_sublevel'}  = $num->format_price( $budget->{'budget_amount_sublevel'} ) if defined $budget->{'budget_amount_sublevel'};
377         $budget->{'budget_unalloc_sublevel'} = $num->format_price( $budget->{'budget_unalloc_sublevel'} ) if defined $budget->{'budget_unalloc_sublevel'};
378
379         my $borrower = &GetMember( $budget->{budget_owner_id} );
380         $budget->{budget_owner_name}     = $borrower->{'firstname'} . ' ' . $borrower->{'surname'};
381         $budget->{budget_borrowernumber} = $borrower->{'borrowernumber'};
382
383         push( @loop, {  %{$budget},
384                         toggle      => $toggle++%2,
385                         branchname  => $branches->{ $budget->{branchcode} }->{branchname},
386                         startdate   => format_date($budget->{startdate}),
387                         enddate     => format_date($budget->{enddate}),
388                     }
389         );
390     }
391
392     $template->param(
393         else                   => 1,
394         budget                 => \@loop,
395         budget_period_total    => $num->format_price($budget_period_total),
396         period_alloc_total     => $num->format_price($period_alloc_total),
397         base_alloc_total       => $num->format_price($base_alloc_total),
398         sub_alloc_total        => $num->format_price($sub_alloc_total),
399         base_spent_total       => $num->format_price($base_spent_total),
400         base_remaining_total   => $num->format_price($base_remaining_total),
401         period_remaining_total => $num->format_price( $period_alloc_total - $base_alloc_total ),
402         branchloop             => \@branchloop2,
403         cur                    => $cur->{symbol},
404         cur_format             => $cur_format,
405         #               pagination_bar => pagination_bar(
406         #                       $script_name, getnbpages(scalar @results, $pagesize),
407         #                       $page,        'page' ),
408     );
409
410 } #---- END $OP eq DEFAULT
411
412 output_html_with_http_headers $input, $cookie, $template->output;