Bug 14826: (QA follow-up) POD fixes
[koha.git] / C4 / Budgets.pm
blob10f5147a3af1e372901e9f393c5bf0d021c5cd65
1 package C4::Budgets;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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>.
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use C4::Context;
23 use Koha::Database;
24 use Koha::Patrons;
25 use C4::Debug;
26 use vars qw(@ISA @EXPORT);
28 BEGIN {
29 require Exporter;
30 @ISA = qw(Exporter);
31 @EXPORT = qw(
33 &GetBudget
34 &GetBudgetByOrderNumber
35 &GetBudgetByCode
36 &GetBudgets
37 &BudgetsByActivity
38 &GetBudgetsReport
39 &GetBudgetReport
40 &GetBudgetHierarchy
41 &AddBudget
42 &ModBudget
43 &DelBudget
44 &GetBudgetSpent
45 &GetBudgetOrdered
46 &GetBudgetName
47 &GetPeriodsCount
48 GetBudgetHierarchySpent
49 GetBudgetHierarchyOrdered
51 &GetBudgetUsers
52 &ModBudgetUsers
53 &CanUserUseBudget
54 &CanUserModifyBudget
56 &GetBudgetPeriod
57 &GetBudgetPeriods
58 &ModBudgetPeriod
59 &AddBudgetPeriod
60 &DelBudgetPeriod
62 &ModBudgetPlan
64 &GetBudgetsPlanCell
65 &AddBudgetPlanValue
66 &GetBudgetAuthCats
67 &BudgetHasChildren
68 &CheckBudgetParent
69 &CheckBudgetParentPerm
71 &HideCols
72 &GetCols
76 # ----------------------------BUDGETS.PM-----------------------------";
78 =head1 FUNCTIONS ABOUT BUDGETS
80 =cut
82 sub HideCols {
83 my ( $authcat, @hide_cols ) = @_;
84 my $dbh = C4::Context->dbh;
86 my $sth1 = $dbh->prepare(
87 qq|
88 UPDATE aqbudgets_planning SET display = 0
89 WHERE authcat = ?
90 AND authvalue = ? |
92 foreach my $authvalue (@hide_cols) {
93 # $sth1->{TraceLevel} = 3;
94 $sth1->execute( $authcat, $authvalue );
98 sub GetCols {
99 my ( $authcat, $authvalue ) = @_;
101 my $dbh = C4::Context->dbh;
102 my $sth = $dbh->prepare(
104 SELECT count(display) as cnt from aqbudgets_planning
105 WHERE authcat = ?
106 AND authvalue = ? and display = 0 |
109 # $sth->{TraceLevel} = 3;
110 $sth->execute( $authcat, $authvalue );
111 my $res = $sth->fetchrow_hashref;
113 return $res->{cnt} > 0 ? 0: 1
117 sub CheckBudgetParentPerm {
118 my ( $budget, $borrower_id ) = @_;
119 my $depth = $budget->{depth};
120 my $parent_id = $budget->{budget_parent_id};
121 while ($depth) {
122 my $parent = GetBudget($parent_id);
123 $parent_id = $parent->{budget_parent_id};
124 if ( $parent->{budget_owner_id} == $borrower_id ) {
125 return 1;
127 $depth--
129 return 0;
132 sub AddBudgetPeriod {
133 my ($budgetperiod) = @_;
134 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
136 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
137 return $resultset->create($budgetperiod)->id;
139 # -------------------------------------------------------------------
140 sub GetPeriodsCount {
141 my $dbh = C4::Context->dbh;
142 my $sth = $dbh->prepare("
143 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
144 $sth->execute();
145 my $res = $sth->fetchrow_hashref;
146 return $res->{'sum'};
149 # -------------------------------------------------------------------
150 sub CheckBudgetParent {
151 my ( $new_parent, $budget ) = @_;
152 my $new_parent_id = $new_parent->{'budget_id'};
153 my $budget_id = $budget->{'budget_id'};
154 my $dbh = C4::Context->dbh;
155 my $parent_id_tmp = $new_parent_id;
157 # check new-parent is not a child (or a child's child ;)
158 my $sth = $dbh->prepare(qq|
159 SELECT budget_parent_id FROM
160 aqbudgets where budget_id = ? | );
161 while (1) {
162 $sth->execute($parent_id_tmp);
163 my $res = $sth->fetchrow_hashref;
164 if ( $res->{'budget_parent_id'} == $budget_id ) {
165 return 1;
167 if ( not defined $res->{'budget_parent_id'} ) {
168 return 0;
170 $parent_id_tmp = $res->{'budget_parent_id'};
174 # -------------------------------------------------------------------
175 sub BudgetHasChildren {
176 my ( $budget_id ) = @_;
177 my $dbh = C4::Context->dbh;
178 my $sth = $dbh->prepare(qq|
179 SELECT count(*) as sum FROM aqbudgets
180 WHERE budget_parent_id = ? | );
181 $sth->execute( $budget_id );
182 my $sum = $sth->fetchrow_hashref;
183 return $sum->{'sum'};
186 sub GetBudgetChildren {
187 my ( $budget_id ) = @_;
188 my $dbh = C4::Context->dbh;
189 return $dbh->selectall_arrayref(q|
190 SELECT * FROM aqbudgets
191 WHERE budget_parent_id = ?
192 |, { Slice => {} }, $budget_id );
195 sub SetOwnerToFundHierarchy {
196 my ( $budget_id, $borrowernumber ) = @_;
198 my $budget = GetBudget( $budget_id );
199 $budget->{budget_owner_id} = $borrowernumber;
200 ModBudget( $budget );
201 my $children = GetBudgetChildren( $budget_id );
202 for my $child ( @$children ) {
203 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
207 # -------------------------------------------------------------------
208 sub GetBudgetsPlanCell {
209 my ( $cell, $period, $budget ) = @_;
210 my ($actual, $sth);
211 my $dbh = C4::Context->dbh;
212 if ( $cell->{'authcat'} eq 'MONTHS' ) {
213 # get the actual amount
214 $sth = $dbh->prepare( qq|
216 SELECT SUM(ecost_tax_included) AS actual FROM aqorders
217 WHERE budget_id = ? AND
218 entrydate like "$cell->{'authvalue'}%" |
220 $sth->execute( $cell->{'budget_id'} );
221 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
222 # get the actual amount
223 $sth = $dbh->prepare( qq|
225 SELECT SUM(ecost_tax_included) FROM aqorders
226 LEFT JOIN aqorders_items
227 ON (aqorders.ordernumber = aqorders_items.ordernumber)
228 LEFT JOIN items
229 ON (aqorders_items.itemnumber = items.itemnumber)
230 WHERE budget_id = ? AND homebranch = ? | );
232 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
233 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
234 # get the actual amount
235 $sth = $dbh->prepare( qq|
237 SELECT SUM( ecost_tax_included * quantity) AS actual
238 FROM aqorders JOIN biblioitems
239 ON (biblioitems.biblionumber = aqorders.biblionumber )
240 WHERE aqorders.budget_id = ? and itemtype = ? |
242 $sth->execute( $cell->{'budget_id'},
243 $cell->{'authvalue'} );
245 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
246 else {
247 # get the actual amount
248 $sth = $dbh->prepare( qq|
250 SELECT SUM(ecost_tax_included * quantity) AS actual
251 FROM aqorders
252 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
253 WHERE aqorders.budget_id = ? AND
254 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
255 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
257 $sth->execute( $cell->{'budget_id'},
258 $budget->{'sort1_authcat'},
259 $cell->{'authvalue'},
260 $budget->{'sort2_authcat'},
261 $cell->{'authvalue'}
264 $actual = $sth->fetchrow_array;
266 # get the estimated amount
267 $sth = $dbh->prepare( qq|
269 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
270 WHERE budget_period_id = ? AND
271 budget_id = ? AND
272 authvalue = ? AND
273 authcat = ? |
275 $sth->execute( $cell->{'budget_period_id'},
276 $cell->{'budget_id'},
277 $cell->{'authvalue'},
278 $cell->{'authcat'},
282 my $res = $sth->fetchrow_hashref;
283 # my $display = $res->{'display'};
284 my $estimated = $res->{'estimated'};
287 return $actual, $estimated;
290 # -------------------------------------------------------------------
291 sub ModBudgetPlan {
292 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
293 my $dbh = C4::Context->dbh;
294 foreach my $buds (@$budget_plan) {
295 my $lines = $buds->{lines};
296 my $sth = $dbh->prepare( qq|
297 DELETE FROM aqbudgets_planning
298 WHERE budget_period_id = ? AND
299 budget_id = ? AND
300 authcat = ? |
302 #delete a aqplan line of cells, then insert new cells,
303 # these could be UPDATES rather than DEL/INSERTS...
304 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
306 foreach my $cell (@$lines) {
307 my $sth = $dbh->prepare( qq|
309 INSERT INTO aqbudgets_planning
310 SET budget_id = ?,
311 budget_period_id = ?,
312 authcat = ?,
313 estimated_amount = ?,
314 authvalue = ? |
316 $sth->execute(
317 $cell->{'budget_id'},
318 $cell->{'budget_period_id'},
319 $cell->{'authcat'},
320 $cell->{'estimated_amount'},
321 $cell->{'authvalue'},
327 # -------------------------------------------------------------------
328 sub GetBudgetSpent {
329 my ($budget_id) = @_;
330 my $dbh = C4::Context->dbh;
331 # unitprice_tax_included should always been set here
332 # we should not need to retrieve ecost_tax_included
333 my $sth = $dbh->prepare(qq|
334 SELECT SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS sum FROM aqorders
335 WHERE budget_id = ? AND
336 quantityreceived > 0 AND
337 datecancellationprinted IS NULL
339 $sth->execute($budget_id);
340 my $sum = $sth->fetchrow_array;
342 $sth = $dbh->prepare(qq|
343 SELECT SUM(shipmentcost) AS sum
344 FROM aqinvoices
345 WHERE shipmentcost_budgetid = ?
348 $sth->execute($budget_id);
349 my ($shipmentcost_sum) = $sth->fetchrow_array;
350 $sum += $shipmentcost_sum;
352 return $sum;
355 # -------------------------------------------------------------------
356 sub GetBudgetOrdered {
357 my ($budget_id) = @_;
358 my $dbh = C4::Context->dbh;
359 my $sth = $dbh->prepare(qq|
360 SELECT SUM(ecost_tax_included * quantity) AS sum FROM aqorders
361 WHERE budget_id = ? AND
362 quantityreceived = 0 AND
363 datecancellationprinted IS NULL
365 $sth->execute($budget_id);
366 my $sum = $sth->fetchrow_array;
368 return $sum;
371 =head2 GetBudgetName
373 my $budget_name = &GetBudgetName($budget_id);
375 get the budget_name for a given budget_id
377 =cut
379 sub GetBudgetName {
380 my ( $budget_id ) = @_;
381 my $dbh = C4::Context->dbh;
382 my $sth = $dbh->prepare(
384 SELECT budget_name
385 FROM aqbudgets
386 WHERE budget_id = ?
389 $sth->execute($budget_id);
390 return $sth->fetchrow_array;
393 =head2 GetBudgetAuthCats
395 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
397 Return the list of authcat for a given budget_period_id
399 =cut
401 sub GetBudgetAuthCats {
402 my ($budget_period_id) = shift;
403 # now, populate the auth_cats_loop used in the budget planning button
404 # we must retrieve all auth values used by at least one budget
405 my $dbh = C4::Context->dbh;
406 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
407 $sth->execute($budget_period_id);
408 my %authcats;
409 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
410 $authcats{$sort1_authcat}=1 if $sort1_authcat;
411 $authcats{$sort2_authcat}=1 if $sort2_authcat;
413 return [ sort keys %authcats ];
416 # -------------------------------------------------------------------
417 sub GetBudgetPeriods {
418 my ($filters,$orderby) = @_;
420 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
421 $rs = $rs->search( $filters, { order_by => $orderby } );
422 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
423 return [ $rs->all ];
425 # -------------------------------------------------------------------
426 sub GetBudgetPeriod {
427 my ($budget_period_id) = @_;
428 my $dbh = C4::Context->dbh;
429 ## $total = number of records linked to the record that must be deleted
430 my $total = 0;
431 ## get information about the record that will be deleted
432 my $sth;
433 if ($budget_period_id) {
434 $sth = $dbh->prepare( qq|
435 SELECT *
436 FROM aqbudgetperiods
437 WHERE budget_period_id=? |
439 $sth->execute($budget_period_id);
440 } else { # ACTIVE BUDGET
441 $sth = $dbh->prepare(qq|
442 SELECT *
443 FROM aqbudgetperiods
444 WHERE budget_period_active=1 |
446 $sth->execute();
448 my $data = $sth->fetchrow_hashref;
449 return $data;
452 sub DelBudgetPeriod{
453 my ($budget_period_id) = @_;
454 my $dbh = C4::Context->dbh;
455 ; ## $total = number of records linked to the record that must be deleted
456 my $total = 0;
458 ## get information about the record that will be deleted
459 my $sth = $dbh->prepare(qq|
460 DELETE
461 FROM aqbudgetperiods
462 WHERE budget_period_id=? |
464 return $sth->execute($budget_period_id);
467 # -------------------------------------------------------------------
468 sub ModBudgetPeriod {
469 my ($budget_period) = @_;
470 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
471 return unless($result);
473 $result = $result->update($budget_period);
474 return $result->in_storage;
477 # -------------------------------------------------------------------
478 sub GetBudgetHierarchy {
479 my ( $budget_period_id, $branchcode, $owner ) = @_;
480 my @bind_params;
481 my $dbh = C4::Context->dbh;
482 my $query = qq|
483 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
484 FROM aqbudgets
485 JOIN aqbudgetperiods USING (budget_period_id)|;
487 my @where_strings;
488 # show only period X if requested
489 if ($budget_period_id) {
490 push @where_strings," aqbudgets.budget_period_id = ?";
491 push @bind_params, $budget_period_id;
493 # show only budgets owned by me, my branch or everyone
494 if ($owner) {
495 if ($branchcode) {
496 push @where_strings,
497 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="")))};
498 push @bind_params, ( $owner, $branchcode );
499 } else {
500 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
501 push @bind_params, $owner;
503 } else {
504 if ($branchcode) {
505 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
506 push @bind_params, $branchcode;
509 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
510 $debug && warn $query,join(",",@bind_params);
511 my $sth = $dbh->prepare($query);
512 $sth->execute(@bind_params);
514 my %links;
515 # create hash with budget_id has key
516 while ( my $data = $sth->fetchrow_hashref ) {
517 $links{ $data->{'budget_id'} } = $data;
520 # link child to parent
521 my @first_parents;
522 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
523 my $child = $links{$budget->{budget_id}};
524 if ( $child->{'budget_parent_id'} ) {
525 my $parent = $links{ $child->{'budget_parent_id'} };
526 if ($parent) {
527 unless ( $parent->{'children'} ) {
528 # init child arrayref
529 $parent->{'children'} = [];
531 # add as child
532 push @{ $parent->{'children'} }, $child;
534 } else {
535 push @first_parents, $child;
539 my @sort = ();
540 foreach my $first_parent (@first_parents) {
541 _add_budget_children(\@sort, $first_parent, 0);
544 foreach my $budget (@sort) {
545 $budget->{budget_spent} = GetBudgetSpent( $budget->{budget_id} );
546 $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
547 $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
548 $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
550 return \@sort;
553 # Recursive method to add a budget and its chidren to an array
554 sub _add_budget_children {
555 my $res = shift;
556 my $budget = shift;
557 $budget->{budget_level} = shift;
558 push @$res, $budget;
559 my $children = $budget->{'children'} || [];
560 return unless @$children; # break recursivity
561 foreach my $child (@$children) {
562 _add_budget_children($res, $child, $budget->{budget_level} + 1);
566 # -------------------------------------------------------------------
568 sub AddBudget {
569 my ($budget) = @_;
570 return unless ($budget);
572 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
573 return $resultset->create($budget)->id;
576 # -------------------------------------------------------------------
577 sub ModBudget {
578 my ($budget) = @_;
579 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
580 return unless($result);
582 $result = $result->update($budget);
583 return $result->in_storage;
586 # -------------------------------------------------------------------
587 sub DelBudget {
588 my ($budget_id) = @_;
589 my $dbh = C4::Context->dbh;
590 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
591 my $rc = $sth->execute($budget_id);
592 return $rc;
596 # -------------------------------------------------------------------
598 =head2 GetBudget
600 &GetBudget($budget_id);
602 get a specific budget
604 =cut
606 sub GetBudget {
607 my ( $budget_id ) = @_;
608 my $dbh = C4::Context->dbh;
609 my $query = "
610 SELECT *
611 FROM aqbudgets
612 WHERE budget_id=?
614 my $sth = $dbh->prepare($query);
615 $sth->execute( $budget_id );
616 my $result = $sth->fetchrow_hashref;
617 return $result;
620 # -------------------------------------------------------------------
622 =head2 GetBudgetByOrderNumber
624 &GetBudgetByOrderNumber($ordernumber);
626 get a specific budget by order number
628 =cut
630 sub GetBudgetByOrderNumber {
631 my ( $ordernumber ) = @_;
632 my $dbh = C4::Context->dbh;
633 my $query = "
634 SELECT aqbudgets.*
635 FROM aqbudgets, aqorders
636 WHERE ordernumber=?
637 AND aqorders.budget_id = aqbudgets.budget_id
639 my $sth = $dbh->prepare($query);
640 $sth->execute( $ordernumber );
641 my $result = $sth->fetchrow_hashref;
642 return $result;
645 =head2 GetBudgetReport
647 &GetBudgetReport( [$budget_id] );
649 Get all orders for a specific budget, without cancelled orders.
651 Returns an array of hashrefs.
653 =cut
655 # --------------------------------------------------------------------
656 sub GetBudgetReport {
657 my ( $budget_id ) = @_;
658 my $dbh = C4::Context->dbh;
659 my $query = '
660 SELECT o.*, b.budget_name
661 FROM aqbudgets b
662 INNER JOIN aqorders o
663 ON b.budget_id = o.budget_id
664 WHERE b.budget_id=?
665 AND (o.orderstatus != "cancelled")
666 ORDER BY b.budget_name';
668 my $sth = $dbh->prepare($query);
669 $sth->execute( $budget_id );
671 my @results = ();
672 while ( my $data = $sth->fetchrow_hashref ) {
673 push( @results, $data );
675 return @results;
678 =head2 GetBudgetsByActivity
680 &GetBudgetsByActivity( $budget_period_active );
682 Get all active or inactive budgets, depending of the value
683 of the parameter.
685 1 = active
686 0 = inactive
688 =cut
690 # --------------------------------------------------------------------
691 sub GetBudgetsByActivity {
692 my ( $budget_period_active ) = @_;
693 my $dbh = C4::Context->dbh;
694 my $query = "
695 SELECT DISTINCT b.*
696 FROM aqbudgetperiods bp
697 INNER JOIN aqbudgets b
698 ON bp.budget_period_id = b.budget_period_id
699 WHERE bp.budget_period_active=?
701 my $sth = $dbh->prepare($query);
702 $sth->execute( $budget_period_active );
703 my @results = ();
704 while ( my $data = $sth->fetchrow_hashref ) {
705 push( @results, $data );
707 return @results;
709 # --------------------------------------------------------------------
711 =head2 GetBudgetsReport
713 &GetBudgetsReport( [$activity] );
715 Get all but cancelled orders for all funds.
717 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
719 active = 1
720 inactive = 0
722 Returns an array of hashrefs.
724 =cut
726 sub GetBudgetsReport {
727 my ($activity) = @_;
728 my $dbh = C4::Context->dbh;
729 my $query = '
730 SELECT o.*, b.budget_name
731 FROM aqbudgetperiods bp
732 INNER JOIN aqbudgets b
733 ON bp.budget_period_id = b.budget_period_id
734 INNER JOIN aqorders o
735 ON b.budget_id = o.budget_id ';
736 if($activity ne ''){
737 $query .= 'WHERE bp.budget_period_active=? ';
739 $query .= 'AND (o.orderstatus != "cancelled")
740 ORDER BY b.budget_name';
742 my $sth = $dbh->prepare($query);
743 if($activity ne ''){
744 $sth->execute($activity);
746 else{
747 $sth->execute;
749 my @results = ();
750 while ( my $data = $sth->fetchrow_hashref ) {
751 push( @results, $data );
753 return @results;
756 =head2 GetBudgetByCode
758 my $budget = &GetBudgetByCode($budget_code);
760 Retrieve all aqbudgets fields as a hashref for the budget that has
761 given budget_code
763 =cut
765 sub GetBudgetByCode {
766 my ( $budget_code ) = @_;
768 my $dbh = C4::Context->dbh;
769 my $query = qq{
770 SELECT aqbudgets.*
771 FROM aqbudgets
772 JOIN aqbudgetperiods USING (budget_period_id)
773 WHERE budget_code = ?
774 ORDER BY budget_period_active DESC, budget_id DESC
775 LIMIT 1
777 my $sth = $dbh->prepare( $query );
778 $sth->execute( $budget_code );
779 return $sth->fetchrow_hashref;
782 =head2 GetBudgetHierarchySpent
784 my $spent = GetBudgetHierarchySpent( $budget_id );
786 Gets the total spent of the level and sublevels of $budget_id
788 =cut
790 sub GetBudgetHierarchySpent {
791 my ( $budget_id ) = @_;
792 my $dbh = C4::Context->dbh;
793 my $children_ids = $dbh->selectcol_arrayref(q|
794 SELECT budget_id
795 FROM aqbudgets
796 WHERE budget_parent_id = ?
797 |, {}, $budget_id );
799 my $total_spent = GetBudgetSpent( $budget_id );
800 for my $child_id ( @$children_ids ) {
801 $total_spent += GetBudgetHierarchySpent( $child_id );
803 return $total_spent;
806 =head2 GetBudgetHierarchyOrdered
808 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
810 Gets the total ordered of the level and sublevels of $budget_id
812 =cut
814 sub GetBudgetHierarchyOrdered {
815 my ( $budget_id ) = @_;
816 my $dbh = C4::Context->dbh;
817 my $children_ids = $dbh->selectcol_arrayref(q|
818 SELECT budget_id
819 FROM aqbudgets
820 WHERE budget_parent_id = ?
821 |, {}, $budget_id );
823 my $total_ordered = GetBudgetOrdered( $budget_id );
824 for my $child_id ( @$children_ids ) {
825 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
827 return $total_ordered;
830 =head2 GetBudgets
832 &GetBudgets($filter, $order_by);
834 gets all budgets
836 =cut
838 # -------------------------------------------------------------------
839 sub GetBudgets {
840 my ($filters, $orderby) = @_;
841 $orderby = 'budget_name' unless($orderby);
843 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
844 $rs = $rs->search( $filters, { order_by => $orderby } );
845 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
846 return [ $rs->all ];
849 =head2 GetBudgetUsers
851 my @borrowernumbers = &GetBudgetUsers($budget_id);
853 Return the list of borrowernumbers linked to a budget
855 =cut
857 sub GetBudgetUsers {
858 my ($budget_id) = @_;
860 my $dbh = C4::Context->dbh;
861 my $query = qq{
862 SELECT borrowernumber
863 FROM aqbudgetborrowers
864 WHERE budget_id = ?
866 my $sth = $dbh->prepare($query);
867 $sth->execute($budget_id);
869 my @borrowernumbers;
870 while (my ($borrowernumber) = $sth->fetchrow_array) {
871 push @borrowernumbers, $borrowernumber
874 return @borrowernumbers;
877 =head2 ModBudgetUsers
879 &ModBudgetUsers($budget_id, @borrowernumbers);
881 Modify the list of borrowernumbers linked to a budget
883 =cut
885 sub ModBudgetUsers {
886 my ($budget_id, @budget_users_id) = @_;
888 return unless $budget_id;
890 my $dbh = C4::Context->dbh;
891 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
892 my $sth = $dbh->prepare($query);
893 $sth->execute($budget_id);
895 $query = qq{
896 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
897 VALUES (?,?)
899 $sth = $dbh->prepare($query);
900 foreach my $borrowernumber (@budget_users_id) {
901 next unless $borrowernumber;
902 $sth->execute($budget_id, $borrowernumber);
906 sub CanUserUseBudget {
907 my ($borrower, $budget, $userflags) = @_;
909 if (not ref $borrower) {
910 $borrower = Koha::Patrons->find( $borrower );
911 return 0 unless $borrower;
912 $borrower = $borrower->unblessed;
914 if (not ref $budget) {
915 $budget = GetBudget($budget);
918 return 0 unless ($borrower and $budget);
920 if (not defined $userflags) {
921 $userflags = C4::Auth::getuserflags($borrower->{flags},
922 $borrower->{userid});
925 unless ($userflags->{superlibrarian}
926 || (ref $userflags->{acquisition}
927 && $userflags->{acquisition}->{budget_manage_all})
928 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
930 if (not exists $userflags->{acquisition}) {
931 return 0;
934 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
935 return 0;
938 # Budget restricted to owner
939 if ( $budget->{budget_permission} == 1 ) {
940 if ( $budget->{budget_owner_id}
941 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
943 return 0;
947 # Budget restricted to owner, users and library
948 elsif ( $budget->{budget_permission} == 2 ) {
949 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
951 if (
953 $budget->{budget_owner_id}
954 and $budget->{budget_owner_id} !=
955 $borrower->{borrowernumber}
956 or not $budget->{budget_owner_id}
958 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
959 @budget_users )
960 and defined $budget->{budget_branchcode}
961 and $budget->{budget_branchcode} ne
962 C4::Context->userenv->{branch}
965 return 0;
969 # Budget restricted to owner and users
970 elsif ( $budget->{budget_permission} == 3 ) {
971 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
972 if (
974 $budget->{budget_owner_id}
975 and $budget->{budget_owner_id} !=
976 $borrower->{borrowernumber}
977 or not $budget->{budget_owner_id}
979 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
980 @budget_users )
983 return 0;
988 return 1;
991 sub CanUserModifyBudget {
992 my ($borrower, $budget, $userflags) = @_;
994 if (not ref $borrower) {
995 $borrower = Koha::Patrons->find( $borrower );
996 return 0 unless $borrower;
997 $borrower = $borrower->unblessed;
999 if (not ref $budget) {
1000 $budget = GetBudget($budget);
1003 return 0 unless ($borrower and $budget);
1005 if (not defined $userflags) {
1006 $userflags = C4::Auth::getuserflags($borrower->{flags},
1007 $borrower->{userid});
1010 unless ($userflags->{superlibrarian}
1011 || (ref $userflags->{acquisition}
1012 && $userflags->{acquisition}->{budget_manage_all})
1013 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1015 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1016 return 0;
1019 if (ref $userflags->{acquisition}
1020 && !$userflags->{acquisition}->{budget_modify}) {
1021 return 0;
1025 return 1;
1028 sub _round {
1029 my ($value, $increment) = @_;
1031 if ($increment && $increment != 0) {
1032 $value = int($value / $increment) * $increment;
1035 return $value;
1038 =head2 CloneBudgetPeriod
1040 my $new_budget_period_id = CloneBudgetPeriod({
1041 budget_period_id => $budget_period_id,
1042 budget_period_startdate => $budget_period_startdate,
1043 budget_period_enddate => $budget_period_enddate,
1044 mark_original_budget_as_inactive => 1n
1045 reset_all_budgets => 1,
1048 Clone a budget period with all budgets.
1049 If the mark_origin_budget_as_inactive is set (0 by default),
1050 the original budget will be marked as inactive.
1052 If the reset_all_budgets is set (0 by default), all budget (fund)
1053 amounts will be reset.
1055 =cut
1057 sub CloneBudgetPeriod {
1058 my ($params) = @_;
1059 my $budget_period_id = $params->{budget_period_id};
1060 my $budget_period_startdate = $params->{budget_period_startdate};
1061 my $budget_period_enddate = $params->{budget_period_enddate};
1062 my $budget_period_description = $params->{budget_period_description};
1063 my $amount_change_percentage = $params->{amount_change_percentage};
1064 my $amount_change_round_increment = $params->{amount_change_round_increment};
1065 my $mark_original_budget_as_inactive =
1066 $params->{mark_original_budget_as_inactive} || 0;
1067 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1069 my $budget_period = GetBudgetPeriod($budget_period_id);
1071 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1072 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1073 $budget_period->{budget_period_description} = $budget_period_description;
1074 # The new budget (budget_period) should be active by default
1075 $budget_period->{budget_period_active} = 1;
1077 if ($amount_change_percentage) {
1078 my $total = $budget_period->{budget_period_total};
1079 $total += $total * $amount_change_percentage / 100;
1080 $total = _round($total, $amount_change_round_increment);
1081 $budget_period->{budget_period_total} = $total;
1084 my $original_budget_period_id = $budget_period->{budget_period_id};
1085 delete $budget_period->{budget_period_id};
1086 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1088 my $budgets = GetBudgetHierarchy($budget_period_id);
1089 CloneBudgetHierarchy(
1091 budgets => $budgets,
1092 new_budget_period_id => $new_budget_period_id
1096 if ($mark_original_budget_as_inactive) {
1097 ModBudgetPeriod(
1099 budget_period_id => $budget_period_id,
1100 budget_period_active => 0,
1105 if ( $reset_all_budgets ) {
1106 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1107 for my $budget ( @$budgets ) {
1108 $budget->{budget_amount} = 0;
1109 ModBudget( $budget );
1111 } elsif ($amount_change_percentage) {
1112 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1113 for my $budget ( @$budgets ) {
1114 my $amount = $budget->{budget_amount};
1115 $amount += $amount * $amount_change_percentage / 100;
1116 $amount = _round($amount, $amount_change_round_increment);
1117 $budget->{budget_amount} = $amount;
1118 ModBudget( $budget );
1122 return $new_budget_period_id;
1125 =head2 CloneBudgetHierarchy
1127 CloneBudgetHierarchy({
1128 budgets => $budgets,
1129 new_budget_period_id => $new_budget_period_id;
1132 Clone a budget hierarchy.
1134 =cut
1136 sub CloneBudgetHierarchy {
1137 my ($params) = @_;
1138 my $budgets = $params->{budgets};
1139 my $new_budget_period_id = $params->{new_budget_period_id};
1140 next unless @$budgets or $new_budget_period_id;
1142 my $children_of = $params->{children_of};
1143 my $new_parent_id = $params->{new_parent_id};
1145 my @first_level_budgets =
1146 ( not defined $children_of )
1147 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1148 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1150 # get only the columns of aqbudgets
1151 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1153 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1154 @first_level_budgets )
1157 my $tidy_budget =
1158 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1159 keys %$budget };
1160 my $new_budget_id = AddBudget(
1162 %$tidy_budget,
1163 budget_id => undef,
1164 budget_parent_id => $new_parent_id,
1165 budget_period_id => $new_budget_period_id
1168 CloneBudgetHierarchy(
1170 budgets => $budgets,
1171 new_budget_period_id => $new_budget_period_id,
1172 children_of => $budget->{budget_id},
1173 new_parent_id => $new_budget_id
1179 =head2 MoveOrders
1181 my $report = MoveOrders({
1182 from_budget_period_id => $from_budget_period_id,
1183 to_budget_period_id => $to_budget_period_id,
1186 Move orders from one budget period to another.
1188 =cut
1190 sub MoveOrders {
1191 my ($params) = @_;
1192 my $from_budget_period_id = $params->{from_budget_period_id};
1193 my $to_budget_period_id = $params->{to_budget_period_id};
1194 my $move_remaining_unspent = $params->{move_remaining_unspent};
1195 return
1196 if not $from_budget_period_id
1197 or not $to_budget_period_id
1198 or $from_budget_period_id == $to_budget_period_id;
1200 # Can't move orders to an inactive budget (budgetperiod)
1201 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1202 return unless $budget_period->{budget_period_active};
1204 my @report;
1205 my $dbh = C4::Context->dbh;
1206 my $sth_update_aqorders = $dbh->prepare(
1208 UPDATE aqorders
1209 SET budget_id = ?
1210 WHERE ordernumber = ?
1213 my $sth_update_budget_amount = $dbh->prepare(
1215 UPDATE aqbudgets
1216 SET budget_amount = ?
1217 WHERE budget_id = ?
1220 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1221 for my $from_budget (@$from_budgets) {
1222 my $new_budget_id = $dbh->selectcol_arrayref(
1224 SELECT budget_id
1225 FROM aqbudgets
1226 WHERE budget_period_id = ?
1227 AND budget_code = ?
1228 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1230 $new_budget_id = $new_budget_id->[0];
1231 my $new_budget = GetBudget( $new_budget_id );
1232 unless ( $new_budget ) {
1233 push @report,
1235 moved => 0,
1236 budget => $from_budget,
1237 error => 'budget_code_not_exists',
1239 next;
1241 my $orders_to_move = C4::Acquisition::SearchOrders(
1243 budget_id => $from_budget->{budget_id},
1244 pending => 1,
1248 my @orders_moved;
1249 for my $order (@$orders_to_move) {
1250 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1251 push @orders_moved, $order;
1254 my $unspent_moved = 0;
1255 if ($move_remaining_unspent) {
1256 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1257 my $unspent = $from_budget->{budget_amount} - $spent;
1258 my $new_budget_amount = $new_budget->{budget_amount};
1259 if ( $unspent > 0 ) {
1260 $new_budget_amount += $unspent;
1261 $unspent_moved = $unspent;
1263 $new_budget->{budget_amount} = $new_budget_amount;
1264 $sth_update_budget_amount->execute( $new_budget_amount,
1265 $new_budget->{budget_id} );
1268 push @report,
1270 budget => $new_budget,
1271 orders_moved => \@orders_moved,
1272 moved => 1,
1273 unspent_moved => $unspent_moved,
1276 return \@report;
1279 END { } # module clean-up code here (global destructor)
1282 __END__
1284 =head1 AUTHOR
1286 Koha Development Team <http://koha-community.org/>
1288 =cut