Merge remote-tracking branch 'origin/new/bug_7805'
[koha.git] / C4 / Budgets.pm
1 package C4::Budgets;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use C4::Context;
23 use C4::Dates qw(format_date format_date_in_iso);
24 use C4::SQLHelper qw<:all>;
25 use C4::Debug;
26
27 use vars qw($VERSION @ISA @EXPORT);
28
29 BEGIN {
30         # set the version for version checking
31     $VERSION = 3.07.00.049;
32         require Exporter;
33         @ISA    = qw(Exporter);
34         @EXPORT = qw(
35
36         &GetBudget
37         &GetBudgets
38         &GetBudgetHierarchy
39             &AddBudget
40         &ModBudget
41         &DelBudget
42         &GetBudgetSpent
43         &GetBudgetOrdered
44         &GetPeriodsCount
45         &GetChildBudgetsSpent
46
47         &GetBudgetUsers
48         &ModBudgetUsers
49         &CanUserUseBudget
50         &CanUserModifyBudget
51
52             &GetBudgetPeriod
53         &GetBudgetPeriods
54         &ModBudgetPeriod
55         &AddBudgetPeriod
56             &DelBudgetPeriod
57
58         &GetAuthvalueDropbox
59
60         &ModBudgetPlan
61
62         &GetCurrency
63         &GetCurrencies
64         &ModCurrencies
65         &ConvertCurrency
66         
67                 &GetBudgetsPlanCell
68         &AddBudgetPlanValue
69         &GetBudgetAuthCats
70         &BudgetHasChildren
71         &CheckBudgetParent
72         &CheckBudgetParentPerm
73
74         &HideCols
75         &GetCols
76         );
77 }
78
79 # ----------------------------BUDGETS.PM-----------------------------";
80
81
82 =head1 FUNCTIONS ABOUT BUDGETS
83
84 =cut
85
86 sub HideCols {
87     my ( $authcat, @hide_cols ) = @_;
88     my $dbh = C4::Context->dbh;
89
90     my $sth1 = $dbh->prepare(
91         qq|
92         UPDATE aqbudgets_planning SET display = 0 
93         WHERE authcat = ? 
94         AND  authvalue = ? |
95     );
96     foreach my $authvalue (@hide_cols) {
97 #        $sth1->{TraceLevel} = 3;
98         $sth1->execute(  $authcat, $authvalue );
99     }
100 }
101
102 sub GetCols {
103     my ( $authcat, $authvalue ) = @_;
104
105     my $dbh = C4::Context->dbh;
106     my $sth = $dbh->prepare(
107         qq|
108         SELECT count(display) as cnt from aqbudgets_planning
109         WHERE  authcat = ? 
110         AND authvalue = ? and display  = 0   |
111     );
112
113 #    $sth->{TraceLevel} = 3;
114     $sth->execute( $authcat, $authvalue );
115     my $res  = $sth->fetchrow_hashref;
116
117     return  $res->{cnt} > 0 ? 0: 1
118
119 }
120
121 sub CheckBudgetParentPerm {
122     my ( $budget, $borrower_id ) = @_;
123     my $depth = $budget->{depth};
124     my $parent_id = $budget->{budget_parent_id};
125     while ($depth) {
126         my $parent = GetBudget($parent_id);
127         $parent_id = $parent->{budget_parent_id};
128         if ( $parent->{budget_owner_id} == $borrower_id ) {
129             return 1;
130         }
131         $depth--
132     }
133     return 0;
134 }
135
136 sub AddBudgetPeriod {
137     my ($budgetperiod) = @_;
138         return InsertInTable("aqbudgetperiods",$budgetperiod);
139 }
140 # -------------------------------------------------------------------
141 sub GetPeriodsCount {
142     my $dbh = C4::Context->dbh;
143     my $sth = $dbh->prepare("
144         SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
145     $sth->execute();
146     my $res = $sth->fetchrow_hashref;
147     return $res->{'sum'};
148 }
149
150 # -------------------------------------------------------------------
151 sub CheckBudgetParent {
152     my ( $new_parent, $budget ) = @_;
153     my $new_parent_id = $new_parent->{'budget_id'};
154     my $budget_id     = $budget->{'budget_id'};
155     my $dbh           = C4::Context->dbh;
156     my $parent_id_tmp = $new_parent_id;
157
158     # check new-parent is not a child (or a child's child ;)
159     my $sth = $dbh->prepare(qq|
160         SELECT budget_parent_id FROM
161             aqbudgets where budget_id = ? | );
162     while (1) {
163         $sth->execute($parent_id_tmp);
164         my $res = $sth->fetchrow_hashref;
165         if ( $res->{'budget_parent_id'} == $budget_id ) {
166             return 1;
167         }
168         if ( not defined $res->{'budget_parent_id'} ) {
169             return 0;
170         }
171         $parent_id_tmp = $res->{'budget_parent_id'};
172     }
173 }
174
175 # -------------------------------------------------------------------
176 sub BudgetHasChildren {
177     my ( $budget_id  ) = @_;
178     my $dbh = C4::Context->dbh;
179     my $sth = $dbh->prepare(qq|
180        SELECT count(*) as sum FROM  aqbudgets
181         WHERE budget_parent_id = ?   | );
182     $sth->execute( $budget_id );
183     my $sum = $sth->fetchrow_hashref;
184     return $sum->{'sum'};
185 }
186
187 # -------------------------------------------------------------------
188 sub GetBudgetsPlanCell {
189     my ( $cell, $period, $budget ) = @_;
190     my ($actual, $sth);
191     my $dbh = C4::Context->dbh;
192     if ( $cell->{'authcat'} eq 'MONTHS' ) {
193         # get the actual amount
194         $sth = $dbh->prepare( qq|
195
196             SELECT SUM(ecost) AS actual FROM aqorders
197                 WHERE    budget_id = ? AND
198                 entrydate like "$cell->{'authvalue'}%"  |
199         );
200         $sth->execute( $cell->{'budget_id'} );
201     } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
202         # get the actual amount
203         $sth = $dbh->prepare( qq|
204
205             SELECT SUM(ecost) FROM aqorders
206                 LEFT JOIN aqorders_items
207                 ON (aqorders.ordernumber = aqorders_items.ordernumber)
208                 LEFT JOIN items
209                 ON (aqorders_items.itemnumber = items.itemnumber)
210                 WHERE budget_id = ? AND homebranch = ? |          );
211
212         $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
213     } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
214         # get the actual amount
215         $sth = $dbh->prepare(  qq|
216
217             SELECT SUM( ecost *  quantity) AS actual
218                 FROM aqorders JOIN biblioitems
219                 ON (biblioitems.biblionumber = aqorders.biblionumber )
220                 WHERE aqorders.budget_id = ? and itemtype  = ? |
221         );
222         $sth->execute(  $cell->{'budget_id'},
223                         $cell->{'authvalue'} );
224     }
225     # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
226     else {
227         # get the actual amount
228         $sth = $dbh->prepare( qq|
229
230         SELECT  SUM(ecost * quantity) AS actual
231             FROM aqorders
232             JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
233             WHERE  aqorders.budget_id = ? AND
234                 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
235                 (aqbudgets.sort2_authcat = ? AND sort2 =?))    |
236         );
237         $sth->execute(  $cell->{'budget_id'},
238                         $budget->{'sort1_authcat'},
239                         $cell->{'authvalue'},
240                         $budget->{'sort2_authcat'},
241                         $cell->{'authvalue'}
242         );
243     }
244     $actual = $sth->fetchrow_array;
245
246     # get the estimated amount
247     $sth = $dbh->prepare( qq|
248
249         SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
250             WHERE budget_period_id = ? AND
251                 budget_id = ? AND
252                 authvalue = ? AND
253                 authcat = ?         |
254     );
255     $sth->execute(  $cell->{'budget_period_id'},
256                     $cell->{'budget_id'},
257                     $cell->{'authvalue'},
258                     $cell->{'authcat'},
259     );
260
261
262     my $res  = $sth->fetchrow_hashref;
263   #  my $display = $res->{'display'};
264     my $estimated = $res->{'estimated'};
265
266
267     return $actual, $estimated;
268 }
269
270 # -------------------------------------------------------------------
271 sub ModBudgetPlan {
272     my ( $budget_plan, $budget_period_id, $authcat ) = @_;
273     my $dbh = C4::Context->dbh;
274     foreach my $buds (@$budget_plan) {
275         my $lines = $buds->{lines};
276         my $sth = $dbh->prepare( qq|
277                 DELETE FROM aqbudgets_planning
278                     WHERE   budget_period_id   = ? AND
279                             budget_id   = ? AND
280                             authcat            = ? |
281         );
282     #delete a aqplan line of cells, then insert new cells, 
283     # these could be UPDATES rather than DEL/INSERTS...
284         $sth->execute( $budget_period_id,  $lines->[0]{budget_id}   , $authcat );
285
286         foreach my $cell (@$lines) {
287             my $sth = $dbh->prepare( qq|
288
289                 INSERT INTO aqbudgets_planning
290                      SET   budget_id     = ?,
291                      budget_period_id  = ?,
292                      authcat          = ?,
293                      estimated_amount  = ?,
294                      authvalue       = ?  |
295             );
296             $sth->execute(
297                             $cell->{'budget_id'},
298                             $cell->{'budget_period_id'},
299                             $cell->{'authcat'},
300                             $cell->{'estimated_amount'},
301                             $cell->{'authvalue'},
302             );
303         }
304     }
305 }
306
307 # -------------------------------------------------------------------
308 sub GetBudgetSpent {
309         my ($budget_id) = @_;
310         my $dbh = C4::Context->dbh;
311         my $sth = $dbh->prepare(qq|
312         SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
313             WHERE budget_id = ? AND
314             quantityreceived > 0 AND
315             datecancellationprinted IS NULL
316     |);
317
318         $sth->execute($budget_id);
319         my $sum =  $sth->fetchrow_array;
320         return $sum;
321 }
322
323 # -------------------------------------------------------------------
324 sub GetBudgetOrdered {
325         my ($budget_id) = @_;
326         my $dbh = C4::Context->dbh;
327         my $sth = $dbh->prepare(qq|
328         SELECT SUM(ecost *  quantity) AS sum FROM aqorders
329             WHERE budget_id = ? AND
330             quantityreceived = 0 AND
331             datecancellationprinted IS NULL
332     |);
333
334         $sth->execute($budget_id);
335         my $sum =  $sth->fetchrow_array;
336         return $sum;
337 }
338
339 # -------------------------------------------------------------------
340 sub GetBudgetAuthCats  {
341     my ($budget_period_id) = shift;
342     # now, populate the auth_cats_loop used in the budget planning button
343     # we must retrieve all auth values used by at least one budget
344     my $dbh = C4::Context->dbh;
345     my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
346     $sth->execute($budget_period_id);
347     my %authcats;
348     while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
349         $authcats{$sort1_authcat}=1;
350         $authcats{$sort2_authcat}=1;
351     }
352     my @auth_cats_loop;
353     foreach (sort keys %authcats) {
354         push @auth_cats_loop,{ authcat => $_ };
355     }
356     return \@auth_cats_loop;
357 }
358
359 # -------------------------------------------------------------------
360 sub GetAuthvalueDropbox {
361     my ( $authcat, $default ) = @_;
362     my $dbh = C4::Context->dbh;
363     my $sth = $dbh->prepare(
364         'SELECT authorised_value,lib FROM authorised_values
365         WHERE category = ? ORDER BY lib'
366     );
367     $sth->execute( $authcat );
368     my $option_list = [];
369     my @authorised_values = ( q{} );
370     while (my ($value, $lib) = $sth->fetchrow_array) {
371         push @{$option_list}, {
372             value => $value,
373             label => $lib,
374             default => ($default eq $value),
375         };
376     }
377
378     if ( @{$option_list} ) {
379         return $option_list;
380     }
381     return;
382 }
383
384 # -------------------------------------------------------------------
385 sub GetBudgetPeriods {
386         my ($filters,$orderby) = @_;
387     return SearchInTable("aqbudgetperiods",$filters, $orderby, undef,undef, undef, "wide");
388 }
389 # -------------------------------------------------------------------
390 sub GetBudgetPeriod {
391         my ($budget_period_id) = @_;
392         my $dbh = C4::Context->dbh;
393         ## $total = number of records linked to the record that must be deleted
394         my $total = 0;
395         ## get information about the record that will be deleted
396         my $sth;
397         if ($budget_period_id) {
398                 $sth = $dbh->prepare( qq|
399               SELECT      *
400                 FROM aqbudgetperiods
401                 WHERE budget_period_id=? |
402                 );
403                 $sth->execute($budget_period_id);
404         } else {         # ACTIVE BUDGET
405                 $sth = $dbh->prepare(qq|
406                           SELECT      *
407                 FROM aqbudgetperiods
408                 WHERE budget_period_active=1 |
409                 );
410                 $sth->execute();
411         }
412         my $data = $sth->fetchrow_hashref;
413         return $data;
414 }
415
416 # -------------------------------------------------------------------
417 sub DelBudgetPeriod{
418         my ($budget_period_id) = @_;
419         my $dbh = C4::Context->dbh;
420           ; ## $total = number of records linked to the record that must be deleted
421     my $total = 0;
422
423         ## get information about the record that will be deleted
424         my $sth = $dbh->prepare(qq|
425                 DELETE 
426          FROM aqbudgetperiods
427          WHERE budget_period_id=? |
428         );
429         return $sth->execute($budget_period_id);
430 }
431
432 # -------------------------------------------------------------------
433 sub ModBudgetPeriod {
434         my ($budget_period_information) = @_;
435         return UpdateInTable("aqbudgetperiods",$budget_period_information);
436 }
437
438 # -------------------------------------------------------------------
439 sub GetBudgetHierarchy {
440     my ( $budget_period_id, $branchcode, $owner ) = @_;
441     my @bind_params;
442     my $dbh   = C4::Context->dbh;
443     my $query = qq|
444                     SELECT aqbudgets.*, aqbudgetperiods.budget_period_active
445                     FROM aqbudgets 
446                     JOIN aqbudgetperiods USING (budget_period_id)|;
447                         
448         my @where_strings;
449     # show only period X if requested
450     if ($budget_period_id) {
451         push @where_strings," aqbudgets.budget_period_id = ?";
452         push @bind_params, $budget_period_id;
453     }
454         # show only budgets owned by me, my branch or everyone
455     if ($owner) {
456         if ($branchcode) {
457             push @where_strings,
458             qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))};
459             push @bind_params, ( $owner, $branchcode );
460         } else {
461             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
462             push @bind_params, $owner;
463         }
464     } else {
465         if ($branchcode) {
466             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
467             push @bind_params, $branchcode;
468         }
469     }
470         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
471         $debug && warn $query,join(",",@bind_params);
472         my $sth = $dbh->prepare($query);
473         $sth->execute(@bind_params);
474         my $results = $sth->fetchall_arrayref({});
475         my @res     = @$results;
476         my $i = 0;
477         while (1) {
478                 my $depth_cnt = 0;
479                 foreach my $r (@res) {
480                         my @child;
481                         # look for children
482                         $r->{depth} = '0' if !defined $r->{budget_parent_id};
483                         foreach my $r2 (@res) {
484                                 if (defined $r2->{budget_parent_id}
485                                         && $r2->{budget_parent_id} == $r->{budget_id}) {
486                                         push @child, $r2->{budget_id};
487                                         $r2->{depth} = ($r->{depth} + 1) if defined $r->{depth};
488                                 }
489                         }
490                         $r->{child} = \@child if scalar @child > 0;    # add the child
491                         $depth_cnt++ if !defined $r->{'depth'};
492                 }
493                 last if ($depth_cnt == 0 || $i == 100);
494                 $i++;
495         }
496
497         # look for top parents 1st
498         my (@sort, $depth_count);
499         ($i, $depth_count) = 0;
500         while (1) {
501                 my $children = 0;
502                 foreach my $r (@res) {
503                         if ($r->{depth} == $depth_count) {
504                                 $children++ if (ref $r->{child} eq 'ARRAY');
505
506                                 # find the parent id element_id and insert it after
507                                 my $i2 = 0;
508                                 my $parent;
509                                 if ($depth_count > 0) {
510
511                                         # add indent
512                                         my $depth = $r->{depth} * 2;
513                                         $r->{budget_code_indent} = $r->{budget_code};
514                                         $r->{budget_name_indent} = $r->{budget_name};
515                                         foreach my $r3 (@sort) {
516                                                 if ($r3->{budget_id} == $r->{budget_parent_id}) {
517                                                         $parent = $i2;
518                                                         last;
519                                                 }
520                                                 $i2++;
521                                         }
522                                 } else {
523                                         $r->{budget_code_indent} = $r->{budget_code};
524                                         $r->{budget_name_indent} = $r->{budget_name};
525                                 }
526                 
527                                 if (defined $parent) {
528                                         splice @sort, ($parent + 1), 0, $r;
529                                 } else {
530                                         push @sort, $r;
531                                 }
532                         }
533
534                         $i++;
535                 }    # --------------foreach
536                 $depth_count++;
537                 last if $children == 0;
538         }
539
540 # add budget-percent and allocation, and flags for html-template
541         foreach my $r (@sort) {
542                 my $subs_href = $r->{'child'};
543         my @subs_arr = ();
544         if ( defined $subs_href ) {
545             @subs_arr = @{$subs_href};
546         }
547
548         my $moo = $r->{'budget_code_indent'};
549         $moo =~ s/\ /\&nbsp\;/g;
550         $r->{'budget_code_indent'} =  $moo;
551
552         $moo = $r->{'budget_name_indent'};
553         $moo =~ s/\ /\&nbsp\;/g;
554         $r->{'budget_name_indent'} = $moo;
555
556         $r->{'budget_spent'}       = GetBudgetSpent( $r->{'budget_id'} );
557
558         $r->{'budget_amount_total'} =  $r->{'budget_amount'};
559
560         # foreach sub-levels
561         my $unalloc_count ;
562
563                 foreach my $sub (@subs_arr) {
564                         my $sub_budget = GetBudget($sub);
565
566                         $r->{budget_spent_sublevel} +=    GetBudgetSpent( $sub_budget->{'budget_id'} );
567                         $unalloc_count +=   $sub_budget->{'budget_amount'};
568                 }
569         }
570         return \@sort;
571 }
572
573 # -------------------------------------------------------------------
574
575 sub AddBudget {
576     my ($budget) = @_;
577         return InsertInTable("aqbudgets",$budget);
578 }
579
580 # -------------------------------------------------------------------
581 sub ModBudget {
582     my ($budget) = @_;
583         return UpdateInTable("aqbudgets",$budget);
584 }
585
586 # -------------------------------------------------------------------
587 sub DelBudget {
588         my ($budget_id) = @_;
589         my $dbh         = C4::Context->dbh;
590         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
591         my $rc          = $sth->execute($budget_id);
592         return $rc;
593 }
594
595
596 =head2 GetBudget
597
598   &GetBudget($budget_id);
599
600 get a specific budget
601
602 =cut
603
604 # -------------------------------------------------------------------
605 sub GetBudget {
606     my ( $budget_id ) = @_;
607     my $dbh = C4::Context->dbh;
608     my $query = "
609         SELECT *
610         FROM   aqbudgets
611         WHERE  budget_id=?
612         ";
613     my $sth = $dbh->prepare($query);
614     $sth->execute( $budget_id );
615     my $result = $sth->fetchrow_hashref;
616     return $result;
617 }
618
619 =head2 GetChildBudgetsSpent
620
621   &GetChildBudgetsSpent($budget-id);
622
623 gets the total spent of the level and sublevels of $budget_id
624
625 =cut
626
627 # -------------------------------------------------------------------
628 sub GetChildBudgetsSpent {
629     my ( $budget_id ) = @_;
630     my $dbh = C4::Context->dbh;
631     my $query = "
632         SELECT *
633         FROM   aqbudgets
634         WHERE  budget_parent_id=?
635         ";
636     my $sth = $dbh->prepare($query);
637     $sth->execute( $budget_id );
638     my $result = $sth->fetchall_arrayref({});
639     my $total_spent = GetBudgetSpent($budget_id);
640     if ($result){
641         $total_spent += GetChildBudgetsSpent($_->{"budget_id"}) foreach @$result;    
642     }
643     return $total_spent;
644 }
645
646 =head2 GetBudgets
647
648   &GetBudgets($filter, $order_by);
649
650 gets all budgets
651
652 =cut
653
654 # -------------------------------------------------------------------
655 sub GetBudgets {
656     my ($filters,$orderby) = @_;
657     return SearchInTable("aqbudgets",$filters, $orderby, undef,undef, undef, "wide");
658 }
659
660 =head2 GetBudgetUsers
661
662     my @borrowernumbers = &GetBudgetUsers($budget_id);
663
664 Return the list of borrowernumbers linked to a budget
665
666 =cut
667
668 sub GetBudgetUsers {
669     my ($budget_id) = @_;
670
671     my $dbh = C4::Context->dbh;
672     my $query = qq{
673         SELECT borrowernumber
674         FROM aqbudgetborrowers
675         WHERE budget_id = ?
676     };
677     my $sth = $dbh->prepare($query);
678     $sth->execute($budget_id);
679
680     my @borrowernumbers;
681     while (my ($borrowernumber) = $sth->fetchrow_array) {
682         push @borrowernumbers, $borrowernumber
683     }
684
685     return @borrowernumbers;
686 }
687
688 =head2 ModBudgetUsers
689
690     &ModBudgetUsers($budget_id, @borrowernumbers);
691
692 Modify the list of borrowernumbers linked to a budget
693
694 =cut
695
696 sub ModBudgetUsers {
697     my ($budget_id, @budget_users_id) = @_;
698
699     return unless $budget_id;
700
701     my $dbh = C4::Context->dbh;
702     my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
703     my $sth = $dbh->prepare($query);
704     $sth->execute($budget_id);
705
706     $query = qq{
707         INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
708         VALUES (?,?)
709     };
710     $sth = $dbh->prepare($query);
711     foreach my $borrowernumber (@budget_users_id) {
712         next unless $borrowernumber;
713         $sth->execute($budget_id, $borrowernumber);
714     }
715 }
716
717 sub CanUserUseBudget {
718     my ($borrower, $budget, $userflags) = @_;
719
720     if (not ref $borrower) {
721         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
722     }
723     if (not ref $budget) {
724         $budget = GetBudget($budget);
725     }
726
727     return 0 unless ($borrower and $budget);
728
729     if (not defined $userflags) {
730         $userflags = C4::Auth::getuserflags($borrower->{flags},
731             $borrower->{userid});
732     }
733
734     unless ($userflags->{superlibrarian}
735     || (ref $userflags->{acquisition}
736         && $userflags->{acquisition}->{budget_manage_all})
737     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
738     {
739         if (not exists $userflags->{acquisition}) {
740             return 0;
741         }
742
743         if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
744             return 0;
745         }
746
747         # Budget restricted to owner
748         if ($budget->{budget_permission} == 1
749         && $budget->{budget_owner_id}
750         && $budget->{budget_owner_id} != $borrower->{borrowernumber}) {
751             return 0;
752         }
753
754         my @budget_users = GetBudgetUsers($budget->{budget_id});
755
756         # Budget restricted to owner, users and library
757         if ($budget->{budget_permission} == 2
758         && $budget->{budget_owner_id}
759         && $budget->{budget_owner_id} != $borrower->{borrowernumber}
760         && (0 == grep {$borrower->{borrowernumber} == $_} @budget_users)
761         && defined $budget->{budget_branchcode}
762         && $budget->{budget_branchcode} ne C4::Context->userenv->{branch}) {
763             return 0;
764         }
765
766         # Budget restricted to owner and users
767         if ($budget->{budget_permission} == 3
768         && $budget->{budget_owner_id}
769         && $budget->{budget_owner_id} != $borrower->{borrowernumber}
770         && (0 == grep {$borrower->{borrowernumber} == $_} @budget_users)) {
771             return 0;
772         }
773     }
774
775     return 1;
776 }
777
778 sub CanUserModifyBudget {
779     my ($borrower, $budget, $userflags) = @_;
780
781     if (not ref $borrower) {
782         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
783     }
784     if (not ref $budget) {
785         $budget = GetBudget($budget);
786     }
787
788     return 0 unless ($borrower and $budget);
789
790     if (not defined $userflags) {
791         $userflags = C4::Auth::getuserflags($borrower->{flags},
792             $borrower->{userid});
793     }
794
795     unless ($userflags->{superlibrarian}
796     || (ref $userflags->{acquisition}
797         && $userflags->{acquisition}->{budget_manage_all})
798     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
799     {
800         if (!CanUserUseBudget($borrower, $budget, $userflags)) {
801             return 0;
802         }
803
804         if (ref $userflags->{acquisition}
805         && !$userflags->{acquisition}->{budget_modify}) {
806             return 0;
807         }
808     }
809
810     return 1;
811 }
812
813 # -------------------------------------------------------------------
814
815 =head2 GetCurrencies
816
817   @currencies = &GetCurrencies;
818
819 Returns the list of all known currencies.
820
821 C<$currencies> is a array; its elements are references-to-hash, whose
822 keys are the fields from the currency table in the Koha database.
823
824 =cut
825
826 sub GetCurrencies {
827     my $dbh   = C4::Context->dbh;
828     my $query = "
829         SELECT *
830         FROM   currency
831     ";
832     my $sth = $dbh->prepare($query);
833     $sth->execute;
834     my @results = ();
835     while ( my $data = $sth->fetchrow_hashref ) {
836         push( @results, $data );
837     }
838     return @results;
839 }
840
841 # -------------------------------------------------------------------
842
843 sub GetCurrency {
844     my $dbh   = C4::Context->dbh;
845     my $query = "
846         SELECT * FROM currency where active = '1'    ";
847     my $sth = $dbh->prepare($query);
848     $sth->execute;
849     my $r = $sth->fetchrow_hashref;
850     return $r;
851 }
852
853 =head2 ModCurrencies
854
855 &ModCurrencies($currency, $newrate);
856
857 Sets the exchange rate for C<$currency> to be C<$newrate>.
858
859 =cut
860
861 sub ModCurrencies {
862     my ( $currency, $rate ) = @_;
863     my $dbh   = C4::Context->dbh;
864     my $query = qq|
865         UPDATE currency
866         SET    rate=?
867         WHERE  currency=? |;
868     my $sth = $dbh->prepare($query);
869     $sth->execute( $rate, $currency );
870 }
871
872 # -------------------------------------------------------------------
873
874 =head2 ConvertCurrency
875
876   $foreignprice = &ConvertCurrency($currency, $localprice);
877
878 Converts the price C<$localprice> to foreign currency C<$currency> by
879 dividing by the exchange rate, and returns the result.
880
881 If no exchange rate is found, e is one to one.
882
883 =cut
884
885 sub ConvertCurrency {
886     my ( $currency, $price ) = @_;
887     my $dbh   = C4::Context->dbh;
888     my $query = "
889         SELECT rate
890         FROM   currency
891         WHERE  currency=?
892     ";
893     my $sth = $dbh->prepare($query);
894     $sth->execute($currency);
895     my $cur = ( $sth->fetchrow_array() )[0];
896     unless ($cur) {
897         $cur = 1;
898     }
899     return ( $price / $cur );
900 }
901
902 =head2 _columns
903
904 returns an array containing fieldname followed by PRI as value if PRIMARY Key
905
906 =cut
907
908 sub _columns(;$) {
909         my $tablename=shift||"aqbudgets";
910     return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from $tablename",{Columns=>[1,4]})};
911 }
912
913 sub _filter_fields{
914         my $budget=shift;
915         my $tablename=shift;
916     my @keys; 
917         my @values;
918         my %columns= _columns($tablename);
919         #Filter Primary Keys of table
920     my $elements=join "|",grep {$columns{$_} ne "PRI"} keys %columns;
921         foreach my $field (grep {/\b($elements)\b/} keys %$budget){
922                 $$budget{$field}=format_date_in_iso($$budget{$field}) if ($field=~/date/ && $$budget{$field} !~C4::Dates->regexp("iso"));
923                 my $strkeys= " $field = ? ";
924                 if ($field=~/branch/){
925                         $strkeys="( $strkeys OR $field='' OR $field IS NULL) ";
926                 }
927                 push @values, $$budget{$field};
928                 push @keys, $strkeys;
929         }
930         return (\@keys,\@values);
931 }
932
933 END { }    # module clean-up code here (global destructor)
934
935 1;
936 __END__
937
938 =head1 AUTHOR
939
940 Koha Development Team <http://koha-community.org/>
941
942 =cut