Bug 15084: Replace C4::Budgets::GetCurrencies with Koha::Acquisition::Currencies...
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use C4::Context;
23 use Koha::Database;
24 use C4::Debug;
25 use vars qw($VERSION @ISA @EXPORT);
26
27 BEGIN {
28         # set the version for version checking
29     $VERSION = 3.07.00.049;
30         require Exporter;
31         @ISA    = qw(Exporter);
32         @EXPORT = qw(
33
34         &GetBudget
35         &GetBudgetByOrderNumber
36         &GetBudgetByCode
37         &GetBudgets
38         &GetBudgetHierarchy
39             &AddBudget
40         &ModBudget
41         &DelBudget
42         &GetBudgetSpent
43         &GetBudgetOrdered
44         &GetBudgetName
45         &GetPeriodsCount
46         GetBudgetHierarchySpent
47         GetBudgetHierarchyOrdered
48
49         &GetBudgetUsers
50         &ModBudgetUsers
51         &CanUserUseBudget
52         &CanUserModifyBudget
53
54             &GetBudgetPeriod
55         &GetBudgetPeriods
56         &ModBudgetPeriod
57         &AddBudgetPeriod
58             &DelBudgetPeriod
59
60         &ModBudgetPlan
61
62         &ConvertCurrency
63         
64                 &GetBudgetsPlanCell
65         &AddBudgetPlanValue
66         &GetBudgetAuthCats
67         &BudgetHasChildren
68         &CheckBudgetParent
69         &CheckBudgetParentPerm
70
71         &HideCols
72         &GetCols
73         );
74 }
75
76 # ----------------------------BUDGETS.PM-----------------------------";
77
78
79 =head1 FUNCTIONS ABOUT BUDGETS
80
81 =cut
82
83 sub HideCols {
84     my ( $authcat, @hide_cols ) = @_;
85     my $dbh = C4::Context->dbh;
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 sub AddBudgetPeriod {
134     my ($budgetperiod) = @_;
135     return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
136
137     my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
138     return $resultset->create($budgetperiod)->id;
139 }
140 # -------------------------------------------------------------------
141 sub GetPeriodsCount {
142     my $dbh = C4::Context->dbh;
143     my $sth = $dbh->prepare("
144         SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
145     $sth->execute();
146     my $res = $sth->fetchrow_hashref;
147     return $res->{'sum'};
148 }
149
150 # -------------------------------------------------------------------
151 sub CheckBudgetParent {
152     my ( $new_parent, $budget ) = @_;
153     my $new_parent_id = $new_parent->{'budget_id'};
154     my $budget_id     = $budget->{'budget_id'};
155     my $dbh           = C4::Context->dbh;
156     my $parent_id_tmp = $new_parent_id;
157
158     # check new-parent is not a child (or a child's child ;)
159     my $sth = $dbh->prepare(qq|
160         SELECT budget_parent_id FROM
161             aqbudgets where budget_id = ? | );
162     while (1) {
163         $sth->execute($parent_id_tmp);
164         my $res = $sth->fetchrow_hashref;
165         if ( $res->{'budget_parent_id'} == $budget_id ) {
166             return 1;
167         }
168         if ( not defined $res->{'budget_parent_id'} ) {
169             return 0;
170         }
171         $parent_id_tmp = $res->{'budget_parent_id'};
172     }
173 }
174
175 # -------------------------------------------------------------------
176 sub BudgetHasChildren {
177     my ( $budget_id  ) = @_;
178     my $dbh = C4::Context->dbh;
179     my $sth = $dbh->prepare(qq|
180        SELECT count(*) as sum FROM  aqbudgets
181         WHERE budget_parent_id = ?   | );
182     $sth->execute( $budget_id );
183     my $sum = $sth->fetchrow_hashref;
184     return $sum->{'sum'};
185 }
186
187 sub GetBudgetChildren {
188     my ( $budget_id ) = @_;
189     my $dbh = C4::Context->dbh;
190     return $dbh->selectall_arrayref(q|
191        SELECT  * FROM  aqbudgets
192         WHERE budget_parent_id = ?
193     |, { Slice => {} }, $budget_id );
194 }
195
196 sub SetOwnerToFundHierarchy {
197     my ( $budget_id, $borrowernumber ) = @_;
198
199     my $budget = GetBudget( $budget_id );
200     $budget->{budget_owner_id} = $borrowernumber;
201     ModBudget( $budget );
202     my $children = GetBudgetChildren( $budget_id );
203     for my $child ( @$children ) {
204         SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
205     }
206 }
207
208 # -------------------------------------------------------------------
209 sub GetBudgetsPlanCell {
210     my ( $cell, $period, $budget ) = @_;
211     my ($actual, $sth);
212     my $dbh = C4::Context->dbh;
213     if ( $cell->{'authcat'} eq 'MONTHS' ) {
214         # get the actual amount
215         $sth = $dbh->prepare( qq|
216
217             SELECT SUM(ecost) AS actual FROM aqorders
218                 WHERE    budget_id = ? AND
219                 entrydate like "$cell->{'authvalue'}%"  |
220         );
221         $sth->execute( $cell->{'budget_id'} );
222     } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
223         # get the actual amount
224         $sth = $dbh->prepare( qq|
225
226             SELECT SUM(ecost) FROM aqorders
227                 LEFT JOIN aqorders_items
228                 ON (aqorders.ordernumber = aqorders_items.ordernumber)
229                 LEFT JOIN items
230                 ON (aqorders_items.itemnumber = items.itemnumber)
231                 WHERE budget_id = ? AND homebranch = ? |          );
232
233         $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
234     } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
235         # get the actual amount
236         $sth = $dbh->prepare(  qq|
237
238             SELECT SUM( ecost *  quantity) AS actual
239                 FROM aqorders JOIN biblioitems
240                 ON (biblioitems.biblionumber = aqorders.biblionumber )
241                 WHERE aqorders.budget_id = ? and itemtype  = ? |
242         );
243         $sth->execute(  $cell->{'budget_id'},
244                         $cell->{'authvalue'} );
245     }
246     # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
247     else {
248         # get the actual amount
249         $sth = $dbh->prepare( qq|
250
251         SELECT  SUM(ecost * quantity) AS actual
252             FROM aqorders
253             JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
254             WHERE  aqorders.budget_id = ? AND
255                 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
256                 (aqbudgets.sort2_authcat = ? AND sort2 =?))    |
257         );
258         $sth->execute(  $cell->{'budget_id'},
259                         $budget->{'sort1_authcat'},
260                         $cell->{'authvalue'},
261                         $budget->{'sort2_authcat'},
262                         $cell->{'authvalue'}
263         );
264     }
265     $actual = $sth->fetchrow_array;
266
267     # get the estimated amount
268     $sth = $dbh->prepare( qq|
269
270         SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
271             WHERE budget_period_id = ? AND
272                 budget_id = ? AND
273                 authvalue = ? AND
274                 authcat = ?         |
275     );
276     $sth->execute(  $cell->{'budget_period_id'},
277                     $cell->{'budget_id'},
278                     $cell->{'authvalue'},
279                     $cell->{'authcat'},
280     );
281
282
283     my $res  = $sth->fetchrow_hashref;
284   #  my $display = $res->{'display'};
285     my $estimated = $res->{'estimated'};
286
287
288     return $actual, $estimated;
289 }
290
291 # -------------------------------------------------------------------
292 sub ModBudgetPlan {
293     my ( $budget_plan, $budget_period_id, $authcat ) = @_;
294     my $dbh = C4::Context->dbh;
295     foreach my $buds (@$budget_plan) {
296         my $lines = $buds->{lines};
297         my $sth = $dbh->prepare( qq|
298                 DELETE FROM aqbudgets_planning
299                     WHERE   budget_period_id   = ? AND
300                             budget_id   = ? AND
301                             authcat            = ? |
302         );
303     #delete a aqplan line of cells, then insert new cells, 
304     # these could be UPDATES rather than DEL/INSERTS...
305         $sth->execute( $budget_period_id,  $lines->[0]{budget_id}   , $authcat );
306
307         foreach my $cell (@$lines) {
308             my $sth = $dbh->prepare( qq|
309
310                 INSERT INTO aqbudgets_planning
311                      SET   budget_id     = ?,
312                      budget_period_id  = ?,
313                      authcat          = ?,
314                      estimated_amount  = ?,
315                      authvalue       = ?  |
316             );
317             $sth->execute(
318                             $cell->{'budget_id'},
319                             $cell->{'budget_period_id'},
320                             $cell->{'authcat'},
321                             $cell->{'estimated_amount'},
322                             $cell->{'authvalue'},
323             );
324         }
325     }
326 }
327
328 # -------------------------------------------------------------------
329 sub GetBudgetSpent {
330         my ($budget_id) = @_;
331         my $dbh = C4::Context->dbh;
332         my $sth = $dbh->prepare(qq|
333         SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
334             WHERE budget_id = ? AND
335             quantityreceived > 0 AND
336             datecancellationprinted IS NULL
337     |);
338         $sth->execute($budget_id);
339         my $sum =  $sth->fetchrow_array;
340
341     $sth = $dbh->prepare(qq|
342         SELECT SUM(shipmentcost) AS sum
343         FROM aqinvoices
344         WHERE shipmentcost_budgetid = ?
345           AND closedate IS NOT NULL
346     |);
347     $sth->execute($budget_id);
348     my ($shipmentcost_sum) = $sth->fetchrow_array;
349     $sum += $shipmentcost_sum;
350
351         return $sum;
352 }
353
354 # -------------------------------------------------------------------
355 sub GetBudgetOrdered {
356         my ($budget_id) = @_;
357         my $dbh = C4::Context->dbh;
358         my $sth = $dbh->prepare(qq|
359         SELECT SUM(ecost *  quantity) AS sum FROM aqorders
360             WHERE budget_id = ? AND
361             quantityreceived = 0 AND
362             datecancellationprinted IS NULL
363     |);
364         $sth->execute($budget_id);
365         my $sum =  $sth->fetchrow_array;
366
367     $sth = $dbh->prepare(qq|
368         SELECT SUM(shipmentcost) AS sum
369         FROM aqinvoices
370         WHERE shipmentcost_budgetid = ?
371           AND closedate IS NULL
372     |);
373     $sth->execute($budget_id);
374     my ($shipmentcost_sum) = $sth->fetchrow_array;
375     $sum += $shipmentcost_sum;
376
377         return $sum;
378 }
379
380 =head2 GetBudgetName
381
382   my $budget_name = &GetBudgetName($budget_id);
383
384 get the budget_name for a given budget_id
385
386 =cut
387
388 sub GetBudgetName {
389     my ( $budget_id ) = @_;
390     my $dbh         = C4::Context->dbh;
391     my $sth         = $dbh->prepare(
392         qq|
393         SELECT budget_name
394         FROM aqbudgets
395         WHERE budget_id = ?
396     |);
397
398     $sth->execute($budget_id);
399     return $sth->fetchrow_array;
400 }
401
402 # -------------------------------------------------------------------
403 sub GetBudgetAuthCats  {
404     my ($budget_period_id) = shift;
405     # now, populate the auth_cats_loop used in the budget planning button
406     # we must retrieve all auth values used by at least one budget
407     my $dbh = C4::Context->dbh;
408     my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
409     $sth->execute($budget_period_id);
410     my %authcats;
411     while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
412         $authcats{$sort1_authcat}=1;
413         $authcats{$sort2_authcat}=1;
414     }
415     my @auth_cats_loop;
416     foreach (sort keys %authcats) {
417         push @auth_cats_loop,{ authcat => $_ };
418     }
419     return \@auth_cats_loop;
420 }
421
422 # -------------------------------------------------------------------
423 sub GetBudgetPeriods {
424         my ($filters,$orderby) = @_;
425
426     my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
427     $rs = $rs->search( $filters, { order_by => $orderby } );
428     $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
429     return [ $rs->all ];
430 }
431 # -------------------------------------------------------------------
432 sub GetBudgetPeriod {
433         my ($budget_period_id) = @_;
434         my $dbh = C4::Context->dbh;
435         ## $total = number of records linked to the record that must be deleted
436         my $total = 0;
437         ## get information about the record that will be deleted
438         my $sth;
439         if ($budget_period_id) {
440                 $sth = $dbh->prepare( qq|
441               SELECT      *
442                 FROM aqbudgetperiods
443                 WHERE budget_period_id=? |
444                 );
445                 $sth->execute($budget_period_id);
446         } else {         # ACTIVE BUDGET
447                 $sth = $dbh->prepare(qq|
448                           SELECT      *
449                 FROM aqbudgetperiods
450                 WHERE budget_period_active=1 |
451                 );
452                 $sth->execute();
453         }
454         my $data = $sth->fetchrow_hashref;
455         return $data;
456 }
457
458 # -------------------------------------------------------------------
459 sub DelBudgetPeriod{
460         my ($budget_period_id) = @_;
461         my $dbh = C4::Context->dbh;
462           ; ## $total = number of records linked to the record that must be deleted
463     my $total = 0;
464
465         ## get information about the record that will be deleted
466         my $sth = $dbh->prepare(qq|
467                 DELETE 
468          FROM aqbudgetperiods
469          WHERE budget_period_id=? |
470         );
471         return $sth->execute($budget_period_id);
472 }
473
474 # -------------------------------------------------------------------
475 sub ModBudgetPeriod {
476     my ($budget_period) = @_;
477     my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
478     return unless($result);
479
480     $result = $result->update($budget_period);
481     return $result->in_storage;
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.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
491                     FROM aqbudgets 
492                     JOIN aqbudgetperiods USING (budget_period_id)|;
493                         
494         my @where_strings;
495     # show only period X if requested
496     if ($budget_period_id) {
497         push @where_strings," aqbudgets.budget_period_id = ?";
498         push @bind_params, $budget_period_id;
499     }
500         # show only budgets owned by me, my branch or everyone
501     if ($owner) {
502         if ($branchcode) {
503             push @where_strings,
504             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="")))};
505             push @bind_params, ( $owner, $branchcode );
506         } else {
507             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
508             push @bind_params, $owner;
509         }
510     } else {
511         if ($branchcode) {
512             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
513             push @bind_params, $branchcode;
514         }
515     }
516         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
517         $debug && warn $query,join(",",@bind_params);
518         my $sth = $dbh->prepare($query);
519         $sth->execute(@bind_params);
520
521     my %links;
522     # create hash with budget_id has key
523     while ( my $data = $sth->fetchrow_hashref ) {
524         $links{ $data->{'budget_id'} } = $data;
525     }
526
527     # link child to parent
528     my @first_parents;
529     foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
530         my $child = $links{$budget->{budget_id}};
531         if ( $child->{'budget_parent_id'} ) {
532             my $parent = $links{ $child->{'budget_parent_id'} };
533             if ($parent) {
534                 unless ( $parent->{'children'} ) {
535                     # init child arrayref
536                     $parent->{'children'} = [];
537                 }
538                 # add as child
539                 push @{ $parent->{'children'} }, $child;
540             }
541         } else {
542             push @first_parents, $child;
543         }
544     }
545
546     my @sort = ();
547     foreach my $first_parent (@first_parents) {
548         _add_budget_children(\@sort, $first_parent);
549     }
550
551     foreach my $budget (@sort) {
552         $budget->{budget_spent}   = GetBudgetSpent( $budget->{budget_id} );
553         $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
554         $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
555         $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
556     }
557     return \@sort;
558 }
559
560 # Recursive method to add a budget and its chidren to an array
561 sub _add_budget_children {
562     my $res = shift;
563     my $budget = shift;
564     push @$res, $budget;
565     my $children = $budget->{'children'} || [];
566     return unless @$children; # break recursivity
567     foreach my $child (@$children) {
568         _add_budget_children($res, $child);
569     }
570 }
571
572 # -------------------------------------------------------------------
573
574 sub AddBudget {
575     my ($budget) = @_;
576     return unless ($budget);
577
578     my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
579     return $resultset->create($budget)->id;
580 }
581
582 # -------------------------------------------------------------------
583 sub ModBudget {
584     my ($budget) = @_;
585     my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
586     return unless($result);
587
588     $result = $result->update($budget);
589     return $result->in_storage;
590 }
591
592 # -------------------------------------------------------------------
593 sub DelBudget {
594         my ($budget_id) = @_;
595         my $dbh         = C4::Context->dbh;
596         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
597         my $rc          = $sth->execute($budget_id);
598         return $rc;
599 }
600
601
602 =head2 GetBudget
603
604   &GetBudget($budget_id);
605
606 get a specific budget
607
608 =cut
609
610 # -------------------------------------------------------------------
611 sub GetBudget {
612     my ( $budget_id ) = @_;
613     my $dbh = C4::Context->dbh;
614     my $query = "
615         SELECT *
616         FROM   aqbudgets
617         WHERE  budget_id=?
618         ";
619     my $sth = $dbh->prepare($query);
620     $sth->execute( $budget_id );
621     my $result = $sth->fetchrow_hashref;
622     return $result;
623 }
624
625 =head2 GetBudgetByOrderNumber
626
627   &GetBudgetByOrderNumber($ordernumber);
628
629 get a specific budget by order number
630
631 =cut
632
633 # -------------------------------------------------------------------
634 sub GetBudgetByOrderNumber {
635     my ( $ordernumber ) = @_;
636     my $dbh = C4::Context->dbh;
637     my $query = "
638         SELECT aqbudgets.*
639         FROM   aqbudgets, aqorders
640         WHERE  ordernumber=?
641         AND    aqorders.budget_id = aqbudgets.budget_id
642         ";
643     my $sth = $dbh->prepare($query);
644     $sth->execute( $ordernumber );
645     my $result = $sth->fetchrow_hashref;
646     return $result;
647 }
648
649 =head2 GetBudgetByCode
650
651     my $budget = &GetBudgetByCode($budget_code);
652
653 Retrieve all aqbudgets fields as a hashref for the budget that has
654 given budget_code
655
656 =cut
657
658 sub GetBudgetByCode {
659     my ( $budget_code ) = @_;
660
661     my $dbh = C4::Context->dbh;
662     my $query = qq{
663         SELECT *
664         FROM aqbudgets
665         WHERE budget_code = ?
666         ORDER BY budget_id DESC
667         LIMIT 1
668     };
669     my $sth = $dbh->prepare( $query );
670     $sth->execute( $budget_code );
671     return $sth->fetchrow_hashref;
672 }
673
674 =head2 GetBudgetHierarchySpent
675
676   my $spent = GetBudgetHierarchySpent( $budget_id );
677
678 Gets the total spent of the level and sublevels of $budget_id
679
680 =cut
681
682 sub GetBudgetHierarchySpent {
683     my ( $budget_id ) = @_;
684     my $dbh = C4::Context->dbh;
685     my $children_ids = $dbh->selectcol_arrayref(q|
686         SELECT budget_id
687         FROM   aqbudgets
688         WHERE  budget_parent_id = ?
689     |, {}, $budget_id );
690
691     my $total_spent = GetBudgetSpent( $budget_id );
692     for my $child_id ( @$children_ids ) {
693         $total_spent += GetBudgetHierarchySpent( $child_id );
694     }
695     return $total_spent;
696 }
697
698 =head2 GetBudgetHierarchyOrdered
699
700   my $ordered = GetBudgetHierarchyOrdered( $budget_id );
701
702 Gets the total ordered of the level and sublevels of $budget_id
703
704 =cut
705
706 sub GetBudgetHierarchyOrdered {
707     my ( $budget_id ) = @_;
708     my $dbh = C4::Context->dbh;
709     my $children_ids = $dbh->selectcol_arrayref(q|
710         SELECT budget_id
711         FROM   aqbudgets
712         WHERE  budget_parent_id = ?
713     |, {}, $budget_id );
714
715     my $total_ordered = GetBudgetOrdered( $budget_id );
716     for my $child_id ( @$children_ids ) {
717         $total_ordered += GetBudgetHierarchyOrdered( $child_id );
718     }
719     return $total_ordered;
720 }
721
722 =head2 GetBudgets
723
724   &GetBudgets($filter, $order_by);
725
726 gets all budgets
727
728 =cut
729
730 # -------------------------------------------------------------------
731 sub GetBudgets {
732     my ($filters, $orderby) = @_;
733     $orderby = 'budget_name' unless($orderby);
734
735     my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
736     $rs = $rs->search( $filters, { order_by => $orderby } );
737     $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
738     return [ $rs->all  ];
739 }
740
741 =head2 GetBudgetUsers
742
743     my @borrowernumbers = &GetBudgetUsers($budget_id);
744
745 Return the list of borrowernumbers linked to a budget
746
747 =cut
748
749 sub GetBudgetUsers {
750     my ($budget_id) = @_;
751
752     my $dbh = C4::Context->dbh;
753     my $query = qq{
754         SELECT borrowernumber
755         FROM aqbudgetborrowers
756         WHERE budget_id = ?
757     };
758     my $sth = $dbh->prepare($query);
759     $sth->execute($budget_id);
760
761     my @borrowernumbers;
762     while (my ($borrowernumber) = $sth->fetchrow_array) {
763         push @borrowernumbers, $borrowernumber
764     }
765
766     return @borrowernumbers;
767 }
768
769 =head2 ModBudgetUsers
770
771     &ModBudgetUsers($budget_id, @borrowernumbers);
772
773 Modify the list of borrowernumbers linked to a budget
774
775 =cut
776
777 sub ModBudgetUsers {
778     my ($budget_id, @budget_users_id) = @_;
779
780     return unless $budget_id;
781
782     my $dbh = C4::Context->dbh;
783     my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
784     my $sth = $dbh->prepare($query);
785     $sth->execute($budget_id);
786
787     $query = qq{
788         INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
789         VALUES (?,?)
790     };
791     $sth = $dbh->prepare($query);
792     foreach my $borrowernumber (@budget_users_id) {
793         next unless $borrowernumber;
794         $sth->execute($budget_id, $borrowernumber);
795     }
796 }
797
798 sub CanUserUseBudget {
799     my ($borrower, $budget, $userflags) = @_;
800
801     if (not ref $borrower) {
802         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
803     }
804     if (not ref $budget) {
805         $budget = GetBudget($budget);
806     }
807
808     return 0 unless ($borrower and $budget);
809
810     if (not defined $userflags) {
811         $userflags = C4::Auth::getuserflags($borrower->{flags},
812             $borrower->{userid});
813     }
814
815     unless ($userflags->{superlibrarian}
816     || (ref $userflags->{acquisition}
817         && $userflags->{acquisition}->{budget_manage_all})
818     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
819     {
820         if (not exists $userflags->{acquisition}) {
821             return 0;
822         }
823
824         if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
825             return 0;
826         }
827
828         # Budget restricted to owner
829         if ( $budget->{budget_permission} == 1 ) {
830             if (    $budget->{budget_owner_id}
831                 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
832             {
833                 return 0;
834             }
835         }
836
837         # Budget restricted to owner, users and library
838         elsif ( $budget->{budget_permission} == 2 ) {
839             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
840
841             if (
842                 (
843                         $budget->{budget_owner_id}
844                     and $budget->{budget_owner_id} !=
845                     $borrower->{borrowernumber}
846                     or not $budget->{budget_owner_id}
847                 )
848                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
849                     @budget_users )
850                 and defined $budget->{budget_branchcode}
851                 and $budget->{budget_branchcode} ne
852                 C4::Context->userenv->{branch}
853               )
854             {
855                 return 0;
856             }
857         }
858
859         # Budget restricted to owner and users
860         elsif ( $budget->{budget_permission} == 3 ) {
861             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
862             if (
863                 (
864                         $budget->{budget_owner_id}
865                     and $budget->{budget_owner_id} !=
866                     $borrower->{borrowernumber}
867                     or not $budget->{budget_owner_id}
868                 )
869                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
870                     @budget_users )
871               )
872             {
873                 return 0;
874             }
875         }
876     }
877
878     return 1;
879 }
880
881 sub CanUserModifyBudget {
882     my ($borrower, $budget, $userflags) = @_;
883
884     if (not ref $borrower) {
885         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
886     }
887     if (not ref $budget) {
888         $budget = GetBudget($budget);
889     }
890
891     return 0 unless ($borrower and $budget);
892
893     if (not defined $userflags) {
894         $userflags = C4::Auth::getuserflags($borrower->{flags},
895             $borrower->{userid});
896     }
897
898     unless ($userflags->{superlibrarian}
899     || (ref $userflags->{acquisition}
900         && $userflags->{acquisition}->{budget_manage_all})
901     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
902     {
903         if (!CanUserUseBudget($borrower, $budget, $userflags)) {
904             return 0;
905         }
906
907         if (ref $userflags->{acquisition}
908         && !$userflags->{acquisition}->{budget_modify}) {
909             return 0;
910         }
911     }
912
913     return 1;
914 }
915
916 # -------------------------------------------------------------------
917
918 =head2 ConvertCurrency
919
920   $foreignprice = &ConvertCurrency($currency, $localprice);
921
922 Converts the price C<$localprice> to foreign currency C<$currency> by
923 dividing by the exchange rate, and returns the result.
924
925 If no exchange rate is found, e is one to one.
926
927 =cut
928
929 sub ConvertCurrency {
930     my ( $currency, $price ) = @_;
931     my $dbh   = C4::Context->dbh;
932     my $query = "
933         SELECT rate
934         FROM   currency
935         WHERE  currency=?
936     ";
937     my $sth = $dbh->prepare($query);
938     $sth->execute($currency);
939     my $cur = ( $sth->fetchrow_array() )[0];
940     unless ($cur) {
941         $cur = 1;
942     }
943     return ( $price / $cur );
944 }
945
946 sub _round {
947     my ($value, $increment) = @_;
948
949     if ($increment && $increment != 0) {
950         $value = int($value / $increment) * $increment;
951     }
952
953     return $value;
954 }
955
956 =head2 CloneBudgetPeriod
957
958   my $new_budget_period_id = CloneBudgetPeriod({
959     budget_period_id => $budget_period_id,
960     budget_period_startdate => $budget_period_startdate,
961     budget_period_enddate   => $budget_period_enddate,
962     mark_original_budget_as_inactive => 1n
963     reset_all_budgets => 1,
964   });
965
966 Clone a budget period with all budgets.
967 If the mark_origin_budget_as_inactive is set (0 by default),
968 the original budget will be marked as inactive.
969
970 If the reset_all_budgets is set (0 by default), all budget (fund)
971 amounts will be reset.
972
973 =cut
974
975 sub CloneBudgetPeriod {
976     my ($params)                  = @_;
977     my $budget_period_id          = $params->{budget_period_id};
978     my $budget_period_startdate   = $params->{budget_period_startdate};
979     my $budget_period_enddate     = $params->{budget_period_enddate};
980     my $budget_period_description = $params->{budget_period_description};
981     my $amount_change_percentage  = $params->{amount_change_percentage};
982     my $amount_change_round_increment = $params->{amount_change_round_increment};
983     my $mark_original_budget_as_inactive =
984       $params->{mark_original_budget_as_inactive} || 0;
985     my $reset_all_budgets = $params->{reset_all_budgets} || 0;
986
987     my $budget_period = GetBudgetPeriod($budget_period_id);
988
989     $budget_period->{budget_period_startdate}   = $budget_period_startdate;
990     $budget_period->{budget_period_enddate}     = $budget_period_enddate;
991     $budget_period->{budget_period_description} = $budget_period_description;
992     # The new budget (budget_period) should be active by default
993     $budget_period->{budget_period_active}    = 1;
994
995     if ($amount_change_percentage) {
996         my $total = $budget_period->{budget_period_total};
997         $total += $total * $amount_change_percentage / 100;
998         $total = _round($total, $amount_change_round_increment);
999         $budget_period->{budget_period_total} = $total;
1000     }
1001
1002     my $original_budget_period_id = $budget_period->{budget_period_id};
1003     delete $budget_period->{budget_period_id};
1004     my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1005
1006     my $budgets = GetBudgetHierarchy($budget_period_id);
1007     CloneBudgetHierarchy(
1008         {
1009             budgets              => $budgets,
1010             new_budget_period_id => $new_budget_period_id
1011         }
1012     );
1013
1014     if ($mark_original_budget_as_inactive) {
1015         ModBudgetPeriod(
1016             {
1017                 budget_period_id     => $budget_period_id,
1018                 budget_period_active => 0,
1019             }
1020         );
1021     }
1022
1023     if ( $reset_all_budgets ) {
1024         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1025         for my $budget ( @$budgets ) {
1026             $budget->{budget_amount} = 0;
1027             ModBudget( $budget );
1028         }
1029     } elsif ($amount_change_percentage) {
1030         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1031         for my $budget ( @$budgets ) {
1032             my $amount = $budget->{budget_amount};
1033             $amount += $amount * $amount_change_percentage / 100;
1034             $amount = _round($amount, $amount_change_round_increment);
1035             $budget->{budget_amount} = $amount;
1036             ModBudget( $budget );
1037         }
1038     }
1039
1040     return $new_budget_period_id;
1041 }
1042
1043 =head2 CloneBudgetHierarchy
1044
1045   CloneBudgetHierarchy({
1046     budgets => $budgets,
1047     new_budget_period_id => $new_budget_period_id;
1048   });
1049
1050 Clone a budget hierarchy.
1051
1052 =cut
1053
1054 sub CloneBudgetHierarchy {
1055     my ($params)             = @_;
1056     my $budgets              = $params->{budgets};
1057     my $new_budget_period_id = $params->{new_budget_period_id};
1058     next unless @$budgets or $new_budget_period_id;
1059
1060     my $children_of   = $params->{children_of};
1061     my $new_parent_id = $params->{new_parent_id};
1062
1063     my @first_level_budgets =
1064       ( not defined $children_of )
1065       ? map { ( not $_->{budget_parent_id} )             ? $_ : () } @$budgets
1066       : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1067
1068     # get only the columns of aqbudgets
1069     my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1070
1071     for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1072         @first_level_budgets )
1073     {
1074
1075         my $tidy_budget =
1076           { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1077               keys %$budget };
1078         my $new_budget_id = AddBudget(
1079             {
1080                 %$tidy_budget,
1081                 budget_id        => undef,
1082                 budget_parent_id => $new_parent_id,
1083                 budget_period_id => $new_budget_period_id
1084             }
1085         );
1086         CloneBudgetHierarchy(
1087             {
1088                 budgets              => $budgets,
1089                 new_budget_period_id => $new_budget_period_id,
1090                 children_of          => $budget->{budget_id},
1091                 new_parent_id        => $new_budget_id
1092             }
1093         );
1094     }
1095 }
1096
1097 =head2 MoveOrders
1098
1099   my $report = MoveOrders({
1100     from_budget_period_id => $from_budget_period_id,
1101     to_budget_period_id   => $to_budget_period_id,
1102   });
1103
1104 Move orders from one budget period to another.
1105
1106 =cut
1107
1108 sub MoveOrders {
1109     my ($params)              = @_;
1110     my $from_budget_period_id = $params->{from_budget_period_id};
1111     my $to_budget_period_id   = $params->{to_budget_period_id};
1112     my $move_remaining_unspent = $params->{move_remaining_unspent};
1113     return
1114       if not $from_budget_period_id
1115           or not $to_budget_period_id
1116           or $from_budget_period_id == $to_budget_period_id;
1117
1118     # Can't move orders to an inactive budget (budgetperiod)
1119     my $budget_period = GetBudgetPeriod($to_budget_period_id);
1120     return unless $budget_period->{budget_period_active};
1121
1122     my @report;
1123     my $dbh     = C4::Context->dbh;
1124     my $sth_update_aqorders = $dbh->prepare(
1125         q|
1126             UPDATE aqorders
1127             SET budget_id = ?
1128             WHERE ordernumber = ?
1129         |
1130     );
1131     my $sth_update_budget_amount = $dbh->prepare(
1132         q|
1133             UPDATE aqbudgets
1134             SET budget_amount = ?
1135             WHERE budget_id = ?
1136         |
1137     );
1138     my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1139     for my $from_budget (@$from_budgets) {
1140         my $new_budget_id = $dbh->selectcol_arrayref(
1141             q|
1142                 SELECT budget_id
1143                 FROM aqbudgets
1144                 WHERE budget_period_id = ?
1145                     AND budget_code = ?
1146             |, {}, $to_budget_period_id, $from_budget->{budget_code}
1147         );
1148         $new_budget_id = $new_budget_id->[0];
1149         my $new_budget = GetBudget( $new_budget_id );
1150         unless ( $new_budget ) {
1151             push @report,
1152               {
1153                 moved       => 0,
1154                 budget      => $from_budget,
1155                 error       => 'budget_code_not_exists',
1156               };
1157             next;
1158         }
1159         my $orders_to_move = C4::Acquisition::SearchOrders(
1160             {
1161                 budget_id => $from_budget->{budget_id},
1162                 pending   => 1,
1163             }
1164         );
1165
1166         my @orders_moved;
1167         for my $order (@$orders_to_move) {
1168             $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1169             push @orders_moved, $order;
1170         }
1171
1172         my $unspent_moved = 0;
1173         if ($move_remaining_unspent) {
1174             my $spent   = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1175             my $unspent = $from_budget->{budget_amount} - $spent;
1176             my $new_budget_amount = $new_budget->{budget_amount};
1177             if ( $unspent > 0 ) {
1178                 $new_budget_amount += $unspent;
1179                 $unspent_moved = $unspent;
1180             }
1181             $new_budget->{budget_amount} = $new_budget_amount;
1182             $sth_update_budget_amount->execute( $new_budget_amount,
1183                 $new_budget->{budget_id} );
1184         }
1185
1186         push @report,
1187           {
1188             budget        => $new_budget,
1189             orders_moved  => \@orders_moved,
1190             moved         => 1,
1191             unspent_moved => $unspent_moved,
1192           };
1193     }
1194     return \@report;
1195 }
1196
1197 END { }    # module clean-up code here (global destructor)
1198
1199 1;
1200 __END__
1201
1202 =head1 AUTHOR
1203
1204 Koha Development Team <http://koha-community.org/>
1205
1206 =cut