Merge remote branch 'kc/new/bug_4912' into kcmaster
[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.*, aqbudgetperiods.budget_period_active
495                     FROM aqbudgets 
496                     JOIN aqbudgetperiods USING (budget_period_id)|;
497                         
498         my @where_strings;
499     # show only period X if requested
500     if ($budget_period_id) {
501         push @where_strings," aqbudgets.budget_period_id = ?";
502         push @bind_params, $budget_period_id;
503     }
504         # show only budgets owned by me, my branch or everyone
505     if ($owner) {
506         if ($branchcode) {
507             push @where_strings,
508             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="")))};
509             push @bind_params, ( $owner, $branchcode );
510         } else {
511             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
512             push @bind_params, $owner;
513         }
514     } else {
515         if ($branchcode) {
516             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
517             push @bind_params, $branchcode;
518         }
519     }
520         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
521         $debug && warn $query,join(",",@bind_params);
522         my $sth = $dbh->prepare($query);
523         $sth->execute(@bind_params);
524         my $results = $sth->fetchall_arrayref({});
525         my @res     = @$results;
526         my $i = 0;
527         while (1) {
528                 my $depth_cnt = 0;
529                 foreach my $r (@res) {
530                         my @child;
531                         # look for children
532                         $r->{depth} = '0' if !defined $r->{budget_parent_id};
533                         foreach my $r2 (@res) {
534                                 if (defined $r2->{budget_parent_id}
535                                         && $r2->{budget_parent_id} == $r->{budget_id}) {
536                                         push @child, $r2->{budget_id};
537                                         $r2->{depth} = ($r->{depth} + 1) if defined $r->{depth};
538                                 }
539                         }
540                         $r->{child} = \@child if scalar @child > 0;    # add the child
541                         $depth_cnt++ if !defined $r->{'depth'};
542                 }
543                 last if ($depth_cnt == 0 || $i == 100);
544                 $i++;
545         }
546
547         # look for top parents 1st
548         my (@sort, $depth_count);
549         ($i, $depth_count) = 0;
550         while (1) {
551                 my $children = 0;
552                 foreach my $r (@res) {
553                         if ($r->{depth} == $depth_count) {
554                                 $children++ if (ref $r->{child} eq 'ARRAY');
555
556                                 # find the parent id element_id and insert it after
557                                 my $i2 = 0;
558                                 my $parent;
559                                 if ($depth_count > 0) {
560
561                                         # add indent
562                                         my $depth = $r->{depth} * 2;
563                                         $r->{budget_code_indent} = $r->{budget_code};
564                                         $r->{budget_name_indent} = $r->{budget_name};
565                                         foreach my $r3 (@sort) {
566                                                 if ($r3->{budget_id} == $r->{budget_parent_id}) {
567                                                         $parent = $i2;
568                                                         last;
569                                                 }
570                                                 $i2++;
571                                         }
572                                 } else {
573                                         $r->{budget_code_indent} = $r->{budget_code};
574                                         $r->{budget_name_indent} = $r->{budget_name};
575                                 }
576                 
577                                 if (defined $parent) {
578                                         splice @sort, ($parent + 1), 0, $r;
579                                 } else {
580                                         push @sort, $r;
581                                 }
582                         }
583
584                         $i++;
585                 }    # --------------foreach
586                 $depth_count++;
587                 last if $children == 0;
588         }
589
590 # add budget-percent and allocation, and flags for html-template
591         foreach my $r (@sort) {
592                 my $subs_href = $r->{'child'};
593         my @subs_arr = @$subs_href if defined $subs_href;
594
595         my $moo = $r->{'budget_code_indent'};
596         $moo =~ s/\ /\&nbsp\;/g;
597         $r->{'budget_code_indent'} =  $moo;
598
599         $moo = $r->{'budget_name_indent'};
600         $moo =~ s/\ /\&nbsp\;/g;
601         $r->{'budget_name_indent'} = $moo;
602
603         $r->{'budget_spent'}       = GetBudgetSpent( $r->{'budget_id'} );
604
605         $r->{'budget_amount_total'} =  $r->{'budget_amount'};
606
607         # foreach sub-levels
608         my $unalloc_count ;
609
610                 foreach my $sub (@subs_arr) {
611                         my $sub_budget = GetBudget($sub);
612
613                         $r->{budget_spent_sublevel} +=    GetBudgetSpent( $sub_budget->{'budget_id'} );
614                         $unalloc_count +=   $sub_budget->{'budget_amount'};
615                 }
616         }
617         return \@sort;
618 }
619
620 # -------------------------------------------------------------------
621
622 sub AddBudget {
623     my ($budget) = @_;
624         return InsertInTable("aqbudgets",$budget);
625 }
626
627 # -------------------------------------------------------------------
628 sub ModBudget {
629     my ($budget) = @_;
630         return UpdateInTable("aqbudgets",$budget);
631 }
632
633 # -------------------------------------------------------------------
634 sub DelBudget {
635         my ($budget_id) = @_;
636         my $dbh         = C4::Context->dbh;
637         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
638         my $rc          = $sth->execute($budget_id);
639         return $rc;
640 }
641
642
643 =head2 GetBudget
644
645   &GetBudget($budget_id);
646
647 get a specific budget
648
649 =cut
650
651 # -------------------------------------------------------------------
652 sub GetBudget {
653     my ( $budget_id ) = @_;
654     my $dbh = C4::Context->dbh;
655     my $query = "
656         SELECT *
657         FROM   aqbudgets
658         WHERE  budget_id=?
659         ";
660     my $sth = $dbh->prepare($query);
661     $sth->execute( $budget_id );
662     my $result = $sth->fetchrow_hashref;
663     return $result;
664 }
665
666 =head2 GetBudgets
667
668   &GetBudgets($filter, $order_by);
669
670 gets all budgets
671
672 =cut
673
674 # -------------------------------------------------------------------
675 sub GetChildBudgetsSpent {
676     my ( $budget_id ) = @_;
677     my $dbh = C4::Context->dbh;
678     my $query = "
679         SELECT *
680         FROM   aqbudgets
681         WHERE  budget_parent_id=?
682         ";
683     my $sth = $dbh->prepare($query);
684     $sth->execute( $budget_id );
685     my $result = $sth->fetchall_arrayref({});
686     my $total_spent = GetBudgetSpent($budget_id);
687     if ($result){
688         $total_spent += GetChildBudgetsSpent($_->{"budget_id"}) foreach @$result;    
689     }
690     return $total_spent;
691 }
692
693 =head2 GetChildBudgetsSpent
694
695   &GetChildBudgetsSpent($budget-id);
696
697 gets the total spent of the level and sublevels of $budget_id
698
699 =cut
700
701 # -------------------------------------------------------------------
702 sub GetBudgets {
703     my ($filters,$orderby) = @_;
704     return SearchInTable("aqbudgets",$filters, $orderby, undef,undef, undef, "wide");
705 }
706
707 # -------------------------------------------------------------------
708
709 =head2 GetCurrencies
710
711   @currencies = &GetCurrencies;
712
713 Returns the list of all known currencies.
714
715 C<$currencies> is a array; its elements are references-to-hash, whose
716 keys are the fields from the currency table in the Koha database.
717
718 =cut
719
720 sub GetCurrencies {
721     my $dbh   = C4::Context->dbh;
722     my $query = "
723         SELECT *
724         FROM   currency
725     ";
726     my $sth = $dbh->prepare($query);
727     $sth->execute;
728     my @results = ();
729     while ( my $data = $sth->fetchrow_hashref ) {
730         push( @results, $data );
731     }
732     return @results;
733 }
734
735 # -------------------------------------------------------------------
736
737 sub GetCurrency {
738     my $dbh   = C4::Context->dbh;
739     my $query = "
740         SELECT * FROM currency where active = '1'    ";
741     my $sth = $dbh->prepare($query);
742     $sth->execute;
743     my $r = $sth->fetchrow_hashref;
744     return $r;
745 }
746
747 =head2 ModCurrencies
748
749 &ModCurrencies($currency, $newrate);
750
751 Sets the exchange rate for C<$currency> to be C<$newrate>.
752
753 =cut
754
755 sub ModCurrencies {
756     my ( $currency, $rate ) = @_;
757     my $dbh   = C4::Context->dbh;
758     my $query = qq|
759         UPDATE currency
760         SET    rate=?
761         WHERE  currency=? |;
762     my $sth = $dbh->prepare($query);
763     $sth->execute( $rate, $currency );
764 }
765
766 # -------------------------------------------------------------------
767
768 =head2 ConvertCurrency
769
770   $foreignprice = &ConvertCurrency($currency, $localprice);
771
772 Converts the price C<$localprice> to foreign currency C<$currency> by
773 dividing by the exchange rate, and returns the result.
774
775 If no exchange rate is found, e is one to one.
776
777 =cut
778
779 sub ConvertCurrency {
780     my ( $currency, $price ) = @_;
781     my $dbh   = C4::Context->dbh;
782     my $query = "
783         SELECT rate
784         FROM   currency
785         WHERE  currency=?
786     ";
787     my $sth = $dbh->prepare($query);
788     $sth->execute($currency);
789     my $cur = ( $sth->fetchrow_array() )[0];
790     unless ($cur) {
791         $cur = 1;
792     }
793     return ( $price / $cur );
794 }
795
796 =head2 _columns
797
798 returns an array containing fieldname followed by PRI as value if PRIMARY Key
799
800 =cut
801
802 sub _columns(;$) {
803         my $tablename=shift||"aqbudgets";
804     return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from $tablename",{Columns=>[1,4]})};
805 }
806
807 sub _filter_fields{
808         my $budget=shift;
809         my $tablename=shift;
810     my @keys; 
811         my @values;
812         my %columns= _columns($tablename);
813         #Filter Primary Keys of table
814     my $elements=join "|",grep {$columns{$_} ne "PRI"} keys %columns;
815         foreach my $field (grep {/\b($elements)\b/} keys %$budget){
816                 $$budget{$field}=format_date_in_iso($$budget{$field}) if ($field=~/date/ && $$budget{$field} !~C4::Dates->regexp("iso"));
817                 my $strkeys= " $field = ? ";
818                 if ($field=~/branch/){
819                         $strkeys="( $strkeys OR $field='' OR $field IS NULL) ";
820                 }
821                 push @values, $$budget{$field};
822                 push @keys, $strkeys;
823         }
824         return (\@keys,\@values);
825 }
826
827 END { }    # module clean-up code here (global destructor)
828
829 1;
830 __END__
831
832 =head1 AUTHOR
833
834 Koha Development Team <http://koha-community.org/>
835
836 =cut