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