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