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