Bug 15009 - Planning dropdown button in aqbudget can have empty line
[koha.git] / C4 / Budgets.pm
blobc3c90e639e03bf4642a83f2ad486b2a897d771fe
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 C4::Debug;
25 use vars qw(@ISA @EXPORT);
27 BEGIN {
28 require Exporter;
29 @ISA = qw(Exporter);
30 @EXPORT = qw(
32 &GetBudget
33 &GetBudgetByOrderNumber
34 &GetBudgetByCode
35 &GetBudgets
36 &BudgetsByActivity
37 &GetBudgetsReport
38 &GetBudgetReport
39 &GetBudgetHierarchy
40 &AddBudget
41 &ModBudget
42 &DelBudget
43 &GetBudgetSpent
44 &GetBudgetOrdered
45 &GetBudgetName
46 &GetPeriodsCount
47 GetBudgetHierarchySpent
48 GetBudgetHierarchyOrdered
50 &GetBudgetUsers
51 &ModBudgetUsers
52 &CanUserUseBudget
53 &CanUserModifyBudget
55 &GetBudgetPeriod
56 &GetBudgetPeriods
57 &ModBudgetPeriod
58 &AddBudgetPeriod
59 &DelBudgetPeriod
61 &ModBudgetPlan
63 &GetBudgetsPlanCell
64 &AddBudgetPlanValue
65 &GetBudgetAuthCats
66 &BudgetHasChildren
67 &CheckBudgetParent
68 &CheckBudgetParentPerm
70 &HideCols
71 &GetCols
75 # ----------------------------BUDGETS.PM-----------------------------";
77 =head1 FUNCTIONS ABOUT BUDGETS
79 =cut
81 sub HideCols {
82 my ( $authcat, @hide_cols ) = @_;
83 my $dbh = C4::Context->dbh;
85 my $sth1 = $dbh->prepare(
86 qq|
87 UPDATE aqbudgets_planning SET display = 0
88 WHERE authcat = ?
89 AND authvalue = ? |
91 foreach my $authvalue (@hide_cols) {
92 # $sth1->{TraceLevel} = 3;
93 $sth1->execute( $authcat, $authvalue );
97 sub GetCols {
98 my ( $authcat, $authvalue ) = @_;
100 my $dbh = C4::Context->dbh;
101 my $sth = $dbh->prepare(
103 SELECT count(display) as cnt from aqbudgets_planning
104 WHERE authcat = ?
105 AND authvalue = ? and display = 0 |
108 # $sth->{TraceLevel} = 3;
109 $sth->execute( $authcat, $authvalue );
110 my $res = $sth->fetchrow_hashref;
112 return $res->{cnt} > 0 ? 0: 1
116 sub CheckBudgetParentPerm {
117 my ( $budget, $borrower_id ) = @_;
118 my $depth = $budget->{depth};
119 my $parent_id = $budget->{budget_parent_id};
120 while ($depth) {
121 my $parent = GetBudget($parent_id);
122 $parent_id = $parent->{budget_parent_id};
123 if ( $parent->{budget_owner_id} == $borrower_id ) {
124 return 1;
126 $depth--
128 return 0;
131 sub AddBudgetPeriod {
132 my ($budgetperiod) = @_;
133 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
135 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
136 return $resultset->create($budgetperiod)->id;
138 # -------------------------------------------------------------------
139 sub GetPeriodsCount {
140 my $dbh = C4::Context->dbh;
141 my $sth = $dbh->prepare("
142 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
143 $sth->execute();
144 my $res = $sth->fetchrow_hashref;
145 return $res->{'sum'};
148 # -------------------------------------------------------------------
149 sub CheckBudgetParent {
150 my ( $new_parent, $budget ) = @_;
151 my $new_parent_id = $new_parent->{'budget_id'};
152 my $budget_id = $budget->{'budget_id'};
153 my $dbh = C4::Context->dbh;
154 my $parent_id_tmp = $new_parent_id;
156 # check new-parent is not a child (or a child's child ;)
157 my $sth = $dbh->prepare(qq|
158 SELECT budget_parent_id FROM
159 aqbudgets where budget_id = ? | );
160 while (1) {
161 $sth->execute($parent_id_tmp);
162 my $res = $sth->fetchrow_hashref;
163 if ( $res->{'budget_parent_id'} == $budget_id ) {
164 return 1;
166 if ( not defined $res->{'budget_parent_id'} ) {
167 return 0;
169 $parent_id_tmp = $res->{'budget_parent_id'};
173 # -------------------------------------------------------------------
174 sub BudgetHasChildren {
175 my ( $budget_id ) = @_;
176 my $dbh = C4::Context->dbh;
177 my $sth = $dbh->prepare(qq|
178 SELECT count(*) as sum FROM aqbudgets
179 WHERE budget_parent_id = ? | );
180 $sth->execute( $budget_id );
181 my $sum = $sth->fetchrow_hashref;
182 return $sum->{'sum'};
185 sub GetBudgetChildren {
186 my ( $budget_id ) = @_;
187 my $dbh = C4::Context->dbh;
188 return $dbh->selectall_arrayref(q|
189 SELECT * FROM aqbudgets
190 WHERE budget_parent_id = ?
191 |, { Slice => {} }, $budget_id );
194 sub SetOwnerToFundHierarchy {
195 my ( $budget_id, $borrowernumber ) = @_;
197 my $budget = GetBudget( $budget_id );
198 $budget->{budget_owner_id} = $borrowernumber;
199 ModBudget( $budget );
200 my $children = GetBudgetChildren( $budget_id );
201 for my $child ( @$children ) {
202 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
206 # -------------------------------------------------------------------
207 sub GetBudgetsPlanCell {
208 my ( $cell, $period, $budget ) = @_;
209 my ($actual, $sth);
210 my $dbh = C4::Context->dbh;
211 if ( $cell->{'authcat'} eq 'MONTHS' ) {
212 # get the actual amount
213 $sth = $dbh->prepare( qq|
215 SELECT SUM(ecost) AS actual FROM aqorders
216 WHERE budget_id = ? AND
217 entrydate like "$cell->{'authvalue'}%" |
219 $sth->execute( $cell->{'budget_id'} );
220 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
221 # get the actual amount
222 $sth = $dbh->prepare( qq|
224 SELECT SUM(ecost) FROM aqorders
225 LEFT JOIN aqorders_items
226 ON (aqorders.ordernumber = aqorders_items.ordernumber)
227 LEFT JOIN items
228 ON (aqorders_items.itemnumber = items.itemnumber)
229 WHERE budget_id = ? AND homebranch = ? | );
231 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
232 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
233 # get the actual amount
234 $sth = $dbh->prepare( qq|
236 SELECT SUM( ecost * quantity) AS actual
237 FROM aqorders JOIN biblioitems
238 ON (biblioitems.biblionumber = aqorders.biblionumber )
239 WHERE aqorders.budget_id = ? and itemtype = ? |
241 $sth->execute( $cell->{'budget_id'},
242 $cell->{'authvalue'} );
244 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
245 else {
246 # get the actual amount
247 $sth = $dbh->prepare( qq|
249 SELECT SUM(ecost * quantity) AS actual
250 FROM aqorders
251 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
252 WHERE aqorders.budget_id = ? AND
253 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
254 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
256 $sth->execute( $cell->{'budget_id'},
257 $budget->{'sort1_authcat'},
258 $cell->{'authvalue'},
259 $budget->{'sort2_authcat'},
260 $cell->{'authvalue'}
263 $actual = $sth->fetchrow_array;
265 # get the estimated amount
266 $sth = $dbh->prepare( qq|
268 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
269 WHERE budget_period_id = ? AND
270 budget_id = ? AND
271 authvalue = ? AND
272 authcat = ? |
274 $sth->execute( $cell->{'budget_period_id'},
275 $cell->{'budget_id'},
276 $cell->{'authvalue'},
277 $cell->{'authcat'},
281 my $res = $sth->fetchrow_hashref;
282 # my $display = $res->{'display'};
283 my $estimated = $res->{'estimated'};
286 return $actual, $estimated;
289 # -------------------------------------------------------------------
290 sub ModBudgetPlan {
291 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
292 my $dbh = C4::Context->dbh;
293 foreach my $buds (@$budget_plan) {
294 my $lines = $buds->{lines};
295 my $sth = $dbh->prepare( qq|
296 DELETE FROM aqbudgets_planning
297 WHERE budget_period_id = ? AND
298 budget_id = ? AND
299 authcat = ? |
301 #delete a aqplan line of cells, then insert new cells,
302 # these could be UPDATES rather than DEL/INSERTS...
303 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
305 foreach my $cell (@$lines) {
306 my $sth = $dbh->prepare( qq|
308 INSERT INTO aqbudgets_planning
309 SET budget_id = ?,
310 budget_period_id = ?,
311 authcat = ?,
312 estimated_amount = ?,
313 authvalue = ? |
315 $sth->execute(
316 $cell->{'budget_id'},
317 $cell->{'budget_period_id'},
318 $cell->{'authcat'},
319 $cell->{'estimated_amount'},
320 $cell->{'authvalue'},
326 # -------------------------------------------------------------------
327 sub GetBudgetSpent {
328 my ($budget_id) = @_;
329 my $dbh = C4::Context->dbh;
330 my $sth = $dbh->prepare(qq|
331 SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
332 WHERE budget_id = ? AND
333 quantityreceived > 0 AND
334 datecancellationprinted IS NULL
336 $sth->execute($budget_id);
337 my $sum = $sth->fetchrow_array;
339 $sth = $dbh->prepare(qq|
340 SELECT SUM(shipmentcost) AS sum
341 FROM aqinvoices
342 WHERE shipmentcost_budgetid = ?
343 AND closedate IS NOT NULL
345 $sth->execute($budget_id);
346 my ($shipmentcost_sum) = $sth->fetchrow_array;
347 $sum += $shipmentcost_sum;
349 return $sum;
352 # -------------------------------------------------------------------
353 sub GetBudgetOrdered {
354 my ($budget_id) = @_;
355 my $dbh = C4::Context->dbh;
356 my $sth = $dbh->prepare(qq|
357 SELECT SUM(ecost * quantity) AS sum FROM aqorders
358 WHERE budget_id = ? AND
359 quantityreceived = 0 AND
360 datecancellationprinted IS NULL
362 $sth->execute($budget_id);
363 my $sum = $sth->fetchrow_array;
365 $sth = $dbh->prepare(qq|
366 SELECT SUM(shipmentcost) AS sum
367 FROM aqinvoices
368 WHERE shipmentcost_budgetid = ?
369 AND closedate IS NULL
371 $sth->execute($budget_id);
372 my ($shipmentcost_sum) = $sth->fetchrow_array;
373 $sum += $shipmentcost_sum;
375 return $sum;
378 =head2 GetBudgetName
380 my $budget_name = &GetBudgetName($budget_id);
382 get the budget_name for a given budget_id
384 =cut
386 sub GetBudgetName {
387 my ( $budget_id ) = @_;
388 my $dbh = C4::Context->dbh;
389 my $sth = $dbh->prepare(
391 SELECT budget_name
392 FROM aqbudgets
393 WHERE budget_id = ?
396 $sth->execute($budget_id);
397 return $sth->fetchrow_array;
400 # -------------------------------------------------------------------
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 my @auth_cats_loop;
414 foreach (sort keys %authcats) {
415 push @auth_cats_loop,{ authcat => $_ };
417 return \@auth_cats_loop;
420 # -------------------------------------------------------------------
421 sub GetBudgetPeriods {
422 my ($filters,$orderby) = @_;
424 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
425 $rs = $rs->search( $filters, { order_by => $orderby } );
426 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
427 return [ $rs->all ];
429 # -------------------------------------------------------------------
430 sub GetBudgetPeriod {
431 my ($budget_period_id) = @_;
432 my $dbh = C4::Context->dbh;
433 ## $total = number of records linked to the record that must be deleted
434 my $total = 0;
435 ## get information about the record that will be deleted
436 my $sth;
437 if ($budget_period_id) {
438 $sth = $dbh->prepare( qq|
439 SELECT *
440 FROM aqbudgetperiods
441 WHERE budget_period_id=? |
443 $sth->execute($budget_period_id);
444 } else { # ACTIVE BUDGET
445 $sth = $dbh->prepare(qq|
446 SELECT *
447 FROM aqbudgetperiods
448 WHERE budget_period_active=1 |
450 $sth->execute();
452 my $data = $sth->fetchrow_hashref;
453 return $data;
456 sub DelBudgetPeriod{
457 my ($budget_period_id) = @_;
458 my $dbh = C4::Context->dbh;
459 ; ## $total = number of records linked to the record that must be deleted
460 my $total = 0;
462 ## get information about the record that will be deleted
463 my $sth = $dbh->prepare(qq|
464 DELETE
465 FROM aqbudgetperiods
466 WHERE budget_period_id=? |
468 return $sth->execute($budget_period_id);
471 # -------------------------------------------------------------------
472 sub ModBudgetPeriod {
473 my ($budget_period) = @_;
474 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
475 return unless($result);
477 $result = $result->update($budget_period);
478 return $result->in_storage;
481 # -------------------------------------------------------------------
482 sub GetBudgetHierarchy {
483 my ( $budget_period_id, $branchcode, $owner ) = @_;
484 my @bind_params;
485 my $dbh = C4::Context->dbh;
486 my $query = qq|
487 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
488 FROM aqbudgets
489 JOIN aqbudgetperiods USING (budget_period_id)|;
491 my @where_strings;
492 # show only period X if requested
493 if ($budget_period_id) {
494 push @where_strings," aqbudgets.budget_period_id = ?";
495 push @bind_params, $budget_period_id;
497 # show only budgets owned by me, my branch or everyone
498 if ($owner) {
499 if ($branchcode) {
500 push @where_strings,
501 qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))};
502 push @bind_params, ( $owner, $branchcode );
503 } else {
504 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
505 push @bind_params, $owner;
507 } else {
508 if ($branchcode) {
509 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
510 push @bind_params, $branchcode;
513 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
514 $debug && warn $query,join(",",@bind_params);
515 my $sth = $dbh->prepare($query);
516 $sth->execute(@bind_params);
518 my %links;
519 # create hash with budget_id has key
520 while ( my $data = $sth->fetchrow_hashref ) {
521 $links{ $data->{'budget_id'} } = $data;
524 # link child to parent
525 my @first_parents;
526 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
527 my $child = $links{$budget->{budget_id}};
528 if ( $child->{'budget_parent_id'} ) {
529 my $parent = $links{ $child->{'budget_parent_id'} };
530 if ($parent) {
531 unless ( $parent->{'children'} ) {
532 # init child arrayref
533 $parent->{'children'} = [];
535 # add as child
536 push @{ $parent->{'children'} }, $child;
538 } else {
539 push @first_parents, $child;
543 my @sort = ();
544 foreach my $first_parent (@first_parents) {
545 _add_budget_children(\@sort, $first_parent);
548 foreach my $budget (@sort) {
549 $budget->{budget_spent} = GetBudgetSpent( $budget->{budget_id} );
550 $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
551 $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
552 $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
554 return \@sort;
557 # Recursive method to add a budget and its chidren to an array
558 sub _add_budget_children {
559 my $res = shift;
560 my $budget = shift;
561 push @$res, $budget;
562 my $children = $budget->{'children'} || [];
563 return unless @$children; # break recursivity
564 foreach my $child (@$children) {
565 _add_budget_children($res, $child);
569 # -------------------------------------------------------------------
571 sub AddBudget {
572 my ($budget) = @_;
573 return unless ($budget);
575 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
576 return $resultset->create($budget)->id;
579 # -------------------------------------------------------------------
580 sub ModBudget {
581 my ($budget) = @_;
582 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
583 return unless($result);
585 $result = $result->update($budget);
586 return $result->in_storage;
589 # -------------------------------------------------------------------
590 sub DelBudget {
591 my ($budget_id) = @_;
592 my $dbh = C4::Context->dbh;
593 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
594 my $rc = $sth->execute($budget_id);
595 return $rc;
599 # -------------------------------------------------------------------
601 =head2 GetBudget
603 &GetBudget($budget_id);
605 get a specific budget
607 =cut
609 sub GetBudget {
610 my ( $budget_id ) = @_;
611 my $dbh = C4::Context->dbh;
612 my $query = "
613 SELECT *
614 FROM aqbudgets
615 WHERE budget_id=?
617 my $sth = $dbh->prepare($query);
618 $sth->execute( $budget_id );
619 my $result = $sth->fetchrow_hashref;
620 return $result;
623 # -------------------------------------------------------------------
625 =head2 GetBudgetByOrderNumber
627 &GetBudgetByOrderNumber($ordernumber);
629 get a specific budget by order number
631 =cut
633 sub GetBudgetByOrderNumber {
634 my ( $ordernumber ) = @_;
635 my $dbh = C4::Context->dbh;
636 my $query = "
637 SELECT aqbudgets.*
638 FROM aqbudgets, aqorders
639 WHERE ordernumber=?
640 AND aqorders.budget_id = aqbudgets.budget_id
642 my $sth = $dbh->prepare($query);
643 $sth->execute( $ordernumber );
644 my $result = $sth->fetchrow_hashref;
645 return $result;
648 =head2 GetBudgetReport
650 &GetBudgetReport( [$budget_id] );
652 Get all orders for a specific budget, without cancelled orders.
654 Returns an array of hashrefs.
656 =cut
658 # --------------------------------------------------------------------
659 sub GetBudgetReport {
660 my ( $budget_id ) = @_;
661 my $dbh = C4::Context->dbh;
662 my $query = '
663 SELECT o.*, b.budget_name
664 FROM aqbudgets b
665 INNER JOIN aqorders o
666 ON b.budget_id = o.budget_id
667 WHERE b.budget_id=?
668 AND (o.orderstatus != "cancelled")
669 ORDER BY b.budget_name';
671 my $sth = $dbh->prepare($query);
672 $sth->execute( $budget_id );
674 my @results = ();
675 while ( my $data = $sth->fetchrow_hashref ) {
676 push( @results, $data );
678 return @results;
681 =head2 GetBudgetsByActivity
683 &GetBudgetsByActivity( $budget_period_active );
685 Get all active or inactive budgets, depending of the value
686 of the parameter.
688 1 = active
689 0 = inactive
691 =cut
693 # --------------------------------------------------------------------
694 sub GetBudgetsByActivity {
695 my ( $budget_period_active ) = @_;
696 my $dbh = C4::Context->dbh;
697 my $query = "
698 SELECT DISTINCT b.*
699 FROM aqbudgetperiods bp
700 INNER JOIN aqbudgets b
701 ON bp.budget_period_id = b.budget_period_id
702 WHERE bp.budget_period_active=?
704 my $sth = $dbh->prepare($query);
705 $sth->execute( $budget_period_active );
706 my @results = ();
707 while ( my $data = $sth->fetchrow_hashref ) {
708 push( @results, $data );
710 return @results;
712 # --------------------------------------------------------------------
714 =head2 GetBudgetsReport
716 &GetBudgetsReport( [$activity] );
718 Get all but cancelled orders for all funds.
720 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
722 active = 1
723 inactive = 0
725 Returns an array of hashrefs.
727 =cut
729 sub GetBudgetsReport {
730 my ($activity) = @_;
731 my $dbh = C4::Context->dbh;
732 my $query = '
733 SELECT o.*, b.budget_name
734 FROM aqbudgetperiods bp
735 INNER JOIN aqbudgets b
736 ON bp.budget_period_id = b.budget_period_id
737 INNER JOIN aqorders o
738 ON b.budget_id = o.budget_id ';
739 if($activity ne ''){
740 $query .= 'WHERE bp.budget_period_active=? ';
742 $query .= 'AND (o.orderstatus != "cancelled")
743 ORDER BY b.budget_name';
745 my $sth = $dbh->prepare($query);
746 if($activity ne ''){
747 $sth->execute($activity);
749 else{
750 $sth->execute;
752 my @results = ();
753 while ( my $data = $sth->fetchrow_hashref ) {
754 push( @results, $data );
756 return @results;
759 =head2 GetBudgetByCode
761 my $budget = &GetBudgetByCode($budget_code);
763 Retrieve all aqbudgets fields as a hashref for the budget that has
764 given budget_code
766 =cut
768 sub GetBudgetByCode {
769 my ( $budget_code ) = @_;
771 my $dbh = C4::Context->dbh;
772 my $query = qq{
773 SELECT *
774 FROM aqbudgets
775 WHERE budget_code = ?
776 ORDER BY budget_id DESC
777 LIMIT 1
779 my $sth = $dbh->prepare( $query );
780 $sth->execute( $budget_code );
781 return $sth->fetchrow_hashref;
784 =head2 GetBudgetHierarchySpent
786 my $spent = GetBudgetHierarchySpent( $budget_id );
788 Gets the total spent of the level and sublevels of $budget_id
790 =cut
792 sub GetBudgetHierarchySpent {
793 my ( $budget_id ) = @_;
794 my $dbh = C4::Context->dbh;
795 my $children_ids = $dbh->selectcol_arrayref(q|
796 SELECT budget_id
797 FROM aqbudgets
798 WHERE budget_parent_id = ?
799 |, {}, $budget_id );
801 my $total_spent = GetBudgetSpent( $budget_id );
802 for my $child_id ( @$children_ids ) {
803 $total_spent += GetBudgetHierarchySpent( $child_id );
805 return $total_spent;
808 =head2 GetBudgetHierarchyOrdered
810 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
812 Gets the total ordered of the level and sublevels of $budget_id
814 =cut
816 sub GetBudgetHierarchyOrdered {
817 my ( $budget_id ) = @_;
818 my $dbh = C4::Context->dbh;
819 my $children_ids = $dbh->selectcol_arrayref(q|
820 SELECT budget_id
821 FROM aqbudgets
822 WHERE budget_parent_id = ?
823 |, {}, $budget_id );
825 my $total_ordered = GetBudgetOrdered( $budget_id );
826 for my $child_id ( @$children_ids ) {
827 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
829 return $total_ordered;
832 =head2 GetBudgets
834 &GetBudgets($filter, $order_by);
836 gets all budgets
838 =cut
840 # -------------------------------------------------------------------
841 sub GetBudgets {
842 my ($filters, $orderby) = @_;
843 $orderby = 'budget_name' unless($orderby);
845 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
846 $rs = $rs->search( $filters, { order_by => $orderby } );
847 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
848 return [ $rs->all ];
851 =head2 GetBudgetUsers
853 my @borrowernumbers = &GetBudgetUsers($budget_id);
855 Return the list of borrowernumbers linked to a budget
857 =cut
859 sub GetBudgetUsers {
860 my ($budget_id) = @_;
862 my $dbh = C4::Context->dbh;
863 my $query = qq{
864 SELECT borrowernumber
865 FROM aqbudgetborrowers
866 WHERE budget_id = ?
868 my $sth = $dbh->prepare($query);
869 $sth->execute($budget_id);
871 my @borrowernumbers;
872 while (my ($borrowernumber) = $sth->fetchrow_array) {
873 push @borrowernumbers, $borrowernumber
876 return @borrowernumbers;
879 =head2 ModBudgetUsers
881 &ModBudgetUsers($budget_id, @borrowernumbers);
883 Modify the list of borrowernumbers linked to a budget
885 =cut
887 sub ModBudgetUsers {
888 my ($budget_id, @budget_users_id) = @_;
890 return unless $budget_id;
892 my $dbh = C4::Context->dbh;
893 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
894 my $sth = $dbh->prepare($query);
895 $sth->execute($budget_id);
897 $query = qq{
898 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
899 VALUES (?,?)
901 $sth = $dbh->prepare($query);
902 foreach my $borrowernumber (@budget_users_id) {
903 next unless $borrowernumber;
904 $sth->execute($budget_id, $borrowernumber);
908 sub CanUserUseBudget {
909 my ($borrower, $budget, $userflags) = @_;
911 if (not ref $borrower) {
912 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
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 = C4::Members::GetMember(borrowernumber => $borrower);
997 if (not ref $budget) {
998 $budget = GetBudget($budget);
1001 return 0 unless ($borrower and $budget);
1003 if (not defined $userflags) {
1004 $userflags = C4::Auth::getuserflags($borrower->{flags},
1005 $borrower->{userid});
1008 unless ($userflags->{superlibrarian}
1009 || (ref $userflags->{acquisition}
1010 && $userflags->{acquisition}->{budget_manage_all})
1011 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1013 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1014 return 0;
1017 if (ref $userflags->{acquisition}
1018 && !$userflags->{acquisition}->{budget_modify}) {
1019 return 0;
1023 return 1;
1026 sub _round {
1027 my ($value, $increment) = @_;
1029 if ($increment && $increment != 0) {
1030 $value = int($value / $increment) * $increment;
1033 return $value;
1036 =head2 CloneBudgetPeriod
1038 my $new_budget_period_id = CloneBudgetPeriod({
1039 budget_period_id => $budget_period_id,
1040 budget_period_startdate => $budget_period_startdate,
1041 budget_period_enddate => $budget_period_enddate,
1042 mark_original_budget_as_inactive => 1n
1043 reset_all_budgets => 1,
1046 Clone a budget period with all budgets.
1047 If the mark_origin_budget_as_inactive is set (0 by default),
1048 the original budget will be marked as inactive.
1050 If the reset_all_budgets is set (0 by default), all budget (fund)
1051 amounts will be reset.
1053 =cut
1055 sub CloneBudgetPeriod {
1056 my ($params) = @_;
1057 my $budget_period_id = $params->{budget_period_id};
1058 my $budget_period_startdate = $params->{budget_period_startdate};
1059 my $budget_period_enddate = $params->{budget_period_enddate};
1060 my $budget_period_description = $params->{budget_period_description};
1061 my $amount_change_percentage = $params->{amount_change_percentage};
1062 my $amount_change_round_increment = $params->{amount_change_round_increment};
1063 my $mark_original_budget_as_inactive =
1064 $params->{mark_original_budget_as_inactive} || 0;
1065 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1067 my $budget_period = GetBudgetPeriod($budget_period_id);
1069 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1070 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1071 $budget_period->{budget_period_description} = $budget_period_description;
1072 # The new budget (budget_period) should be active by default
1073 $budget_period->{budget_period_active} = 1;
1075 if ($amount_change_percentage) {
1076 my $total = $budget_period->{budget_period_total};
1077 $total += $total * $amount_change_percentage / 100;
1078 $total = _round($total, $amount_change_round_increment);
1079 $budget_period->{budget_period_total} = $total;
1082 my $original_budget_period_id = $budget_period->{budget_period_id};
1083 delete $budget_period->{budget_period_id};
1084 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1086 my $budgets = GetBudgetHierarchy($budget_period_id);
1087 CloneBudgetHierarchy(
1089 budgets => $budgets,
1090 new_budget_period_id => $new_budget_period_id
1094 if ($mark_original_budget_as_inactive) {
1095 ModBudgetPeriod(
1097 budget_period_id => $budget_period_id,
1098 budget_period_active => 0,
1103 if ( $reset_all_budgets ) {
1104 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1105 for my $budget ( @$budgets ) {
1106 $budget->{budget_amount} = 0;
1107 ModBudget( $budget );
1109 } elsif ($amount_change_percentage) {
1110 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1111 for my $budget ( @$budgets ) {
1112 my $amount = $budget->{budget_amount};
1113 $amount += $amount * $amount_change_percentage / 100;
1114 $amount = _round($amount, $amount_change_round_increment);
1115 $budget->{budget_amount} = $amount;
1116 ModBudget( $budget );
1120 return $new_budget_period_id;
1123 =head2 CloneBudgetHierarchy
1125 CloneBudgetHierarchy({
1126 budgets => $budgets,
1127 new_budget_period_id => $new_budget_period_id;
1130 Clone a budget hierarchy.
1132 =cut
1134 sub CloneBudgetHierarchy {
1135 my ($params) = @_;
1136 my $budgets = $params->{budgets};
1137 my $new_budget_period_id = $params->{new_budget_period_id};
1138 next unless @$budgets or $new_budget_period_id;
1140 my $children_of = $params->{children_of};
1141 my $new_parent_id = $params->{new_parent_id};
1143 my @first_level_budgets =
1144 ( not defined $children_of )
1145 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1146 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1148 # get only the columns of aqbudgets
1149 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1151 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1152 @first_level_budgets )
1155 my $tidy_budget =
1156 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1157 keys %$budget };
1158 my $new_budget_id = AddBudget(
1160 %$tidy_budget,
1161 budget_id => undef,
1162 budget_parent_id => $new_parent_id,
1163 budget_period_id => $new_budget_period_id
1166 CloneBudgetHierarchy(
1168 budgets => $budgets,
1169 new_budget_period_id => $new_budget_period_id,
1170 children_of => $budget->{budget_id},
1171 new_parent_id => $new_budget_id
1177 =head2 MoveOrders
1179 my $report = MoveOrders({
1180 from_budget_period_id => $from_budget_period_id,
1181 to_budget_period_id => $to_budget_period_id,
1184 Move orders from one budget period to another.
1186 =cut
1188 sub MoveOrders {
1189 my ($params) = @_;
1190 my $from_budget_period_id = $params->{from_budget_period_id};
1191 my $to_budget_period_id = $params->{to_budget_period_id};
1192 my $move_remaining_unspent = $params->{move_remaining_unspent};
1193 return
1194 if not $from_budget_period_id
1195 or not $to_budget_period_id
1196 or $from_budget_period_id == $to_budget_period_id;
1198 # Can't move orders to an inactive budget (budgetperiod)
1199 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1200 return unless $budget_period->{budget_period_active};
1202 my @report;
1203 my $dbh = C4::Context->dbh;
1204 my $sth_update_aqorders = $dbh->prepare(
1206 UPDATE aqorders
1207 SET budget_id = ?
1208 WHERE ordernumber = ?
1211 my $sth_update_budget_amount = $dbh->prepare(
1213 UPDATE aqbudgets
1214 SET budget_amount = ?
1215 WHERE budget_id = ?
1218 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1219 for my $from_budget (@$from_budgets) {
1220 my $new_budget_id = $dbh->selectcol_arrayref(
1222 SELECT budget_id
1223 FROM aqbudgets
1224 WHERE budget_period_id = ?
1225 AND budget_code = ?
1226 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1228 $new_budget_id = $new_budget_id->[0];
1229 my $new_budget = GetBudget( $new_budget_id );
1230 unless ( $new_budget ) {
1231 push @report,
1233 moved => 0,
1234 budget => $from_budget,
1235 error => 'budget_code_not_exists',
1237 next;
1239 my $orders_to_move = C4::Acquisition::SearchOrders(
1241 budget_id => $from_budget->{budget_id},
1242 pending => 1,
1246 my @orders_moved;
1247 for my $order (@$orders_to_move) {
1248 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1249 push @orders_moved, $order;
1252 my $unspent_moved = 0;
1253 if ($move_remaining_unspent) {
1254 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1255 my $unspent = $from_budget->{budget_amount} - $spent;
1256 my $new_budget_amount = $new_budget->{budget_amount};
1257 if ( $unspent > 0 ) {
1258 $new_budget_amount += $unspent;
1259 $unspent_moved = $unspent;
1261 $new_budget->{budget_amount} = $new_budget_amount;
1262 $sth_update_budget_amount->execute( $new_budget_amount,
1263 $new_budget->{budget_id} );
1266 push @report,
1268 budget => $new_budget,
1269 orders_moved => \@orders_moved,
1270 moved => 1,
1271 unspent_moved => $unspent_moved,
1274 return \@report;
1277 END { } # module clean-up code here (global destructor)
1280 __END__
1282 =head1 AUTHOR
1284 Koha Development Team <http://koha-community.org/>
1286 =cut