Bug 15008 - Add custom HTML areas to circulation and reports home pages
[koha.git] / C4 / Budgets.pm
blobdb936be0c497ac5e34d37856d2f4bb0ef55c3cc4
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 &GetBudgetHierarchy
37 &AddBudget
38 &ModBudget
39 &DelBudget
40 &GetBudgetSpent
41 &GetBudgetOrdered
42 &GetBudgetName
43 &GetPeriodsCount
44 GetBudgetHierarchySpent
45 GetBudgetHierarchyOrdered
47 &GetBudgetUsers
48 &ModBudgetUsers
49 &CanUserUseBudget
50 &CanUserModifyBudget
52 &GetBudgetPeriod
53 &GetBudgetPeriods
54 &ModBudgetPeriod
55 &AddBudgetPeriod
56 &DelBudgetPeriod
58 &ModBudgetPlan
60 &GetBudgetsPlanCell
61 &AddBudgetPlanValue
62 &GetBudgetAuthCats
63 &BudgetHasChildren
64 &CheckBudgetParent
65 &CheckBudgetParentPerm
67 &HideCols
68 &GetCols
72 # ----------------------------BUDGETS.PM-----------------------------";
75 =head1 FUNCTIONS ABOUT BUDGETS
77 =cut
79 sub HideCols {
80 my ( $authcat, @hide_cols ) = @_;
81 my $dbh = C4::Context->dbh;
83 my $sth1 = $dbh->prepare(
84 qq|
85 UPDATE aqbudgets_planning SET display = 0
86 WHERE authcat = ?
87 AND authvalue = ? |
89 foreach my $authvalue (@hide_cols) {
90 # $sth1->{TraceLevel} = 3;
91 $sth1->execute( $authcat, $authvalue );
95 sub GetCols {
96 my ( $authcat, $authvalue ) = @_;
98 my $dbh = C4::Context->dbh;
99 my $sth = $dbh->prepare(
101 SELECT count(display) as cnt from aqbudgets_planning
102 WHERE authcat = ?
103 AND authvalue = ? and display = 0 |
106 # $sth->{TraceLevel} = 3;
107 $sth->execute( $authcat, $authvalue );
108 my $res = $sth->fetchrow_hashref;
110 return $res->{cnt} > 0 ? 0: 1
114 sub CheckBudgetParentPerm {
115 my ( $budget, $borrower_id ) = @_;
116 my $depth = $budget->{depth};
117 my $parent_id = $budget->{budget_parent_id};
118 while ($depth) {
119 my $parent = GetBudget($parent_id);
120 $parent_id = $parent->{budget_parent_id};
121 if ( $parent->{budget_owner_id} == $borrower_id ) {
122 return 1;
124 $depth--
126 return 0;
129 sub AddBudgetPeriod {
130 my ($budgetperiod) = @_;
131 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
133 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
134 return $resultset->create($budgetperiod)->id;
136 # -------------------------------------------------------------------
137 sub GetPeriodsCount {
138 my $dbh = C4::Context->dbh;
139 my $sth = $dbh->prepare("
140 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
141 $sth->execute();
142 my $res = $sth->fetchrow_hashref;
143 return $res->{'sum'};
146 # -------------------------------------------------------------------
147 sub CheckBudgetParent {
148 my ( $new_parent, $budget ) = @_;
149 my $new_parent_id = $new_parent->{'budget_id'};
150 my $budget_id = $budget->{'budget_id'};
151 my $dbh = C4::Context->dbh;
152 my $parent_id_tmp = $new_parent_id;
154 # check new-parent is not a child (or a child's child ;)
155 my $sth = $dbh->prepare(qq|
156 SELECT budget_parent_id FROM
157 aqbudgets where budget_id = ? | );
158 while (1) {
159 $sth->execute($parent_id_tmp);
160 my $res = $sth->fetchrow_hashref;
161 if ( $res->{'budget_parent_id'} == $budget_id ) {
162 return 1;
164 if ( not defined $res->{'budget_parent_id'} ) {
165 return 0;
167 $parent_id_tmp = $res->{'budget_parent_id'};
171 # -------------------------------------------------------------------
172 sub BudgetHasChildren {
173 my ( $budget_id ) = @_;
174 my $dbh = C4::Context->dbh;
175 my $sth = $dbh->prepare(qq|
176 SELECT count(*) as sum FROM aqbudgets
177 WHERE budget_parent_id = ? | );
178 $sth->execute( $budget_id );
179 my $sum = $sth->fetchrow_hashref;
180 return $sum->{'sum'};
183 sub GetBudgetChildren {
184 my ( $budget_id ) = @_;
185 my $dbh = C4::Context->dbh;
186 return $dbh->selectall_arrayref(q|
187 SELECT * FROM aqbudgets
188 WHERE budget_parent_id = ?
189 |, { Slice => {} }, $budget_id );
192 sub SetOwnerToFundHierarchy {
193 my ( $budget_id, $borrowernumber ) = @_;
195 my $budget = GetBudget( $budget_id );
196 $budget->{budget_owner_id} = $borrowernumber;
197 ModBudget( $budget );
198 my $children = GetBudgetChildren( $budget_id );
199 for my $child ( @$children ) {
200 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
204 # -------------------------------------------------------------------
205 sub GetBudgetsPlanCell {
206 my ( $cell, $period, $budget ) = @_;
207 my ($actual, $sth);
208 my $dbh = C4::Context->dbh;
209 if ( $cell->{'authcat'} eq 'MONTHS' ) {
210 # get the actual amount
211 $sth = $dbh->prepare( qq|
213 SELECT SUM(ecost) AS actual FROM aqorders
214 WHERE budget_id = ? AND
215 entrydate like "$cell->{'authvalue'}%" |
217 $sth->execute( $cell->{'budget_id'} );
218 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
219 # get the actual amount
220 $sth = $dbh->prepare( qq|
222 SELECT SUM(ecost) FROM aqorders
223 LEFT JOIN aqorders_items
224 ON (aqorders.ordernumber = aqorders_items.ordernumber)
225 LEFT JOIN items
226 ON (aqorders_items.itemnumber = items.itemnumber)
227 WHERE budget_id = ? AND homebranch = ? | );
229 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
230 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
231 # get the actual amount
232 $sth = $dbh->prepare( qq|
234 SELECT SUM( ecost * quantity) AS actual
235 FROM aqorders JOIN biblioitems
236 ON (biblioitems.biblionumber = aqorders.biblionumber )
237 WHERE aqorders.budget_id = ? and itemtype = ? |
239 $sth->execute( $cell->{'budget_id'},
240 $cell->{'authvalue'} );
242 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
243 else {
244 # get the actual amount
245 $sth = $dbh->prepare( qq|
247 SELECT SUM(ecost * quantity) AS actual
248 FROM aqorders
249 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
250 WHERE aqorders.budget_id = ? AND
251 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
252 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
254 $sth->execute( $cell->{'budget_id'},
255 $budget->{'sort1_authcat'},
256 $cell->{'authvalue'},
257 $budget->{'sort2_authcat'},
258 $cell->{'authvalue'}
261 $actual = $sth->fetchrow_array;
263 # get the estimated amount
264 $sth = $dbh->prepare( qq|
266 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
267 WHERE budget_period_id = ? AND
268 budget_id = ? AND
269 authvalue = ? AND
270 authcat = ? |
272 $sth->execute( $cell->{'budget_period_id'},
273 $cell->{'budget_id'},
274 $cell->{'authvalue'},
275 $cell->{'authcat'},
279 my $res = $sth->fetchrow_hashref;
280 # my $display = $res->{'display'};
281 my $estimated = $res->{'estimated'};
284 return $actual, $estimated;
287 # -------------------------------------------------------------------
288 sub ModBudgetPlan {
289 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
290 my $dbh = C4::Context->dbh;
291 foreach my $buds (@$budget_plan) {
292 my $lines = $buds->{lines};
293 my $sth = $dbh->prepare( qq|
294 DELETE FROM aqbudgets_planning
295 WHERE budget_period_id = ? AND
296 budget_id = ? AND
297 authcat = ? |
299 #delete a aqplan line of cells, then insert new cells,
300 # these could be UPDATES rather than DEL/INSERTS...
301 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
303 foreach my $cell (@$lines) {
304 my $sth = $dbh->prepare( qq|
306 INSERT INTO aqbudgets_planning
307 SET budget_id = ?,
308 budget_period_id = ?,
309 authcat = ?,
310 estimated_amount = ?,
311 authvalue = ? |
313 $sth->execute(
314 $cell->{'budget_id'},
315 $cell->{'budget_period_id'},
316 $cell->{'authcat'},
317 $cell->{'estimated_amount'},
318 $cell->{'authvalue'},
324 # -------------------------------------------------------------------
325 sub GetBudgetSpent {
326 my ($budget_id) = @_;
327 my $dbh = C4::Context->dbh;
328 my $sth = $dbh->prepare(qq|
329 SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
330 WHERE budget_id = ? AND
331 quantityreceived > 0 AND
332 datecancellationprinted IS NULL
334 $sth->execute($budget_id);
335 my $sum = $sth->fetchrow_array;
337 $sth = $dbh->prepare(qq|
338 SELECT SUM(shipmentcost) AS sum
339 FROM aqinvoices
340 WHERE shipmentcost_budgetid = ?
341 AND closedate IS NOT NULL
343 $sth->execute($budget_id);
344 my ($shipmentcost_sum) = $sth->fetchrow_array;
345 $sum += $shipmentcost_sum;
347 return $sum;
350 # -------------------------------------------------------------------
351 sub GetBudgetOrdered {
352 my ($budget_id) = @_;
353 my $dbh = C4::Context->dbh;
354 my $sth = $dbh->prepare(qq|
355 SELECT SUM(ecost * quantity) AS sum FROM aqorders
356 WHERE budget_id = ? AND
357 quantityreceived = 0 AND
358 datecancellationprinted IS NULL
360 $sth->execute($budget_id);
361 my $sum = $sth->fetchrow_array;
363 $sth = $dbh->prepare(qq|
364 SELECT SUM(shipmentcost) AS sum
365 FROM aqinvoices
366 WHERE shipmentcost_budgetid = ?
367 AND closedate IS NULL
369 $sth->execute($budget_id);
370 my ($shipmentcost_sum) = $sth->fetchrow_array;
371 $sum += $shipmentcost_sum;
373 return $sum;
376 =head2 GetBudgetName
378 my $budget_name = &GetBudgetName($budget_id);
380 get the budget_name for a given budget_id
382 =cut
384 sub GetBudgetName {
385 my ( $budget_id ) = @_;
386 my $dbh = C4::Context->dbh;
387 my $sth = $dbh->prepare(
389 SELECT budget_name
390 FROM aqbudgets
391 WHERE budget_id = ?
394 $sth->execute($budget_id);
395 return $sth->fetchrow_array;
398 # -------------------------------------------------------------------
399 sub GetBudgetAuthCats {
400 my ($budget_period_id) = shift;
401 # now, populate the auth_cats_loop used in the budget planning button
402 # we must retrieve all auth values used by at least one budget
403 my $dbh = C4::Context->dbh;
404 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
405 $sth->execute($budget_period_id);
406 my %authcats;
407 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
408 $authcats{$sort1_authcat}=1;
409 $authcats{$sort2_authcat}=1;
411 my @auth_cats_loop;
412 foreach (sort keys %authcats) {
413 push @auth_cats_loop,{ authcat => $_ };
415 return \@auth_cats_loop;
418 # -------------------------------------------------------------------
419 sub GetBudgetPeriods {
420 my ($filters,$orderby) = @_;
422 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
423 $rs = $rs->search( $filters, { order_by => $orderby } );
424 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
425 return [ $rs->all ];
427 # -------------------------------------------------------------------
428 sub GetBudgetPeriod {
429 my ($budget_period_id) = @_;
430 my $dbh = C4::Context->dbh;
431 ## $total = number of records linked to the record that must be deleted
432 my $total = 0;
433 ## get information about the record that will be deleted
434 my $sth;
435 if ($budget_period_id) {
436 $sth = $dbh->prepare( qq|
437 SELECT *
438 FROM aqbudgetperiods
439 WHERE budget_period_id=? |
441 $sth->execute($budget_period_id);
442 } else { # ACTIVE BUDGET
443 $sth = $dbh->prepare(qq|
444 SELECT *
445 FROM aqbudgetperiods
446 WHERE budget_period_active=1 |
448 $sth->execute();
450 my $data = $sth->fetchrow_hashref;
451 return $data;
454 # -------------------------------------------------------------------
455 sub DelBudgetPeriod{
456 my ($budget_period_id) = @_;
457 my $dbh = C4::Context->dbh;
458 ; ## $total = number of records linked to the record that must be deleted
459 my $total = 0;
461 ## get information about the record that will be deleted
462 my $sth = $dbh->prepare(qq|
463 DELETE
464 FROM aqbudgetperiods
465 WHERE budget_period_id=? |
467 return $sth->execute($budget_period_id);
470 # -------------------------------------------------------------------
471 sub ModBudgetPeriod {
472 my ($budget_period) = @_;
473 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
474 return unless($result);
476 $result = $result->update($budget_period);
477 return $result->in_storage;
480 # -------------------------------------------------------------------
481 sub GetBudgetHierarchy {
482 my ( $budget_period_id, $branchcode, $owner ) = @_;
483 my @bind_params;
484 my $dbh = C4::Context->dbh;
485 my $query = qq|
486 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
487 FROM aqbudgets
488 JOIN aqbudgetperiods USING (budget_period_id)|;
490 my @where_strings;
491 # show only period X if requested
492 if ($budget_period_id) {
493 push @where_strings," aqbudgets.budget_period_id = ?";
494 push @bind_params, $budget_period_id;
496 # show only budgets owned by me, my branch or everyone
497 if ($owner) {
498 if ($branchcode) {
499 push @where_strings,
500 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="")))};
501 push @bind_params, ( $owner, $branchcode );
502 } else {
503 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
504 push @bind_params, $owner;
506 } else {
507 if ($branchcode) {
508 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
509 push @bind_params, $branchcode;
512 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
513 $debug && warn $query,join(",",@bind_params);
514 my $sth = $dbh->prepare($query);
515 $sth->execute(@bind_params);
517 my %links;
518 # create hash with budget_id has key
519 while ( my $data = $sth->fetchrow_hashref ) {
520 $links{ $data->{'budget_id'} } = $data;
523 # link child to parent
524 my @first_parents;
525 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
526 my $child = $links{$budget->{budget_id}};
527 if ( $child->{'budget_parent_id'} ) {
528 my $parent = $links{ $child->{'budget_parent_id'} };
529 if ($parent) {
530 unless ( $parent->{'children'} ) {
531 # init child arrayref
532 $parent->{'children'} = [];
534 # add as child
535 push @{ $parent->{'children'} }, $child;
537 } else {
538 push @first_parents, $child;
542 my @sort = ();
543 foreach my $first_parent (@first_parents) {
544 _add_budget_children(\@sort, $first_parent);
547 foreach my $budget (@sort) {
548 $budget->{budget_spent} = GetBudgetSpent( $budget->{budget_id} );
549 $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
550 $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
551 $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
553 return \@sort;
556 # Recursive method to add a budget and its chidren to an array
557 sub _add_budget_children {
558 my $res = shift;
559 my $budget = shift;
560 push @$res, $budget;
561 my $children = $budget->{'children'} || [];
562 return unless @$children; # break recursivity
563 foreach my $child (@$children) {
564 _add_budget_children($res, $child);
568 # -------------------------------------------------------------------
570 sub AddBudget {
571 my ($budget) = @_;
572 return unless ($budget);
574 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
575 return $resultset->create($budget)->id;
578 # -------------------------------------------------------------------
579 sub ModBudget {
580 my ($budget) = @_;
581 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
582 return unless($result);
584 $result = $result->update($budget);
585 return $result->in_storage;
588 # -------------------------------------------------------------------
589 sub DelBudget {
590 my ($budget_id) = @_;
591 my $dbh = C4::Context->dbh;
592 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
593 my $rc = $sth->execute($budget_id);
594 return $rc;
598 =head2 GetBudget
600 &GetBudget($budget_id);
602 get a specific budget
604 =cut
606 # -------------------------------------------------------------------
607 sub GetBudget {
608 my ( $budget_id ) = @_;
609 my $dbh = C4::Context->dbh;
610 my $query = "
611 SELECT *
612 FROM aqbudgets
613 WHERE budget_id=?
615 my $sth = $dbh->prepare($query);
616 $sth->execute( $budget_id );
617 my $result = $sth->fetchrow_hashref;
618 return $result;
621 =head2 GetBudgetByOrderNumber
623 &GetBudgetByOrderNumber($ordernumber);
625 get a specific budget by order number
627 =cut
629 # -------------------------------------------------------------------
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 GetBudgetByCode
647 my $budget = &GetBudgetByCode($budget_code);
649 Retrieve all aqbudgets fields as a hashref for the budget that has
650 given budget_code
652 =cut
654 sub GetBudgetByCode {
655 my ( $budget_code ) = @_;
657 my $dbh = C4::Context->dbh;
658 my $query = qq{
659 SELECT *
660 FROM aqbudgets
661 WHERE budget_code = ?
662 ORDER BY budget_id DESC
663 LIMIT 1
665 my $sth = $dbh->prepare( $query );
666 $sth->execute( $budget_code );
667 return $sth->fetchrow_hashref;
670 =head2 GetBudgetHierarchySpent
672 my $spent = GetBudgetHierarchySpent( $budget_id );
674 Gets the total spent of the level and sublevels of $budget_id
676 =cut
678 sub GetBudgetHierarchySpent {
679 my ( $budget_id ) = @_;
680 my $dbh = C4::Context->dbh;
681 my $children_ids = $dbh->selectcol_arrayref(q|
682 SELECT budget_id
683 FROM aqbudgets
684 WHERE budget_parent_id = ?
685 |, {}, $budget_id );
687 my $total_spent = GetBudgetSpent( $budget_id );
688 for my $child_id ( @$children_ids ) {
689 $total_spent += GetBudgetHierarchySpent( $child_id );
691 return $total_spent;
694 =head2 GetBudgetHierarchyOrdered
696 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
698 Gets the total ordered of the level and sublevels of $budget_id
700 =cut
702 sub GetBudgetHierarchyOrdered {
703 my ( $budget_id ) = @_;
704 my $dbh = C4::Context->dbh;
705 my $children_ids = $dbh->selectcol_arrayref(q|
706 SELECT budget_id
707 FROM aqbudgets
708 WHERE budget_parent_id = ?
709 |, {}, $budget_id );
711 my $total_ordered = GetBudgetOrdered( $budget_id );
712 for my $child_id ( @$children_ids ) {
713 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
715 return $total_ordered;
718 =head2 GetBudgets
720 &GetBudgets($filter, $order_by);
722 gets all budgets
724 =cut
726 # -------------------------------------------------------------------
727 sub GetBudgets {
728 my ($filters, $orderby) = @_;
729 $orderby = 'budget_name' unless($orderby);
731 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
732 $rs = $rs->search( $filters, { order_by => $orderby } );
733 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
734 return [ $rs->all ];
737 =head2 GetBudgetUsers
739 my @borrowernumbers = &GetBudgetUsers($budget_id);
741 Return the list of borrowernumbers linked to a budget
743 =cut
745 sub GetBudgetUsers {
746 my ($budget_id) = @_;
748 my $dbh = C4::Context->dbh;
749 my $query = qq{
750 SELECT borrowernumber
751 FROM aqbudgetborrowers
752 WHERE budget_id = ?
754 my $sth = $dbh->prepare($query);
755 $sth->execute($budget_id);
757 my @borrowernumbers;
758 while (my ($borrowernumber) = $sth->fetchrow_array) {
759 push @borrowernumbers, $borrowernumber
762 return @borrowernumbers;
765 =head2 ModBudgetUsers
767 &ModBudgetUsers($budget_id, @borrowernumbers);
769 Modify the list of borrowernumbers linked to a budget
771 =cut
773 sub ModBudgetUsers {
774 my ($budget_id, @budget_users_id) = @_;
776 return unless $budget_id;
778 my $dbh = C4::Context->dbh;
779 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
780 my $sth = $dbh->prepare($query);
781 $sth->execute($budget_id);
783 $query = qq{
784 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
785 VALUES (?,?)
787 $sth = $dbh->prepare($query);
788 foreach my $borrowernumber (@budget_users_id) {
789 next unless $borrowernumber;
790 $sth->execute($budget_id, $borrowernumber);
794 sub CanUserUseBudget {
795 my ($borrower, $budget, $userflags) = @_;
797 if (not ref $borrower) {
798 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
800 if (not ref $budget) {
801 $budget = GetBudget($budget);
804 return 0 unless ($borrower and $budget);
806 if (not defined $userflags) {
807 $userflags = C4::Auth::getuserflags($borrower->{flags},
808 $borrower->{userid});
811 unless ($userflags->{superlibrarian}
812 || (ref $userflags->{acquisition}
813 && $userflags->{acquisition}->{budget_manage_all})
814 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
816 if (not exists $userflags->{acquisition}) {
817 return 0;
820 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
821 return 0;
824 # Budget restricted to owner
825 if ( $budget->{budget_permission} == 1 ) {
826 if ( $budget->{budget_owner_id}
827 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
829 return 0;
833 # Budget restricted to owner, users and library
834 elsif ( $budget->{budget_permission} == 2 ) {
835 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
837 if (
839 $budget->{budget_owner_id}
840 and $budget->{budget_owner_id} !=
841 $borrower->{borrowernumber}
842 or not $budget->{budget_owner_id}
844 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
845 @budget_users )
846 and defined $budget->{budget_branchcode}
847 and $budget->{budget_branchcode} ne
848 C4::Context->userenv->{branch}
851 return 0;
855 # Budget restricted to owner and users
856 elsif ( $budget->{budget_permission} == 3 ) {
857 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
858 if (
860 $budget->{budget_owner_id}
861 and $budget->{budget_owner_id} !=
862 $borrower->{borrowernumber}
863 or not $budget->{budget_owner_id}
865 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
866 @budget_users )
869 return 0;
874 return 1;
877 sub CanUserModifyBudget {
878 my ($borrower, $budget, $userflags) = @_;
880 if (not ref $borrower) {
881 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
883 if (not ref $budget) {
884 $budget = GetBudget($budget);
887 return 0 unless ($borrower and $budget);
889 if (not defined $userflags) {
890 $userflags = C4::Auth::getuserflags($borrower->{flags},
891 $borrower->{userid});
894 unless ($userflags->{superlibrarian}
895 || (ref $userflags->{acquisition}
896 && $userflags->{acquisition}->{budget_manage_all})
897 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
899 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
900 return 0;
903 if (ref $userflags->{acquisition}
904 && !$userflags->{acquisition}->{budget_modify}) {
905 return 0;
909 return 1;
912 sub _round {
913 my ($value, $increment) = @_;
915 if ($increment && $increment != 0) {
916 $value = int($value / $increment) * $increment;
919 return $value;
922 =head2 CloneBudgetPeriod
924 my $new_budget_period_id = CloneBudgetPeriod({
925 budget_period_id => $budget_period_id,
926 budget_period_startdate => $budget_period_startdate,
927 budget_period_enddate => $budget_period_enddate,
928 mark_original_budget_as_inactive => 1n
929 reset_all_budgets => 1,
932 Clone a budget period with all budgets.
933 If the mark_origin_budget_as_inactive is set (0 by default),
934 the original budget will be marked as inactive.
936 If the reset_all_budgets is set (0 by default), all budget (fund)
937 amounts will be reset.
939 =cut
941 sub CloneBudgetPeriod {
942 my ($params) = @_;
943 my $budget_period_id = $params->{budget_period_id};
944 my $budget_period_startdate = $params->{budget_period_startdate};
945 my $budget_period_enddate = $params->{budget_period_enddate};
946 my $budget_period_description = $params->{budget_period_description};
947 my $amount_change_percentage = $params->{amount_change_percentage};
948 my $amount_change_round_increment = $params->{amount_change_round_increment};
949 my $mark_original_budget_as_inactive =
950 $params->{mark_original_budget_as_inactive} || 0;
951 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
953 my $budget_period = GetBudgetPeriod($budget_period_id);
955 $budget_period->{budget_period_startdate} = $budget_period_startdate;
956 $budget_period->{budget_period_enddate} = $budget_period_enddate;
957 $budget_period->{budget_period_description} = $budget_period_description;
958 # The new budget (budget_period) should be active by default
959 $budget_period->{budget_period_active} = 1;
961 if ($amount_change_percentage) {
962 my $total = $budget_period->{budget_period_total};
963 $total += $total * $amount_change_percentage / 100;
964 $total = _round($total, $amount_change_round_increment);
965 $budget_period->{budget_period_total} = $total;
968 my $original_budget_period_id = $budget_period->{budget_period_id};
969 delete $budget_period->{budget_period_id};
970 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
972 my $budgets = GetBudgetHierarchy($budget_period_id);
973 CloneBudgetHierarchy(
975 budgets => $budgets,
976 new_budget_period_id => $new_budget_period_id
980 if ($mark_original_budget_as_inactive) {
981 ModBudgetPeriod(
983 budget_period_id => $budget_period_id,
984 budget_period_active => 0,
989 if ( $reset_all_budgets ) {
990 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
991 for my $budget ( @$budgets ) {
992 $budget->{budget_amount} = 0;
993 ModBudget( $budget );
995 } elsif ($amount_change_percentage) {
996 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
997 for my $budget ( @$budgets ) {
998 my $amount = $budget->{budget_amount};
999 $amount += $amount * $amount_change_percentage / 100;
1000 $amount = _round($amount, $amount_change_round_increment);
1001 $budget->{budget_amount} = $amount;
1002 ModBudget( $budget );
1006 return $new_budget_period_id;
1009 =head2 CloneBudgetHierarchy
1011 CloneBudgetHierarchy({
1012 budgets => $budgets,
1013 new_budget_period_id => $new_budget_period_id;
1016 Clone a budget hierarchy.
1018 =cut
1020 sub CloneBudgetHierarchy {
1021 my ($params) = @_;
1022 my $budgets = $params->{budgets};
1023 my $new_budget_period_id = $params->{new_budget_period_id};
1024 next unless @$budgets or $new_budget_period_id;
1026 my $children_of = $params->{children_of};
1027 my $new_parent_id = $params->{new_parent_id};
1029 my @first_level_budgets =
1030 ( not defined $children_of )
1031 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1032 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1034 # get only the columns of aqbudgets
1035 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1037 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1038 @first_level_budgets )
1041 my $tidy_budget =
1042 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1043 keys %$budget };
1044 my $new_budget_id = AddBudget(
1046 %$tidy_budget,
1047 budget_id => undef,
1048 budget_parent_id => $new_parent_id,
1049 budget_period_id => $new_budget_period_id
1052 CloneBudgetHierarchy(
1054 budgets => $budgets,
1055 new_budget_period_id => $new_budget_period_id,
1056 children_of => $budget->{budget_id},
1057 new_parent_id => $new_budget_id
1063 =head2 MoveOrders
1065 my $report = MoveOrders({
1066 from_budget_period_id => $from_budget_period_id,
1067 to_budget_period_id => $to_budget_period_id,
1070 Move orders from one budget period to another.
1072 =cut
1074 sub MoveOrders {
1075 my ($params) = @_;
1076 my $from_budget_period_id = $params->{from_budget_period_id};
1077 my $to_budget_period_id = $params->{to_budget_period_id};
1078 my $move_remaining_unspent = $params->{move_remaining_unspent};
1079 return
1080 if not $from_budget_period_id
1081 or not $to_budget_period_id
1082 or $from_budget_period_id == $to_budget_period_id;
1084 # Can't move orders to an inactive budget (budgetperiod)
1085 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1086 return unless $budget_period->{budget_period_active};
1088 my @report;
1089 my $dbh = C4::Context->dbh;
1090 my $sth_update_aqorders = $dbh->prepare(
1092 UPDATE aqorders
1093 SET budget_id = ?
1094 WHERE ordernumber = ?
1097 my $sth_update_budget_amount = $dbh->prepare(
1099 UPDATE aqbudgets
1100 SET budget_amount = ?
1101 WHERE budget_id = ?
1104 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1105 for my $from_budget (@$from_budgets) {
1106 my $new_budget_id = $dbh->selectcol_arrayref(
1108 SELECT budget_id
1109 FROM aqbudgets
1110 WHERE budget_period_id = ?
1111 AND budget_code = ?
1112 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1114 $new_budget_id = $new_budget_id->[0];
1115 my $new_budget = GetBudget( $new_budget_id );
1116 unless ( $new_budget ) {
1117 push @report,
1119 moved => 0,
1120 budget => $from_budget,
1121 error => 'budget_code_not_exists',
1123 next;
1125 my $orders_to_move = C4::Acquisition::SearchOrders(
1127 budget_id => $from_budget->{budget_id},
1128 pending => 1,
1132 my @orders_moved;
1133 for my $order (@$orders_to_move) {
1134 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1135 push @orders_moved, $order;
1138 my $unspent_moved = 0;
1139 if ($move_remaining_unspent) {
1140 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1141 my $unspent = $from_budget->{budget_amount} - $spent;
1142 my $new_budget_amount = $new_budget->{budget_amount};
1143 if ( $unspent > 0 ) {
1144 $new_budget_amount += $unspent;
1145 $unspent_moved = $unspent;
1147 $new_budget->{budget_amount} = $new_budget_amount;
1148 $sth_update_budget_amount->execute( $new_budget_amount,
1149 $new_budget->{budget_id} );
1152 push @report,
1154 budget => $new_budget,
1155 orders_moved => \@orders_moved,
1156 moved => 1,
1157 unspent_moved => $unspent_moved,
1160 return \@report;
1163 END { } # module clean-up code here (global destructor)
1166 __END__
1168 =head1 AUTHOR
1170 Koha Development Team <http://koha-community.org/>
1172 =cut