big aqplan commit v2 for mantis:1177
[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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 use C4::Context;
22 use C4::Dates qw(format_date format_date_in_iso);
23 use C4::Debug;
24
25 use vars qw($VERSION @ISA @EXPORT);
26
27 BEGIN {
28         # set the version for version checking
29         $VERSION = 3.01;
30         require Exporter;
31         @ISA    = qw(Exporter);
32         @EXPORT = qw(
33
34         &GetBudget
35         &GetBudgets
36         &GetBudgetHierarchy
37             &AddBudget
38         &ModBudget
39         &DelBudget
40         &GetBudgetSpent
41         &GetPeriodsCount
42
43             &GetBudgetPeriod
44         &GetBudgetPeriods
45         &ModBudgetPeriod
46             &DelBudgetPeriod
47
48             &GetBudgetPeriodsDropbox
49         &GetBudgetSortDropbox
50             &GetAuthcatDropbox
51         &GetAuthvalueDropbox
52         &GetBudgetPermDropbox
53
54         &ModBudgetPlan
55         &GetCurrency
56         &GetCurrencies
57         &ModCurrencies
58         &ConvertCurrency
59         &GetBudgetsPlanCell
60         &AddBudgetPlanValue
61         &GetBudgetAuthCats
62         &BudgetHasChildren
63         &CheckBudgetParent
64         &CheckBudgetParentPerm
65
66         &HideCols
67         &GetCols
68         );
69 }
70
71 # ----------------------------BUDGETS.PM-----------------------------";
72
73
74 sub HideCols {
75     my ( $authcat, @hide_cols ) = @_;
76     my $dbh = C4::Context->dbh;
77
78 =c
79     my $sth = $dbh->prepare(
80         qq|
81         UPDATE aqbudgets_planning
82         SET display = 1 where authcat =  ? |
83     );
84     $sth->execute( $authcat );
85 =cut
86
87     my $sth1 = $dbh->prepare(
88         qq|
89         UPDATE aqbudgets_planning SET display = 0 
90         WHERE authcat = ? 
91         AND  authvalue = ? |
92     );
93     foreach my $authvalue (@hide_cols) {
94 #        $sth1->{TraceLevel} = 3;
95         $sth1->execute(  $authcat, $authvalue );
96     }
97 }
98
99 sub GetCols {
100     my ( $authcat, $authvalue ) = @_;
101
102     my $dbh = C4::Context->dbh;
103     my $sth = $dbh->prepare(
104         qq|
105         SELECT count(display) as cnt from aqbudgets_planning
106         WHERE  authcat = ? 
107         AND authvalue = ? and display  = 0   |
108     );
109
110 #    $sth->{TraceLevel} = 3;
111     $sth->execute( $authcat, $authvalue );
112     my $res  = $sth->fetchrow_hashref;
113
114     return  $res->{cnt} > 0 ? 0: 1
115
116 }
117
118 sub CheckBudgetParentPerm {
119     my ( $budget, $borrower_id ) = @_;
120     my $depth = $budget->{depth};
121     my $parent_id = $budget->{budget_parent_id};
122     while ($depth) {
123         my $parent = GetBudget($parent_id);
124         $parent_id = $parent->{budget_parent_id};
125         if ( $parent->{budget_owner_id} == $borrower_id ) {
126             return 1;
127         }
128         $depth--
129     }
130     return 0;
131 }
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     $sth->finish;
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->{TraceLevel} = 2;
232         $sth->execute(  $cell->{'budget_id'},
233                         $budget->{'sort1_authcat'},
234                         $cell->{'authvalue'},
235                         $budget->{'sort2_authcat'},
236                         $cell->{'authvalue'}
237         );
238     }
239     $actual = $sth->fetchrow_array;
240
241     # get the estimated amount
242     my $sth = $dbh->prepare( qq|
243
244         SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
245             WHERE budget_period_id = ? AND
246                 budget_id = ? AND
247                 authvalue = ? AND
248                 authcat = ?         |
249     );
250     $sth->execute(  $cell->{'budget_period_id'},
251                     $cell->{'budget_id'},
252                     $cell->{'authvalue'},
253                     $cell->{'authcat'},
254     );
255
256
257     my $res  = $sth->fetchrow_hashref;
258   #  my $display = $res->{'display'};
259     my $estimated = $res->{'estimated'};
260
261
262     return $actual, $estimated;
263 }
264
265 # -------------------------------------------------------------------
266 sub ModBudgetPlan {
267     my ( $budget_plan, $budget_period_id, $authcat ) = @_;
268     my $dbh = C4::Context->dbh;
269     foreach my $buds (@$budget_plan) {
270         my $lines = $buds->{lines};
271         my $sth = $dbh->prepare( qq|
272                 DELETE FROM aqbudgets_planning
273                     WHERE   budget_period_id   = ? AND
274                             budget_id   = ? AND
275                             authcat            = ? |
276         );
277     #delete a aqplan line of cells, then insert new cells, 
278     # these could be UPDATES rather than DEL/INSERTS...
279         $sth->execute( $budget_period_id,  $lines->[0]{budget_id}   , $authcat );
280
281         foreach my $cell (@$lines) {
282             my $sth = $dbh->prepare( qq|
283
284                 INSERT INTO aqbudgets_planning
285                      SET   budget_id     = ?,
286                      budget_period_id  = ?,
287                      authcat          = ?,
288                      estimated_amount  = ?,
289                      authvalue       = ?  |
290             );
291             $sth->execute(
292                             $cell->{'budget_id'},
293                             $cell->{'budget_period_id'},
294                             $cell->{'authcat'},
295                             $cell->{'estimated_amount'},
296                             $cell->{'authvalue'},
297             );
298         }
299     }
300 }
301
302 # -------------------------------------------------------------------
303 sub GetBudgetSpent {
304         my ($budget_id) = @_;
305         my $dbh = C4::Context->dbh;
306         my $sth = $dbh->prepare(qq|
307         SELECT SUM(ecost *  quantity  ) AS sum FROM aqorders
308             WHERE budget_id = ? AND
309             datecancellationprinted IS NULL 
310     |);
311
312         $sth->execute($budget_id);
313         my $sum =  $sth->fetchrow_array;
314 #       $sum =  sprintf  "%.2f", $sum;
315         return $sum;
316 }
317
318 # -------------------------------------------------------------------
319 sub GetBudgetPermDropbox {
320         my ($perm) = @_;
321         my %labels;
322         $labels{'0'} = 'None';
323         $labels{'1'} = 'Owner';
324         $labels{'2'} = 'Library';
325         my $radio = CGI::scrolling_list(
326                 -name      => 'budget_permission',
327                 -values    => [ '0', '1', '2' ],
328                 -default   => $perm,
329                 -labels    => \%labels,
330                 -size    => 1,
331         );
332         return $radio;
333 }
334
335 # -------------------------------------------------------------------
336 sub GetAuthcatDropbox  {
337         my ($name, $default ) = @_;
338         my @authorised_values;
339         my $value;
340         my $dbh = C4::Context->dbh;
341         my $sth = $dbh->prepare(qq|
342                 SELECT distinct(category)
343             FROM authorised_values WHERE category LIKE 'Asort%'
344             ORDER BY lib |
345         );
346         $sth->execute();
347
348         push @authorised_values, '';
349         while (my $value = $sth->fetchrow_array) {
350                 push @authorised_values, $value;
351         }
352
353     my $budget_authcat_dropbox = CGI::scrolling_list(
354         -name     => $name,
355         -values   => \@authorised_values,
356         -override => 1,
357         -size     => 1,
358         -default  => $default,
359         -multiple => 0,
360         -tabindex => 1,
361         -id       => $name,
362     );
363         return $budget_authcat_dropbox;
364 }
365
366 # -------------------------------------------------------------------
367 sub GetBudgetAuthCats  {
368         my @auth_cats;
369         my $value;
370         my $dbh = C4::Context->dbh;
371         my $sth = $dbh->prepare(
372                 "SELECT distinct(category)
373             FROM authorised_values where category like 'Asort%'
374             ORDER BY category"
375         );
376         $sth->execute();
377     while ( my $value = $sth->fetchrow_array ) {
378         push @auth_cats, $value;
379     }
380     my @loop_data = ();    # initialize an array to hold your loop
381     while (@auth_cats) {
382         my %row_data;      # get a fresh hash for the row data
383         $row_data{authcat} = shift @auth_cats;
384         push( @loop_data, \%row_data );
385     }
386     return @loop_data;
387 }
388
389 # -------------------------------------------------------------------
390 sub GetAuthvalueDropbox {
391         my ( $name, $authcat, $default ) = @_;
392         my @authorised_values;
393         my %authorised_lib;
394         my $value;
395         my $dbh = C4::Context->dbh;
396         my $sth = $dbh->prepare(
397                 "SELECT authorised_value,lib
398             FROM authorised_values
399             WHERE category = ?
400             ORDER BY  lib"
401         );
402         $sth->execute( $authcat );
403
404         push @authorised_values, '';
405         while (my ($value, $lib) = $sth->fetchrow_array) {
406                 push @authorised_values, $value;
407                 $authorised_lib{$value} = $lib;
408         }
409
410     return 0 if keys(%authorised_lib) == 0;
411
412     my $budget_authvalue_dropbox = CGI::scrolling_list(
413         -values   => \@authorised_values,
414         -labels   => \%authorised_lib,
415         -default  => $default,
416         -override => 1,
417         -size     => 1,
418         -multiple => 0,
419         -name     => $name,
420         -id       => $name,
421     );
422
423     return $budget_authvalue_dropbox
424 }
425
426 # -------------------------------------------------------------------
427 sub GetBudgetPeriodsDropbox {
428     my ($budget_period_id) = @_;
429         my %labels;
430         my @values;
431         my ($active, $periods) = GetBudgetPeriods();
432         foreach my $r (@$periods) {
433                 $labels{"$r->{budget_period_id}"} = $r->{budget_period_description};
434                 push @values, $r->{budget_period_id};
435         }
436
437         # if no buget_id is passed then its an add
438         my $budget_period_dropbox = CGI::scrolling_list(
439                 -name    => 'budget_period_id',
440                 -values  => \@values,
441                 -default => $budget_period_id ? $budget_period_id :  $active,
442                 -size    => 1,
443                 -labels  => \%labels,
444         );
445         return $budget_period_dropbox;
446 }
447
448 # -------------------------------------------------------------------
449 sub GetBudgetPeriods {
450         my $dbh = C4::Context->dbh;
451         my $sth = $dbh->prepare(qq|
452         SELECT *
453          FROM aqbudgetperiods
454          ORDER BY budget_period_startdate, budget_period_enddate |
455         );
456         $sth->execute();
457         my @results;
458         my $active;
459         while (my $data = $sth->fetchrow_hashref) {
460                 if ($data->{'budget_period_active'} == 1) {
461                         $active = $data->{'budget_period_id'};
462                 }
463                 push(@results, $data);
464         }
465         $sth->finish;
466         return ($active, \@results);
467 }
468
469 # -------------------------------------------------------------------
470 sub GetBudgetPeriod {
471         my ($budget_period_id) = @_;
472         my $dbh = C4::Context->dbh;
473         ## $total = number of records linked to the record that must be deleted
474         my $total = 0;
475         ## get information about the record that will be deleted
476         my $sth;
477         if ($budget_period_id gt 0) {
478                 $sth = $dbh->prepare( qq|
479               SELECT      *
480                 FROM aqbudgetperiods
481                 WHERE budget_period_id=? |
482                 );
483                 $sth->execute($budget_period_id);
484         } else {         # ACTIVE BUDGET
485                 $sth = $dbh->prepare(qq|
486                           SELECT      *
487                 FROM aqbudgetperiods
488                 WHERE budget_period_active=1 |
489                 );
490                 $sth->execute();
491         }
492         my $data = $sth->fetchrow_hashref;
493         $sth->finish;
494         return $data;
495 }
496
497 # -------------------------------------------------------------------
498 sub DelBudgetPeriod() {
499         my ($budget_period_id) = @_;
500         my $dbh = C4::Context->dbh;
501           ; ## $total = number of records linked to the record that must be deleted
502     my $total = 0;
503
504         ## get information about the record that will be deleted
505         my $sth = $dbh->prepare(qq|
506                 SELECT     budget_period_id
507                  , budget_period_startdate
508                  , budget_period_enddate
509                  , budget_period_amount
510                  , budget_period_ref
511                  , budget_period_description
512          FROM aqbudgetperiods
513          WHERE budget_period_id=? |
514         );
515         $sth->execute($budget_period_id);
516         my $data = $sth->fetchrow_hashref;
517         $sth->finish;
518 }
519
520 # -------------------------------------------------------------------
521 sub ModBudgetPeriod() {
522         my ($budget_period_id) = @_;
523         my $dbh = C4::Context->dbh
524           ; ## $total = number of records linked to the record that must be deleted       my $total = 0;
525
526         ## get information about the record that will be deleted
527         my $sth = $dbh->prepare("
528             SELECT     budget_period_id
529                  , budget_period_startdate
530                  , budget_period_enddate
531                  , budget_period_amount
532                  , budget_period_ref
533                  , budget_period_description
534         FROM aqbudgetperiods
535         WHERE budget_period_id=?;"
536         );
537         $sth->execute($budget_period_id);
538         my $data = $sth->fetchrow_hashref;
539         $sth->finish;
540 }
541
542 # -------------------------------------------------------------------
543 sub GetBudgetHierarchy {
544         my ($budget_period_id, $branchcode, $owner) = @_;
545         my @bind_params;
546         my $dbh   = C4::Context->dbh;
547         my $query = qq|
548                     SELECT *
549                     FROM aqbudgets
550                     JOIN aqbudgetperiods USING (budget_period_id)
551                     WHERE budget_period_active=1 |;
552     # show only period X if requested
553     if ($budget_period_id) {
554         $query .= "AND aqbudgets.budget_period_id = ?";
555         push @bind_params, $budget_period_id;
556     }
557         # show only budgets owned by me, my branch or everyone
558     if ($owner) {
559         if ($branchcode) {
560             $query .= " AND (budget_owner_id = ? OR budget_branchcode = ? OR (budget_branchcode IS NULL AND budget_owner_id IS NULL))";
561             push @bind_params, $owner;
562             push @bind_params, $branchcode;
563         } else {
564             $query .= ' AND budget_owner_id = ? OR budget_owner_id IS NULL';
565             push @bind_params, $owner;
566         }
567     } else {
568         if ($branchcode) {
569             $query .= " AND (budget_branchcode =? or budget_branchcode is NULL)";
570             push @bind_params, $branchcode;
571         }
572     }
573         my $sth = $dbh->prepare($query);
574         $sth->execute(@bind_params);
575         my $results = $sth->fetchall_arrayref({});
576         my @res     = @$results;
577         my $i = 0;
578         while (1) {
579                 my $depth_cnt = 0;
580                 foreach my $r (@res) {
581                         my @child;
582                         # look for children
583                         $r->{depth} = '0' if !defined $r->{budget_parent_id};
584                         foreach my $r2 (@res) {
585                                 if (defined $r2->{budget_parent_id}
586                                         && $r2->{budget_parent_id} == $r->{budget_id}) {
587                                         push @child, $r2->{budget_id};
588                                         $r2->{depth} = ($r->{depth} + 1) if defined $r->{depth};
589                                 }
590                         }
591                         $r->{child} = \@child if scalar @child > 0;    # add the child
592                         $depth_cnt++ if !defined $r->{'depth'};
593                 }
594                 last if ($depth_cnt == 0 || $i == 100);
595                 $i++;
596         }
597
598         # look for top parents 1st
599         my @sort;
600         my ($i, $depth_count) = 0;
601         while (1) {
602                 my $children = 0;
603                 foreach my $r (@res) {
604                         if ($r->{depth} == $depth_count) {
605                                 $children++ if (ref $r->{child} eq 'ARRAY');
606
607                                 # find the parent id element_id and insert it after
608                                 my $i2 = 0;
609                                 my $parent;
610                                 if ($depth_count > 0) {
611
612                                         # add indent
613                                         my $depth = $r->{depth} * 2;
614                                         my $space = pack "A[$depth]";
615                                         $r->{budget_code_indent} = $space . $r->{budget_code};
616                                         $r->{budget_name_indent} = $space . $r->{budget_name};
617                                         foreach my $r3 (@sort) {
618                                                 if ($r3->{budget_id} == $r->{budget_parent_id}) {
619                                                         $parent = $i2;
620                                                         last;
621                                                 }
622                                                 $i2++;
623                                         }
624                                 } else {
625                                         $r->{budget_code_indent} = $r->{budget_code};
626                                         $r->{budget_name_indent} = $r->{budget_name};
627                                 }
628
629                                 if (defined $parent) {
630                                         splice @sort, ($parent + 1), 0, $r;
631                                 } else {
632                                         push @sort, $r;
633                                 }
634                         }
635
636                         $i++;
637                 }    # --------------foreach
638                 $depth_count++;
639                 last if $children == 0;
640         }
641
642 # add budget-percent and allocation, and flags for html-template
643         foreach my $r (@sort) {
644                 my $subs_href = $r->{'child'};
645         my @subs_arr = @$subs_href if defined $subs_href;
646
647         my $moo = $r->{'budget_code_indent'};
648         $moo =~ s/\ /\&nbsp\;/g;
649         $r->{'budget_code_indent'} =  $moo;
650
651         my $moo = $r->{'budget_name_indent'};
652         $moo =~ s/\ /\&nbsp\;/g;
653         $r->{'budget_name_indent'} = $moo;
654
655         $r->{'budget_spent'}       = GetBudgetSpent( $r->{'budget_id'} );
656
657 #        $budget->{'budget_alloc'}       = sprintf( "%.2f", $budget->{'budget_alloc'} - $budget->{'budget_amount  alloc'} );
658 #        $budget->{'budget_alloc'} = sprintf( "%.2f", $budget->{'budget_alloc'} );
659
660         $r->{'budget_amount_total'} =  $r->{'budget_amount'} + $r->{'budget_amount_sublevel'}  ;
661 #           $r->{budget_alloc} = $r->{'budget_amount'} - $r->{'budget_amount_sublevel'}  ;
662
663           #  $r->{'budget_amount_sublevel'}  ;
664
665         # foreach sub-levels
666         my $unalloc_count ;
667
668                 foreach my $sub (@subs_arr) {
669                         my $sub_budget = GetBudget($sub);
670                         # $r->{budget_spent_sublevel} += $bud->{'budget_amount'} ;
671
672                         $r->{budget_spent_sublevel} +=    GetBudgetSpent( $sub_budget->{'budget_id'} );
673                         $unalloc_count +=   $sub_budget->{'budget_amount'} + $sub_budget->{'budget_amount_sublevel'};
674                 }
675
676             $r->{budget_unalloc_sublevel} =  $r->{'budget_amount_sublevel'}   -   $unalloc_count;
677
678         #                 (($r->{'budget_amount'} - $r->{'budget_alloc'}) /  $r->{'budget_amount'}) * 100;
679
680 =c
681 #        my $percent =     $r->{'budget_amount'}  ? (  $r->{'budget_alloc'} / $r->{'budget_amount'} ) * 100 :  0;
682  #       my $spent_percent = ( $r->{'budget_spent'} / $r->{'budget_amount'} ) * 100 if $r->{'budget_amount'};
683
684         #                 (($r->{'budget_amount'} - $r->{'budget_alloc'}) /  $r->{'budget_amount'}) * 100;
685 #        my $percent = ( $r->{'budget_alloc'} / $r->{'budget_amount'} ) * 100 if $r->{'budget_amount'};
686 #        my $spent_percent = ( $r->{'budget_spent'} / $r->{'budget_amount'} ) * 100 if $r->{'budget_amount'};
687                 if ($percent == 0) {
688                         $r->{budget_alloc_none} = 1;
689                 } elsif ($percent == 100) {
690                         $r->{budget_alloc_full} = 1
691
692                 } else {
693                         $r->{budget_alloc_percent} =    sprintf("%00d", $percent);
694                 }
695 =cut
696
697         if ( scalar  @subs_arr == 0  && $r->{budget_amount_sublevel} > 0 ) {
698             $r->{warn_no_subs} = 1;
699         }
700         }
701         return \@sort;
702 }
703
704 # -------------------------------------------------------------------
705 sub AddBudget {
706 my ($budget) = @_;
707 my $dbh        = C4::Context->dbh;
708         my $query = qq|
709     INSERT INTO aqbudgets
710     SET budget_code         = ?,
711         budget_period_id    = ?,
712         budget_parent_id    = ?,
713         budget_name         = ?,
714         budget_branchcode   = ?,
715         budget_amount       = ?,
716         budget_amount_sublevel       = ?,
717         budget_encumb       = ?,
718         budget_expend       = ?,
719         budget_notes        = ?,
720         sort1_authcat       = ?,
721         sort2_authcat       = ?,
722         budget_owner_id     = ?,
723         budget_permission   = ?
724     |;
725         my $sth = $dbh->prepare($query);
726         $sth->execute(
727         $budget->{'budget_code'}        ? $budget->{'budget_code'} : undef,
728         $budget->{'budget_period_id'}   ? $budget->{'budget_period_id'} : undef,
729         $budget->{'budget_parent_id'}   ? $budget->{'budget_parent_id'} : undef,
730         $budget->{'budget_name'}        ? $budget->{'budget_name'} : undef,
731         $budget->{'budget_branchcode'}  ? $budget->{'budget_branchcode'} : undef,
732         $budget->{'budget_amount'}      ? $budget->{'budget_amount'} : undef,
733         $budget->{'budget_amount_sublevel'}      ? $budget->{'budget_amount_sublevel'} : undef,
734         $budget->{'budget_encumb'}      ? $budget->{'budget_encumb'} : undef,
735         $budget->{'budget_expend'}      ? $budget->{'budget_expend'} : undef,
736         $budget->{'budget_notes'}       ? $budget->{'budget_notes'} : undef,
737         $budget->{'sort1_authcat'}      ? $budget->{'sort1_authcat'} : undef,
738         $budget->{'sort2_authcat'}      ? $budget->{'sort2_authcat'} : undef,
739         $budget->{'budget_owner_id'}    ? $budget->{'budget_owner_id'} : undef,
740         $budget->{'budget_permission'}  ? $budget->{'budget_permission'} : undef,
741         );
742         $sth->finish;
743 }
744
745 # -------------------------------------------------------------------
746 sub ModBudget {
747     my ($budget) = @_;
748     my $dbh      = C4::Context->dbh;
749         my $query = qq|
750     UPDATE aqbudgets
751     SET budget_code         = ?,
752         budget_period_id    = ?,
753         budget_parent_id    = ?,
754         budget_name         = ?,
755         budget_branchcode   = ?,
756         budget_amount       = ?,
757         budget_amount_sublevel       = ?,
758         budget_encumb       = ?,
759         budget_expend       = ?,
760         budget_notes        = ?,
761         sort1_authcat       = ?,
762         sort2_authcat       = ?,
763         budget_owner_id     = ?,
764         budget_permission   = ?
765     WHERE budget_id = ?
766     |;
767
768         my $sth = $dbh->prepare($query);
769     $sth->execute(
770         $budget->{'budget_code'}        ? $budget->{'budget_code'} : undef,
771         $budget->{'budget_period_id'}   ? $budget->{'budget_period_id'} : undef,
772         $budget->{'budget_parent_id'}   ? $budget->{'budget_parent_id'} : undef,
773         $budget->{'budget_name'}        ? $budget->{'budget_name'} : undef,
774         $budget->{'budget_branchcode'}  ? $budget->{'budget_branchcode'} : undef,
775         $budget->{'budget_amount'}      ? $budget->{'budget_amount'} : undef,
776         $budget->{'budget_amount_sublevel'}      ? $budget->{'budget_amount_sublevel'} : undef,
777         $budget->{'budget_encumb'}      ? $budget->{'budget_encumb'} : undef,
778         $budget->{'budget_expend'}      ? $budget->{'budget_expend'} : undef,
779         $budget->{'budget_notes'}       ? $budget->{'budget_notes'} : undef,
780         $budget->{'sort1_authcat'}      ? $budget->{'sort1_authcat'} : undef,
781         $budget->{'sort2_authcat'}      ? $budget->{'sort2_authcat'} : undef,
782         $budget->{'budget_owner_id'}    ? $budget->{'budget_owner_id'} : undef,
783         $budget->{'budget_permission'}  ? $budget->{'budget_permission'} : undef,
784         $budget->{'budget_id'},
785     );
786     $sth->finish;
787 }
788
789 # -------------------------------------------------------------------
790 sub DelBudget {
791         my ($budget_id) = @_;
792         my $dbh         = C4::Context->dbh;
793         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
794         my $rc          = $sth->execute($budget_id);
795         $sth->finish;
796         return $rc;
797 }
798
799 =back
800
801 =head2 FUNCTIONS ABOUT BUDGETS
802
803 =over 2
804
805 =cut
806
807 =head3 GetBudget
808
809 =over 4
810
811 &GetBudget($budget_id);
812
813 get a specific budget
814
815 =back
816
817 =cut
818
819 # -------------------------------------------------------------------
820 sub GetBudget {
821     my ( $budget_id ) = @_;
822     my $dbh = C4::Context->dbh;
823     my $query;
824     my $query = "
825         SELECT *
826         FROM   aqbudgets
827         WHERE  budget_id=?
828         ";
829     my $sth = $dbh->prepare($query);
830     $sth->execute( $budget_id );
831     my $result = $sth->fetchrow_hashref;
832     return $result;
833 }
834
835 =head3 GetBudgets
836
837 =over 4
838
839 &GetBudget($budget_id);
840
841 gets all budgets
842
843 =back
844
845 =cut
846
847 # -------------------------------------------------------------------
848 sub GetBudgets {
849     my ($active) = @_;
850     my $dbh      = C4::Context->dbh;
851     my $q        = "SELECT * from aqbudgets";
852     my $row;
853     my $sth;
854     unless ($active) {
855         $sth = $dbh->prepare($q);
856         $sth->execute();
857     } else {
858         $q   = "select budget_period_id from aqbudgetperiods where budget_period_active = 1 ";
859         $sth = $dbh->prepare($q);
860         $sth->execute();
861         $row = $sth->fetchrow_hashref();
862         $q   = "select * from aqbudgets  WHERE budget_period_id =? ";
863         $sth = $dbh->prepare($q);
864         $sth->execute( $row->{'budget_period_id'} );
865     }
866     my $results = $sth->fetchall_arrayref( {} );
867     $sth->finish;
868     return $results;
869 }
870
871 # -------------------------------------------------------------------
872
873 =head3 GetCurrencies
874
875 @currencies = &GetCurrencies;
876
877 Returns the list of all known currencies.
878
879 C<$currencies> is a array; its elements are references-to-hash, whose
880 keys are the fields from the currency table in the Koha database.
881
882 =cut
883
884 sub GetCurrencies {
885     my $dbh   = C4::Context->dbh;
886     my $query = "
887         SELECT *
888         FROM   currency
889     ";
890     my $sth = $dbh->prepare($query);
891     $sth->execute;
892     my @results = ();
893     while ( my $data = $sth->fetchrow_hashref ) {
894         push( @results, $data );
895     }
896     $sth->finish;
897     return @results;
898 }
899
900 # -------------------------------------------------------------------
901
902 sub GetCurrency {
903     my $dbh   = C4::Context->dbh;
904     my $query = "
905         SELECT * FROM currency where active = '1'    ";
906     my $sth = $dbh->prepare($query);
907     $sth->execute;
908     my $r = $sth->fetchrow_hashref;
909     $sth->finish;
910     return $r;
911 }
912
913 =head3 ModCurrencies
914
915 &ModCurrencies($currency, $newrate);
916
917 Sets the exchange rate for C<$currency> to be C<$newrate>.
918
919 =cut
920
921 sub ModCurrencies {
922     my ( $currency, $rate ) = @_;
923     my $dbh   = C4::Context->dbh;
924     my $query = qq|
925         UPDATE currency
926         SET    rate=?
927         WHERE  currency=? |;
928     my $sth = $dbh->prepare($query);
929     $sth->execute( $rate, $currency );
930 }
931
932 # -------------------------------------------------------------------
933
934 =head3 ConvertCurrency
935
936 $foreignprice = &ConvertCurrency($currency, $localprice);
937
938 Converts the price C<$localprice> to foreign currency C<$currency> by
939 dividing by the exchange rate, and returns the result.
940
941 If no exchange rate is found,e is one
942 to one.
943
944 =cut
945
946 sub ConvertCurrency {
947     my ( $currency, $price ) = @_;
948     my $dbh   = C4::Context->dbh;
949     my $query = "
950         SELECT rate
951         FROM   currency
952         WHERE  currency=?
953     ";
954     my $sth = $dbh->prepare($query);
955     $sth->execute($currency);
956     my $cur = ( $sth->fetchrow_array() )[0];
957     unless ($cur) {
958         $cur = 1;
959     }
960     return ( $price / $cur );
961 }
962
963 END { }    # module clean-up code here (global destructor)
964
965 1;
966 __END__
967
968 =back
969
970 =head1 AUTHOR
971
972 Koha Developement team <info@koha.org>
973
974 =cut