Merge branch 'bug_8557' into 3.12-master
[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         $sth->execute($budget_id);
318         my $sum =  $sth->fetchrow_array;
319
320     $sth = $dbh->prepare(qq|
321         SELECT SUM(shipmentcost) AS sum
322         FROM aqinvoices
323         WHERE shipmentcost_budgetid = ?
324           AND closedate IS NOT NULL
325     |);
326     $sth->execute($budget_id);
327     my ($shipmentcost_sum) = $sth->fetchrow_array;
328     $sum += $shipmentcost_sum;
329
330         return $sum;
331 }
332
333 # -------------------------------------------------------------------
334 sub GetBudgetOrdered {
335         my ($budget_id) = @_;
336         my $dbh = C4::Context->dbh;
337         my $sth = $dbh->prepare(qq|
338         SELECT SUM(ecost *  quantity) AS sum FROM aqorders
339             WHERE budget_id = ? AND
340             quantityreceived = 0 AND
341             datecancellationprinted IS NULL
342     |);
343         $sth->execute($budget_id);
344         my $sum =  $sth->fetchrow_array;
345
346     $sth = $dbh->prepare(qq|
347         SELECT SUM(shipmentcost) AS sum
348         FROM aqinvoices
349         WHERE shipmentcost_budgetid = ?
350           AND closedate IS NULL
351     |);
352     $sth->execute($budget_id);
353     my ($shipmentcost_sum) = $sth->fetchrow_array;
354     $sum += $shipmentcost_sum;
355
356         return $sum;
357 }
358
359 # -------------------------------------------------------------------
360 sub GetBudgetAuthCats  {
361     my ($budget_period_id) = shift;
362     # now, populate the auth_cats_loop used in the budget planning button
363     # we must retrieve all auth values used by at least one budget
364     my $dbh = C4::Context->dbh;
365     my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
366     $sth->execute($budget_period_id);
367     my %authcats;
368     while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
369         $authcats{$sort1_authcat}=1;
370         $authcats{$sort2_authcat}=1;
371     }
372     my @auth_cats_loop;
373     foreach (sort keys %authcats) {
374         push @auth_cats_loop,{ authcat => $_ };
375     }
376     return \@auth_cats_loop;
377 }
378
379 # -------------------------------------------------------------------
380 sub GetAuthvalueDropbox {
381     my ( $authcat, $default ) = @_;
382     my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
383     my $dbh = C4::Context->dbh;
384
385     my $query = qq{
386         SELECT *
387         FROM authorised_values
388     };
389     $query .= qq{
390           LEFT JOIN authorised_values_branches ON ( id = av_id )
391     } if $branch_limit;
392     $query .= qq{
393         WHERE category = ?
394     };
395     $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit;
396     $query .= " GROUP BY lib ORDER BY category, lib, lib_opac";
397     my $sth = $dbh->prepare($query);
398     $sth->execute( $authcat, $branch_limit ? $branch_limit : () );
399
400
401     my $option_list = [];
402     my @authorised_values = ( q{} );
403     while (my $av = $sth->fetchrow_hashref) {
404         push @{$option_list}, {
405             value => $av->{authorised_value},
406             label => $av->{lib},
407             default => ($default eq $av->{authorised_value}),
408         };
409     }
410
411     if ( @{$option_list} ) {
412         return $option_list;
413     }
414     return;
415 }
416
417 # -------------------------------------------------------------------
418 sub GetBudgetPeriods {
419         my ($filters,$orderby) = @_;
420     return SearchInTable("aqbudgetperiods",$filters, $orderby, undef,undef, undef, "wide");
421 }
422 # -------------------------------------------------------------------
423 sub GetBudgetPeriod {
424         my ($budget_period_id) = @_;
425         my $dbh = C4::Context->dbh;
426         ## $total = number of records linked to the record that must be deleted
427         my $total = 0;
428         ## get information about the record that will be deleted
429         my $sth;
430         if ($budget_period_id) {
431                 $sth = $dbh->prepare( qq|
432               SELECT      *
433                 FROM aqbudgetperiods
434                 WHERE budget_period_id=? |
435                 );
436                 $sth->execute($budget_period_id);
437         } else {         # ACTIVE BUDGET
438                 $sth = $dbh->prepare(qq|
439                           SELECT      *
440                 FROM aqbudgetperiods
441                 WHERE budget_period_active=1 |
442                 );
443                 $sth->execute();
444         }
445         my $data = $sth->fetchrow_hashref;
446         return $data;
447 }
448
449 # -------------------------------------------------------------------
450 sub DelBudgetPeriod{
451         my ($budget_period_id) = @_;
452         my $dbh = C4::Context->dbh;
453           ; ## $total = number of records linked to the record that must be deleted
454     my $total = 0;
455
456         ## get information about the record that will be deleted
457         my $sth = $dbh->prepare(qq|
458                 DELETE 
459          FROM aqbudgetperiods
460          WHERE budget_period_id=? |
461         );
462         return $sth->execute($budget_period_id);
463 }
464
465 # -------------------------------------------------------------------
466 sub ModBudgetPeriod {
467         my ($budget_period_information) = @_;
468         return UpdateInTable("aqbudgetperiods",$budget_period_information);
469 }
470
471 # -------------------------------------------------------------------
472 sub GetBudgetHierarchy {
473     my ( $budget_period_id, $branchcode, $owner ) = @_;
474     my @bind_params;
475     my $dbh   = C4::Context->dbh;
476     my $query = qq|
477                     SELECT aqbudgets.*, aqbudgetperiods.budget_period_active
478                     FROM aqbudgets 
479                     JOIN aqbudgetperiods USING (budget_period_id)|;
480                         
481         my @where_strings;
482     # show only period X if requested
483     if ($budget_period_id) {
484         push @where_strings," aqbudgets.budget_period_id = ?";
485         push @bind_params, $budget_period_id;
486     }
487         # show only budgets owned by me, my branch or everyone
488     if ($owner) {
489         if ($branchcode) {
490             push @where_strings,
491             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="")))};
492             push @bind_params, ( $owner, $branchcode );
493         } else {
494             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
495             push @bind_params, $owner;
496         }
497     } else {
498         if ($branchcode) {
499             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
500             push @bind_params, $branchcode;
501         }
502     }
503         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
504         $debug && warn $query,join(",",@bind_params);
505         my $sth = $dbh->prepare($query);
506         $sth->execute(@bind_params);
507         my $results = $sth->fetchall_arrayref({});
508         my @res     = @$results;
509         my $i = 0;
510         while (1) {
511                 my $depth_cnt = 0;
512                 foreach my $r (@res) {
513                         my @child;
514                         # look for children
515                         $r->{depth} = '0' if !defined $r->{budget_parent_id};
516                         foreach my $r2 (@res) {
517                                 if (defined $r2->{budget_parent_id}
518                                         && $r2->{budget_parent_id} == $r->{budget_id}) {
519                                         push @child, $r2->{budget_id};
520                                         $r2->{depth} = ($r->{depth} + 1) if defined $r->{depth};
521                                 }
522                         }
523                         $r->{child} = \@child if scalar @child > 0;    # add the child
524                         $depth_cnt++ if !defined $r->{'depth'};
525                 }
526                 last if ($depth_cnt == 0 || $i == 100);
527                 $i++;
528         }
529
530         # look for top parents 1st
531         my (@sort, $depth_count);
532         ($i, $depth_count) = 0;
533         while (1) {
534                 my $children = 0;
535                 foreach my $r (@res) {
536                         if ($r->{depth} == $depth_count) {
537                                 $children++ if (ref $r->{child} eq 'ARRAY');
538
539                                 # find the parent id element_id and insert it after
540                                 my $i2 = 0;
541                                 my $parent;
542                                 if ($depth_count > 0) {
543
544                                         # add indent
545                                         my $depth = $r->{depth} * 2;
546                                         $r->{budget_code_indent} = $r->{budget_code};
547                                         $r->{budget_name_indent} = $r->{budget_name};
548                                         foreach my $r3 (@sort) {
549                                                 if ($r3->{budget_id} == $r->{budget_parent_id}) {
550                                                         $parent = $i2;
551                                                         last;
552                                                 }
553                                                 $i2++;
554                                         }
555                                 } else {
556                                         $r->{budget_code_indent} = $r->{budget_code};
557                                         $r->{budget_name_indent} = $r->{budget_name};
558                                 }
559                 
560                                 if (defined $parent) {
561                                         splice @sort, ($parent + 1), 0, $r;
562                                 } else {
563                                         push @sort, $r;
564                                 }
565                         }
566
567                         $i++;
568                 }    # --------------foreach
569                 $depth_count++;
570                 last if $children == 0;
571         }
572
573 # add budget-percent and allocation, and flags for html-template
574         foreach my $r (@sort) {
575                 my $subs_href = $r->{'child'};
576         my @subs_arr = ();
577         if ( defined $subs_href ) {
578             @subs_arr = @{$subs_href};
579         }
580
581         my $moo = $r->{'budget_code_indent'};
582         $moo =~ s/\ /\&nbsp\;/g;
583         $r->{'budget_code_indent'} =  $moo;
584
585         $moo = $r->{'budget_name_indent'};
586         $moo =~ s/\ /\&nbsp\;/g;
587         $r->{'budget_name_indent'} = $moo;
588
589         $r->{'budget_spent'}       = GetBudgetSpent( $r->{'budget_id'} );
590
591         $r->{'budget_amount_total'} =  $r->{'budget_amount'};
592
593         # foreach sub-levels
594         my $unalloc_count ;
595
596                 foreach my $sub (@subs_arr) {
597                         my $sub_budget = GetBudget($sub);
598
599                         $r->{budget_spent_sublevel} +=    GetBudgetSpent( $sub_budget->{'budget_id'} );
600                         $unalloc_count +=   $sub_budget->{'budget_amount'};
601                 }
602         }
603         return \@sort;
604 }
605
606 # -------------------------------------------------------------------
607
608 sub AddBudget {
609     my ($budget) = @_;
610         return InsertInTable("aqbudgets",$budget);
611 }
612
613 # -------------------------------------------------------------------
614 sub ModBudget {
615     my ($budget) = @_;
616         return UpdateInTable("aqbudgets",$budget);
617 }
618
619 # -------------------------------------------------------------------
620 sub DelBudget {
621         my ($budget_id) = @_;
622         my $dbh         = C4::Context->dbh;
623         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
624         my $rc          = $sth->execute($budget_id);
625         return $rc;
626 }
627
628
629 =head2 GetBudget
630
631   &GetBudget($budget_id);
632
633 get a specific budget
634
635 =cut
636
637 # -------------------------------------------------------------------
638 sub GetBudget {
639     my ( $budget_id ) = @_;
640     my $dbh = C4::Context->dbh;
641     my $query = "
642         SELECT *
643         FROM   aqbudgets
644         WHERE  budget_id=?
645         ";
646     my $sth = $dbh->prepare($query);
647     $sth->execute( $budget_id );
648     my $result = $sth->fetchrow_hashref;
649     return $result;
650 }
651
652 =head2 GetChildBudgetsSpent
653
654   &GetChildBudgetsSpent($budget-id);
655
656 gets the total spent of the level and sublevels of $budget_id
657
658 =cut
659
660 # -------------------------------------------------------------------
661 sub GetChildBudgetsSpent {
662     my ( $budget_id ) = @_;
663     my $dbh = C4::Context->dbh;
664     my $query = "
665         SELECT *
666         FROM   aqbudgets
667         WHERE  budget_parent_id=?
668         ";
669     my $sth = $dbh->prepare($query);
670     $sth->execute( $budget_id );
671     my $result = $sth->fetchall_arrayref({});
672     my $total_spent = GetBudgetSpent($budget_id);
673     if ($result){
674         $total_spent += GetChildBudgetsSpent($_->{"budget_id"}) foreach @$result;    
675     }
676     return $total_spent;
677 }
678
679 =head2 GetBudgets
680
681   &GetBudgets($filter, $order_by);
682
683 gets all budgets
684
685 =cut
686
687 # -------------------------------------------------------------------
688 sub GetBudgets {
689     my ($filters,$orderby) = @_;
690     return SearchInTable("aqbudgets",$filters, $orderby, undef,undef, undef, "wide");
691 }
692
693 =head2 GetBudgetUsers
694
695     my @borrowernumbers = &GetBudgetUsers($budget_id);
696
697 Return the list of borrowernumbers linked to a budget
698
699 =cut
700
701 sub GetBudgetUsers {
702     my ($budget_id) = @_;
703
704     my $dbh = C4::Context->dbh;
705     my $query = qq{
706         SELECT borrowernumber
707         FROM aqbudgetborrowers
708         WHERE budget_id = ?
709     };
710     my $sth = $dbh->prepare($query);
711     $sth->execute($budget_id);
712
713     my @borrowernumbers;
714     while (my ($borrowernumber) = $sth->fetchrow_array) {
715         push @borrowernumbers, $borrowernumber
716     }
717
718     return @borrowernumbers;
719 }
720
721 =head2 ModBudgetUsers
722
723     &ModBudgetUsers($budget_id, @borrowernumbers);
724
725 Modify the list of borrowernumbers linked to a budget
726
727 =cut
728
729 sub ModBudgetUsers {
730     my ($budget_id, @budget_users_id) = @_;
731
732     return unless $budget_id;
733
734     my $dbh = C4::Context->dbh;
735     my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
736     my $sth = $dbh->prepare($query);
737     $sth->execute($budget_id);
738
739     $query = qq{
740         INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
741         VALUES (?,?)
742     };
743     $sth = $dbh->prepare($query);
744     foreach my $borrowernumber (@budget_users_id) {
745         next unless $borrowernumber;
746         $sth->execute($budget_id, $borrowernumber);
747     }
748 }
749
750 sub CanUserUseBudget {
751     my ($borrower, $budget, $userflags) = @_;
752
753     if (not ref $borrower) {
754         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
755     }
756     if (not ref $budget) {
757         $budget = GetBudget($budget);
758     }
759
760     return 0 unless ($borrower and $budget);
761
762     if (not defined $userflags) {
763         $userflags = C4::Auth::getuserflags($borrower->{flags},
764             $borrower->{userid});
765     }
766
767     unless ($userflags->{superlibrarian}
768     || (ref $userflags->{acquisition}
769         && $userflags->{acquisition}->{budget_manage_all})
770     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
771     {
772         if (not exists $userflags->{acquisition}) {
773             return 0;
774         }
775
776         if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
777             return 0;
778         }
779
780         # Budget restricted to owner
781         if ($budget->{budget_permission} == 1
782         && $budget->{budget_owner_id}
783         && $budget->{budget_owner_id} != $borrower->{borrowernumber}) {
784             return 0;
785         }
786
787         my @budget_users = GetBudgetUsers($budget->{budget_id});
788
789         # Budget restricted to owner, users and library
790         if ($budget->{budget_permission} == 2
791         && $budget->{budget_owner_id}
792         && $budget->{budget_owner_id} != $borrower->{borrowernumber}
793         && (0 == grep {$borrower->{borrowernumber} == $_} @budget_users)
794         && defined $budget->{budget_branchcode}
795         && $budget->{budget_branchcode} ne C4::Context->userenv->{branch}) {
796             return 0;
797         }
798
799         # Budget restricted to owner and users
800         if ($budget->{budget_permission} == 3
801         && $budget->{budget_owner_id}
802         && $budget->{budget_owner_id} != $borrower->{borrowernumber}
803         && (0 == grep {$borrower->{borrowernumber} == $_} @budget_users)) {
804             return 0;
805         }
806     }
807
808     return 1;
809 }
810
811 sub CanUserModifyBudget {
812     my ($borrower, $budget, $userflags) = @_;
813
814     if (not ref $borrower) {
815         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
816     }
817     if (not ref $budget) {
818         $budget = GetBudget($budget);
819     }
820
821     return 0 unless ($borrower and $budget);
822
823     if (not defined $userflags) {
824         $userflags = C4::Auth::getuserflags($borrower->{flags},
825             $borrower->{userid});
826     }
827
828     unless ($userflags->{superlibrarian}
829     || (ref $userflags->{acquisition}
830         && $userflags->{acquisition}->{budget_manage_all})
831     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
832     {
833         if (!CanUserUseBudget($borrower, $budget, $userflags)) {
834             return 0;
835         }
836
837         if (ref $userflags->{acquisition}
838         && !$userflags->{acquisition}->{budget_modify}) {
839             return 0;
840         }
841     }
842
843     return 1;
844 }
845
846 # -------------------------------------------------------------------
847
848 =head2 GetCurrencies
849
850   @currencies = &GetCurrencies;
851
852 Returns the list of all known currencies.
853
854 C<$currencies> is a array; its elements are references-to-hash, whose
855 keys are the fields from the currency table in the Koha database.
856
857 =cut
858
859 sub GetCurrencies {
860     my $dbh   = C4::Context->dbh;
861     my $query = "
862         SELECT *
863         FROM   currency
864     ";
865     my $sth = $dbh->prepare($query);
866     $sth->execute;
867     my @results = ();
868     while ( my $data = $sth->fetchrow_hashref ) {
869         push( @results, $data );
870     }
871     return @results;
872 }
873
874 # -------------------------------------------------------------------
875
876 sub GetCurrency {
877     my $dbh   = C4::Context->dbh;
878     my $query = "
879         SELECT * FROM currency where active = '1'    ";
880     my $sth = $dbh->prepare($query);
881     $sth->execute;
882     my $r = $sth->fetchrow_hashref;
883     return $r;
884 }
885
886 =head2 ModCurrencies
887
888 &ModCurrencies($currency, $newrate);
889
890 Sets the exchange rate for C<$currency> to be C<$newrate>.
891
892 =cut
893
894 sub ModCurrencies {
895     my ( $currency, $rate ) = @_;
896     my $dbh   = C4::Context->dbh;
897     my $query = qq|
898         UPDATE currency
899         SET    rate=?
900         WHERE  currency=? |;
901     my $sth = $dbh->prepare($query);
902     $sth->execute( $rate, $currency );
903 }
904
905 # -------------------------------------------------------------------
906
907 =head2 ConvertCurrency
908
909   $foreignprice = &ConvertCurrency($currency, $localprice);
910
911 Converts the price C<$localprice> to foreign currency C<$currency> by
912 dividing by the exchange rate, and returns the result.
913
914 If no exchange rate is found, e is one to one.
915
916 =cut
917
918 sub ConvertCurrency {
919     my ( $currency, $price ) = @_;
920     my $dbh   = C4::Context->dbh;
921     my $query = "
922         SELECT rate
923         FROM   currency
924         WHERE  currency=?
925     ";
926     my $sth = $dbh->prepare($query);
927     $sth->execute($currency);
928     my $cur = ( $sth->fetchrow_array() )[0];
929     unless ($cur) {
930         $cur = 1;
931     }
932     return ( $price / $cur );
933 }
934
935 =head2 _columns
936
937 returns an array containing fieldname followed by PRI as value if PRIMARY Key
938
939 =cut
940
941 sub _columns(;$) {
942         my $tablename=shift||"aqbudgets";
943     return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from $tablename",{Columns=>[1,4]})};
944 }
945
946 sub _filter_fields{
947         my $budget=shift;
948         my $tablename=shift;
949     my @keys; 
950         my @values;
951         my %columns= _columns($tablename);
952         #Filter Primary Keys of table
953     my $elements=join "|",grep {$columns{$_} ne "PRI"} keys %columns;
954         foreach my $field (grep {/\b($elements)\b/} keys %$budget){
955                 $$budget{$field}=format_date_in_iso($$budget{$field}) if ($field=~/date/ && $$budget{$field} !~C4::Dates->regexp("iso"));
956                 my $strkeys= " $field = ? ";
957                 if ($field=~/branch/){
958                         $strkeys="( $strkeys OR $field='' OR $field IS NULL) ";
959                 }
960                 push @values, $$budget{$field};
961                 push @keys, $strkeys;
962         }
963         return (\@keys,\@values);
964 }
965
966 END { }    # module clean-up code here (global destructor)
967
968 1;
969 __END__
970
971 =head1 AUTHOR
972
973 Koha Development Team <http://koha-community.org/>
974
975 =cut