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