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