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