Bug 10760: (followup) Move street type after address
[koha.git] / C4 / Budgets.pm
blobd0c440025c43914caf4f5544627581d566035f8f
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 =head2 GetBudgetAuthCats
402 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
404 Return the list of authcat for a given budget_period_id
406 =cut
408 sub GetBudgetAuthCats {
409 my ($budget_period_id) = shift;
410 # now, populate the auth_cats_loop used in the budget planning button
411 # we must retrieve all auth values used by at least one budget
412 my $dbh = C4::Context->dbh;
413 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
414 $sth->execute($budget_period_id);
415 my %authcats;
416 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
417 $authcats{$sort1_authcat}=1 if $sort1_authcat;
418 $authcats{$sort2_authcat}=1 if $sort2_authcat;
420 return [ sort keys %authcats ];
423 # -------------------------------------------------------------------
424 sub GetBudgetPeriods {
425 my ($filters,$orderby) = @_;
427 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
428 $rs = $rs->search( $filters, { order_by => $orderby } );
429 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
430 return [ $rs->all ];
432 # -------------------------------------------------------------------
433 sub GetBudgetPeriod {
434 my ($budget_period_id) = @_;
435 my $dbh = C4::Context->dbh;
436 ## $total = number of records linked to the record that must be deleted
437 my $total = 0;
438 ## get information about the record that will be deleted
439 my $sth;
440 if ($budget_period_id) {
441 $sth = $dbh->prepare( qq|
442 SELECT *
443 FROM aqbudgetperiods
444 WHERE budget_period_id=? |
446 $sth->execute($budget_period_id);
447 } else { # ACTIVE BUDGET
448 $sth = $dbh->prepare(qq|
449 SELECT *
450 FROM aqbudgetperiods
451 WHERE budget_period_active=1 |
453 $sth->execute();
455 my $data = $sth->fetchrow_hashref;
456 return $data;
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;
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=? |
471 return $sth->execute($budget_period_id);
474 # -------------------------------------------------------------------
475 sub ModBudgetPeriod {
476 my ($budget_period) = @_;
477 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
478 return unless($result);
480 $result = $result->update($budget_period);
481 return $result->in_storage;
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)|;
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;
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;
510 } else {
511 if ($branchcode) {
512 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
513 push @bind_params, $branchcode;
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);
521 my %links;
522 # create hash with budget_id has key
523 while ( my $data = $sth->fetchrow_hashref ) {
524 $links{ $data->{'budget_id'} } = $data;
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'} = [];
538 # add as child
539 push @{ $parent->{'children'} }, $child;
541 } else {
542 push @first_parents, $child;
546 my @sort = ();
547 foreach my $first_parent (@first_parents) {
548 _add_budget_children(\@sort, $first_parent);
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} );
557 return \@sort;
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);
572 # -------------------------------------------------------------------
574 sub AddBudget {
575 my ($budget) = @_;
576 return unless ($budget);
578 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
579 return $resultset->create($budget)->id;
582 # -------------------------------------------------------------------
583 sub ModBudget {
584 my ($budget) = @_;
585 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
586 return unless($result);
588 $result = $result->update($budget);
589 return $result->in_storage;
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;
602 # -------------------------------------------------------------------
604 =head2 GetBudget
606 &GetBudget($budget_id);
608 get a specific budget
610 =cut
612 sub GetBudget {
613 my ( $budget_id ) = @_;
614 my $dbh = C4::Context->dbh;
615 my $query = "
616 SELECT *
617 FROM aqbudgets
618 WHERE budget_id=?
620 my $sth = $dbh->prepare($query);
621 $sth->execute( $budget_id );
622 my $result = $sth->fetchrow_hashref;
623 return $result;
626 # -------------------------------------------------------------------
628 =head2 GetBudgetByOrderNumber
630 &GetBudgetByOrderNumber($ordernumber);
632 get a specific budget by order number
634 =cut
636 sub GetBudgetByOrderNumber {
637 my ( $ordernumber ) = @_;
638 my $dbh = C4::Context->dbh;
639 my $query = "
640 SELECT aqbudgets.*
641 FROM aqbudgets, aqorders
642 WHERE ordernumber=?
643 AND aqorders.budget_id = aqbudgets.budget_id
645 my $sth = $dbh->prepare($query);
646 $sth->execute( $ordernumber );
647 my $result = $sth->fetchrow_hashref;
648 return $result;
651 =head2 GetBudgetReport
653 &GetBudgetReport( [$budget_id] );
655 Get all orders for a specific budget, without cancelled orders.
657 Returns an array of hashrefs.
659 =cut
661 # --------------------------------------------------------------------
662 sub GetBudgetReport {
663 my ( $budget_id ) = @_;
664 my $dbh = C4::Context->dbh;
665 my $query = '
666 SELECT o.*, b.budget_name
667 FROM aqbudgets b
668 INNER JOIN aqorders o
669 ON b.budget_id = o.budget_id
670 WHERE b.budget_id=?
671 AND (o.orderstatus != "cancelled")
672 ORDER BY b.budget_name';
674 my $sth = $dbh->prepare($query);
675 $sth->execute( $budget_id );
677 my @results = ();
678 while ( my $data = $sth->fetchrow_hashref ) {
679 push( @results, $data );
681 return @results;
684 =head2 GetBudgetsByActivity
686 &GetBudgetsByActivity( $budget_period_active );
688 Get all active or inactive budgets, depending of the value
689 of the parameter.
691 1 = active
692 0 = inactive
694 =cut
696 # --------------------------------------------------------------------
697 sub GetBudgetsByActivity {
698 my ( $budget_period_active ) = @_;
699 my $dbh = C4::Context->dbh;
700 my $query = "
701 SELECT DISTINCT b.*
702 FROM aqbudgetperiods bp
703 INNER JOIN aqbudgets b
704 ON bp.budget_period_id = b.budget_period_id
705 WHERE bp.budget_period_active=?
707 my $sth = $dbh->prepare($query);
708 $sth->execute( $budget_period_active );
709 my @results = ();
710 while ( my $data = $sth->fetchrow_hashref ) {
711 push( @results, $data );
713 return @results;
715 # --------------------------------------------------------------------
717 =head2 GetBudgetsReport
719 &GetBudgetsReport( [$activity] );
721 Get all but cancelled orders for all funds.
723 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
725 active = 1
726 inactive = 0
728 Returns an array of hashrefs.
730 =cut
732 sub GetBudgetsReport {
733 my ($activity) = @_;
734 my $dbh = C4::Context->dbh;
735 my $query = '
736 SELECT o.*, b.budget_name
737 FROM aqbudgetperiods bp
738 INNER JOIN aqbudgets b
739 ON bp.budget_period_id = b.budget_period_id
740 INNER JOIN aqorders o
741 ON b.budget_id = o.budget_id ';
742 if($activity ne ''){
743 $query .= 'WHERE bp.budget_period_active=? ';
745 $query .= 'AND (o.orderstatus != "cancelled")
746 ORDER BY b.budget_name';
748 my $sth = $dbh->prepare($query);
749 if($activity ne ''){
750 $sth->execute($activity);
752 else{
753 $sth->execute;
755 my @results = ();
756 while ( my $data = $sth->fetchrow_hashref ) {
757 push( @results, $data );
759 return @results;
762 =head2 GetBudgetByCode
764 my $budget = &GetBudgetByCode($budget_code);
766 Retrieve all aqbudgets fields as a hashref for the budget that has
767 given budget_code
769 =cut
771 sub GetBudgetByCode {
772 my ( $budget_code ) = @_;
774 my $dbh = C4::Context->dbh;
775 my $query = qq{
776 SELECT *
777 FROM aqbudgets
778 WHERE budget_code = ?
779 ORDER BY budget_id DESC
780 LIMIT 1
782 my $sth = $dbh->prepare( $query );
783 $sth->execute( $budget_code );
784 return $sth->fetchrow_hashref;
787 =head2 GetBudgetHierarchySpent
789 my $spent = GetBudgetHierarchySpent( $budget_id );
791 Gets the total spent of the level and sublevels of $budget_id
793 =cut
795 sub GetBudgetHierarchySpent {
796 my ( $budget_id ) = @_;
797 my $dbh = C4::Context->dbh;
798 my $children_ids = $dbh->selectcol_arrayref(q|
799 SELECT budget_id
800 FROM aqbudgets
801 WHERE budget_parent_id = ?
802 |, {}, $budget_id );
804 my $total_spent = GetBudgetSpent( $budget_id );
805 for my $child_id ( @$children_ids ) {
806 $total_spent += GetBudgetHierarchySpent( $child_id );
808 return $total_spent;
811 =head2 GetBudgetHierarchyOrdered
813 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
815 Gets the total ordered of the level and sublevels of $budget_id
817 =cut
819 sub GetBudgetHierarchyOrdered {
820 my ( $budget_id ) = @_;
821 my $dbh = C4::Context->dbh;
822 my $children_ids = $dbh->selectcol_arrayref(q|
823 SELECT budget_id
824 FROM aqbudgets
825 WHERE budget_parent_id = ?
826 |, {}, $budget_id );
828 my $total_ordered = GetBudgetOrdered( $budget_id );
829 for my $child_id ( @$children_ids ) {
830 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
832 return $total_ordered;
835 =head2 GetBudgets
837 &GetBudgets($filter, $order_by);
839 gets all budgets
841 =cut
843 # -------------------------------------------------------------------
844 sub GetBudgets {
845 my ($filters, $orderby) = @_;
846 $orderby = 'budget_name' unless($orderby);
848 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
849 $rs = $rs->search( $filters, { order_by => $orderby } );
850 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
851 return [ $rs->all ];
854 =head2 GetBudgetUsers
856 my @borrowernumbers = &GetBudgetUsers($budget_id);
858 Return the list of borrowernumbers linked to a budget
860 =cut
862 sub GetBudgetUsers {
863 my ($budget_id) = @_;
865 my $dbh = C4::Context->dbh;
866 my $query = qq{
867 SELECT borrowernumber
868 FROM aqbudgetborrowers
869 WHERE budget_id = ?
871 my $sth = $dbh->prepare($query);
872 $sth->execute($budget_id);
874 my @borrowernumbers;
875 while (my ($borrowernumber) = $sth->fetchrow_array) {
876 push @borrowernumbers, $borrowernumber
879 return @borrowernumbers;
882 =head2 ModBudgetUsers
884 &ModBudgetUsers($budget_id, @borrowernumbers);
886 Modify the list of borrowernumbers linked to a budget
888 =cut
890 sub ModBudgetUsers {
891 my ($budget_id, @budget_users_id) = @_;
893 return unless $budget_id;
895 my $dbh = C4::Context->dbh;
896 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
897 my $sth = $dbh->prepare($query);
898 $sth->execute($budget_id);
900 $query = qq{
901 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
902 VALUES (?,?)
904 $sth = $dbh->prepare($query);
905 foreach my $borrowernumber (@budget_users_id) {
906 next unless $borrowernumber;
907 $sth->execute($budget_id, $borrowernumber);
911 sub CanUserUseBudget {
912 my ($borrower, $budget, $userflags) = @_;
914 if (not ref $borrower) {
915 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
917 if (not ref $budget) {
918 $budget = GetBudget($budget);
921 return 0 unless ($borrower and $budget);
923 if (not defined $userflags) {
924 $userflags = C4::Auth::getuserflags($borrower->{flags},
925 $borrower->{userid});
928 unless ($userflags->{superlibrarian}
929 || (ref $userflags->{acquisition}
930 && $userflags->{acquisition}->{budget_manage_all})
931 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
933 if (not exists $userflags->{acquisition}) {
934 return 0;
937 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
938 return 0;
941 # Budget restricted to owner
942 if ( $budget->{budget_permission} == 1 ) {
943 if ( $budget->{budget_owner_id}
944 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
946 return 0;
950 # Budget restricted to owner, users and library
951 elsif ( $budget->{budget_permission} == 2 ) {
952 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
954 if (
956 $budget->{budget_owner_id}
957 and $budget->{budget_owner_id} !=
958 $borrower->{borrowernumber}
959 or not $budget->{budget_owner_id}
961 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
962 @budget_users )
963 and defined $budget->{budget_branchcode}
964 and $budget->{budget_branchcode} ne
965 C4::Context->userenv->{branch}
968 return 0;
972 # Budget restricted to owner and users
973 elsif ( $budget->{budget_permission} == 3 ) {
974 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
975 if (
977 $budget->{budget_owner_id}
978 and $budget->{budget_owner_id} !=
979 $borrower->{borrowernumber}
980 or not $budget->{budget_owner_id}
982 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
983 @budget_users )
986 return 0;
991 return 1;
994 sub CanUserModifyBudget {
995 my ($borrower, $budget, $userflags) = @_;
997 if (not ref $borrower) {
998 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
1000 if (not ref $budget) {
1001 $budget = GetBudget($budget);
1004 return 0 unless ($borrower and $budget);
1006 if (not defined $userflags) {
1007 $userflags = C4::Auth::getuserflags($borrower->{flags},
1008 $borrower->{userid});
1011 unless ($userflags->{superlibrarian}
1012 || (ref $userflags->{acquisition}
1013 && $userflags->{acquisition}->{budget_manage_all})
1014 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1016 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1017 return 0;
1020 if (ref $userflags->{acquisition}
1021 && !$userflags->{acquisition}->{budget_modify}) {
1022 return 0;
1026 return 1;
1029 sub _round {
1030 my ($value, $increment) = @_;
1032 if ($increment && $increment != 0) {
1033 $value = int($value / $increment) * $increment;
1036 return $value;
1039 =head2 CloneBudgetPeriod
1041 my $new_budget_period_id = CloneBudgetPeriod({
1042 budget_period_id => $budget_period_id,
1043 budget_period_startdate => $budget_period_startdate,
1044 budget_period_enddate => $budget_period_enddate,
1045 mark_original_budget_as_inactive => 1n
1046 reset_all_budgets => 1,
1049 Clone a budget period with all budgets.
1050 If the mark_origin_budget_as_inactive is set (0 by default),
1051 the original budget will be marked as inactive.
1053 If the reset_all_budgets is set (0 by default), all budget (fund)
1054 amounts will be reset.
1056 =cut
1058 sub CloneBudgetPeriod {
1059 my ($params) = @_;
1060 my $budget_period_id = $params->{budget_period_id};
1061 my $budget_period_startdate = $params->{budget_period_startdate};
1062 my $budget_period_enddate = $params->{budget_period_enddate};
1063 my $budget_period_description = $params->{budget_period_description};
1064 my $amount_change_percentage = $params->{amount_change_percentage};
1065 my $amount_change_round_increment = $params->{amount_change_round_increment};
1066 my $mark_original_budget_as_inactive =
1067 $params->{mark_original_budget_as_inactive} || 0;
1068 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1070 my $budget_period = GetBudgetPeriod($budget_period_id);
1072 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1073 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1074 $budget_period->{budget_period_description} = $budget_period_description;
1075 # The new budget (budget_period) should be active by default
1076 $budget_period->{budget_period_active} = 1;
1078 if ($amount_change_percentage) {
1079 my $total = $budget_period->{budget_period_total};
1080 $total += $total * $amount_change_percentage / 100;
1081 $total = _round($total, $amount_change_round_increment);
1082 $budget_period->{budget_period_total} = $total;
1085 my $original_budget_period_id = $budget_period->{budget_period_id};
1086 delete $budget_period->{budget_period_id};
1087 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1089 my $budgets = GetBudgetHierarchy($budget_period_id);
1090 CloneBudgetHierarchy(
1092 budgets => $budgets,
1093 new_budget_period_id => $new_budget_period_id
1097 if ($mark_original_budget_as_inactive) {
1098 ModBudgetPeriod(
1100 budget_period_id => $budget_period_id,
1101 budget_period_active => 0,
1106 if ( $reset_all_budgets ) {
1107 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1108 for my $budget ( @$budgets ) {
1109 $budget->{budget_amount} = 0;
1110 ModBudget( $budget );
1112 } elsif ($amount_change_percentage) {
1113 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1114 for my $budget ( @$budgets ) {
1115 my $amount = $budget->{budget_amount};
1116 $amount += $amount * $amount_change_percentage / 100;
1117 $amount = _round($amount, $amount_change_round_increment);
1118 $budget->{budget_amount} = $amount;
1119 ModBudget( $budget );
1123 return $new_budget_period_id;
1126 =head2 CloneBudgetHierarchy
1128 CloneBudgetHierarchy({
1129 budgets => $budgets,
1130 new_budget_period_id => $new_budget_period_id;
1133 Clone a budget hierarchy.
1135 =cut
1137 sub CloneBudgetHierarchy {
1138 my ($params) = @_;
1139 my $budgets = $params->{budgets};
1140 my $new_budget_period_id = $params->{new_budget_period_id};
1141 next unless @$budgets or $new_budget_period_id;
1143 my $children_of = $params->{children_of};
1144 my $new_parent_id = $params->{new_parent_id};
1146 my @first_level_budgets =
1147 ( not defined $children_of )
1148 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1149 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1151 # get only the columns of aqbudgets
1152 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1154 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1155 @first_level_budgets )
1158 my $tidy_budget =
1159 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1160 keys %$budget };
1161 my $new_budget_id = AddBudget(
1163 %$tidy_budget,
1164 budget_id => undef,
1165 budget_parent_id => $new_parent_id,
1166 budget_period_id => $new_budget_period_id
1169 CloneBudgetHierarchy(
1171 budgets => $budgets,
1172 new_budget_period_id => $new_budget_period_id,
1173 children_of => $budget->{budget_id},
1174 new_parent_id => $new_budget_id
1180 =head2 MoveOrders
1182 my $report = MoveOrders({
1183 from_budget_period_id => $from_budget_period_id,
1184 to_budget_period_id => $to_budget_period_id,
1187 Move orders from one budget period to another.
1189 =cut
1191 sub MoveOrders {
1192 my ($params) = @_;
1193 my $from_budget_period_id = $params->{from_budget_period_id};
1194 my $to_budget_period_id = $params->{to_budget_period_id};
1195 my $move_remaining_unspent = $params->{move_remaining_unspent};
1196 return
1197 if not $from_budget_period_id
1198 or not $to_budget_period_id
1199 or $from_budget_period_id == $to_budget_period_id;
1201 # Can't move orders to an inactive budget (budgetperiod)
1202 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1203 return unless $budget_period->{budget_period_active};
1205 my @report;
1206 my $dbh = C4::Context->dbh;
1207 my $sth_update_aqorders = $dbh->prepare(
1209 UPDATE aqorders
1210 SET budget_id = ?
1211 WHERE ordernumber = ?
1214 my $sth_update_budget_amount = $dbh->prepare(
1216 UPDATE aqbudgets
1217 SET budget_amount = ?
1218 WHERE budget_id = ?
1221 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1222 for my $from_budget (@$from_budgets) {
1223 my $new_budget_id = $dbh->selectcol_arrayref(
1225 SELECT budget_id
1226 FROM aqbudgets
1227 WHERE budget_period_id = ?
1228 AND budget_code = ?
1229 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1231 $new_budget_id = $new_budget_id->[0];
1232 my $new_budget = GetBudget( $new_budget_id );
1233 unless ( $new_budget ) {
1234 push @report,
1236 moved => 0,
1237 budget => $from_budget,
1238 error => 'budget_code_not_exists',
1240 next;
1242 my $orders_to_move = C4::Acquisition::SearchOrders(
1244 budget_id => $from_budget->{budget_id},
1245 pending => 1,
1249 my @orders_moved;
1250 for my $order (@$orders_to_move) {
1251 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1252 push @orders_moved, $order;
1255 my $unspent_moved = 0;
1256 if ($move_remaining_unspent) {
1257 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1258 my $unspent = $from_budget->{budget_amount} - $spent;
1259 my $new_budget_amount = $new_budget->{budget_amount};
1260 if ( $unspent > 0 ) {
1261 $new_budget_amount += $unspent;
1262 $unspent_moved = $unspent;
1264 $new_budget->{budget_amount} = $new_budget_amount;
1265 $sth_update_budget_amount->execute( $new_budget_amount,
1266 $new_budget->{budget_id} );
1269 push @report,
1271 budget => $new_budget,
1272 orders_moved => \@orders_moved,
1273 moved => 1,
1274 unspent_moved => $unspent_moved,
1277 return \@report;
1280 END { } # module clean-up code here (global destructor)
1283 __END__
1285 =head1 AUTHOR
1287 Koha Development Team <http://koha-community.org/>
1289 =cut