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