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>.
21 #use warnings; FIXME - Bug 2505
26 use vars qw(@ISA @EXPORT);
34 &GetBudgetByOrderNumber
48 GetBudgetHierarchySpent
49 GetBudgetHierarchyOrdered
69 &CheckBudgetParentPerm
76 # ----------------------------BUDGETS.PM-----------------------------";
78 =head1 FUNCTIONS ABOUT BUDGETS
83 my ( $authcat, @hide_cols ) = @_;
84 my $dbh = C4::Context->dbh;
86 my $sth1 = $dbh->prepare(
88 UPDATE aqbudgets_planning SET display = 0
92 foreach my $authvalue (@hide_cols) {
93 # $sth1->{TraceLevel} = 3;
94 $sth1->execute( $authcat, $authvalue );
99 my ( $authcat, $authvalue ) = @_;
101 my $dbh = C4::Context->dbh;
102 my $sth = $dbh->prepare(
104 SELECT count(display) as cnt from aqbudgets_planning
106 AND authvalue = ? and display = 0 |
109 # $sth->{TraceLevel} = 3;
110 $sth->execute( $authcat, $authvalue );
111 my $res = $sth->fetchrow_hashref;
113 return $res->{cnt} > 0 ? 0: 1
117 sub CheckBudgetParentPerm {
118 my ( $budget, $borrower_id ) = @_;
119 my $depth = $budget->{depth};
120 my $parent_id = $budget->{budget_parent_id};
122 my $parent = GetBudget($parent_id);
123 $parent_id = $parent->{budget_parent_id};
124 if ( $parent->{budget_owner_id} == $borrower_id ) {
132 sub AddBudgetPeriod {
133 my ($budgetperiod) = @_;
134 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
136 undef $budgetperiod->{budget_period_id};
137 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
138 return $resultset->create($budgetperiod)->id;
140 # -------------------------------------------------------------------
141 sub GetPeriodsCount {
142 my $dbh = C4::Context->dbh;
143 my $sth = $dbh->prepare("
144 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
146 my $res = $sth->fetchrow_hashref;
147 return $res->{'sum'};
150 # -------------------------------------------------------------------
151 sub CheckBudgetParent {
152 my ( $new_parent, $budget ) = @_;
153 my $new_parent_id = $new_parent->{'budget_id'};
154 my $budget_id = $budget->{'budget_id'};
155 my $dbh = C4::Context->dbh;
156 my $parent_id_tmp = $new_parent_id;
158 # check new-parent is not a child (or a child's child ;)
159 my $sth = $dbh->prepare(qq|
160 SELECT budget_parent_id FROM
161 aqbudgets where budget_id = ? | );
163 $sth->execute($parent_id_tmp);
164 my $res = $sth->fetchrow_hashref;
165 if ( $res->{'budget_parent_id'} == $budget_id ) {
168 if ( not defined $res->{'budget_parent_id'} ) {
171 $parent_id_tmp = $res->{'budget_parent_id'};
175 # -------------------------------------------------------------------
176 sub BudgetHasChildren {
177 my ( $budget_id ) = @_;
178 my $dbh = C4::Context->dbh;
179 my $sth = $dbh->prepare(qq|
180 SELECT count(*) as sum FROM aqbudgets
181 WHERE budget_parent_id = ? | );
182 $sth->execute( $budget_id );
183 my $sum = $sth->fetchrow_hashref;
184 return $sum->{'sum'};
187 sub GetBudgetChildren {
188 my ( $budget_id ) = @_;
189 my $dbh = C4::Context->dbh;
190 return $dbh->selectall_arrayref(q|
191 SELECT * FROM aqbudgets
192 WHERE budget_parent_id = ?
193 |, { Slice => {} }, $budget_id );
196 sub SetOwnerToFundHierarchy {
197 my ( $budget_id, $borrowernumber ) = @_;
199 my $budget = GetBudget( $budget_id );
200 $budget->{budget_owner_id} = $borrowernumber;
201 ModBudget( $budget );
202 my $children = GetBudgetChildren( $budget_id );
203 for my $child ( @$children ) {
204 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
208 # -------------------------------------------------------------------
209 sub GetBudgetsPlanCell {
210 my ( $cell, $period, $budget ) = @_;
212 my $dbh = C4::Context->dbh;
213 if ( $cell->{'authcat'} eq 'MONTHS' ) {
214 # get the actual amount
215 $sth = $dbh->prepare( qq|
217 SELECT SUM(ecost_tax_included) AS actual FROM aqorders
218 WHERE budget_id = ? AND
219 entrydate like "$cell->{'authvalue'}%" |
221 $sth->execute( $cell->{'budget_id'} );
222 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
223 # get the actual amount
224 $sth = $dbh->prepare( qq|
226 SELECT SUM(ecost_tax_included) FROM aqorders
227 LEFT JOIN aqorders_items
228 ON (aqorders.ordernumber = aqorders_items.ordernumber)
230 ON (aqorders_items.itemnumber = items.itemnumber)
231 WHERE budget_id = ? AND homebranch = ? | );
233 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
234 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
235 # get the actual amount
236 $sth = $dbh->prepare( qq|
238 SELECT SUM( ecost_tax_included * quantity) AS actual
239 FROM aqorders JOIN biblioitems
240 ON (biblioitems.biblionumber = aqorders.biblionumber )
241 WHERE aqorders.budget_id = ? and itemtype = ? |
243 $sth->execute( $cell->{'budget_id'},
244 $cell->{'authvalue'} );
246 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
248 # get the actual amount
249 $sth = $dbh->prepare( qq|
251 SELECT SUM(ecost_tax_included * quantity) AS actual
253 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
254 WHERE aqorders.budget_id = ? AND
255 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
256 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
258 $sth->execute( $cell->{'budget_id'},
259 $budget->{'sort1_authcat'},
260 $cell->{'authvalue'},
261 $budget->{'sort2_authcat'},
265 $actual = $sth->fetchrow_array;
267 # get the estimated amount
268 $sth = $dbh->prepare( qq|
270 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
271 WHERE budget_period_id = ? AND
276 $sth->execute( $cell->{'budget_period_id'},
277 $cell->{'budget_id'},
278 $cell->{'authvalue'},
283 my $res = $sth->fetchrow_hashref;
284 # my $display = $res->{'display'};
285 my $estimated = $res->{'estimated'};
288 return $actual, $estimated;
291 # -------------------------------------------------------------------
293 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
294 my $dbh = C4::Context->dbh;
295 foreach my $buds (@$budget_plan) {
296 my $lines = $buds->{lines};
297 my $sth = $dbh->prepare( qq|
298 DELETE FROM aqbudgets_planning
299 WHERE budget_period_id = ? AND
303 #delete a aqplan line of cells, then insert new cells,
304 # these could be UPDATES rather than DEL/INSERTS...
305 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
307 foreach my $cell (@$lines) {
308 my $sth = $dbh->prepare( qq|
310 INSERT INTO aqbudgets_planning
312 budget_period_id = ?,
314 estimated_amount = ?,
318 $cell->{'budget_id'},
319 $cell->{'budget_period_id'},
321 $cell->{'estimated_amount'},
322 $cell->{'authvalue'},
328 # -------------------------------------------------------------------
330 my ($budget_id) = @_;
331 my $dbh = C4::Context->dbh;
332 # unitprice_tax_included should always been set here
333 # we should not need to retrieve ecost_tax_included
334 my $sth = $dbh->prepare(qq|
335 SELECT SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS sum FROM aqorders
336 WHERE budget_id = ? AND
337 quantityreceived > 0 AND
338 datecancellationprinted IS NULL
340 $sth->execute($budget_id);
341 my $sum = $sth->fetchrow_array;
343 $sth = $dbh->prepare(qq|
344 SELECT SUM(shipmentcost) AS sum
346 WHERE shipmentcost_budgetid = ?
349 $sth->execute($budget_id);
350 my ($shipmentcost_sum) = $sth->fetchrow_array;
351 $sum += $shipmentcost_sum;
356 # -------------------------------------------------------------------
357 sub GetBudgetOrdered {
358 my ($budget_id) = @_;
359 my $dbh = C4::Context->dbh;
360 my $sth = $dbh->prepare(qq|
361 SELECT SUM(ecost_tax_included * quantity) AS sum FROM aqorders
362 WHERE budget_id = ? AND
363 quantityreceived = 0 AND
364 datecancellationprinted IS NULL
366 $sth->execute($budget_id);
367 my $sum = $sth->fetchrow_array;
374 my $budget_name = &GetBudgetName($budget_id);
376 get the budget_name for a given budget_id
381 my ( $budget_id ) = @_;
382 my $dbh = C4::Context->dbh;
383 my $sth = $dbh->prepare(
390 $sth->execute($budget_id);
391 return $sth->fetchrow_array;
394 =head2 GetBudgetAuthCats
396 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
398 Return the list of authcat for a given budget_period_id
402 sub GetBudgetAuthCats {
403 my ($budget_period_id) = shift;
404 # now, populate the auth_cats_loop used in the budget planning button
405 # we must retrieve all auth values used by at least one budget
406 my $dbh = C4::Context->dbh;
407 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
408 $sth->execute($budget_period_id);
410 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
411 $authcats{$sort1_authcat}=1 if $sort1_authcat;
412 $authcats{$sort2_authcat}=1 if $sort2_authcat;
414 return [ sort keys %authcats ];
417 # -------------------------------------------------------------------
418 sub GetBudgetPeriods {
419 my ($filters,$orderby) = @_;
421 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
422 $rs = $rs->search( $filters, { order_by => $orderby } );
423 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
426 # -------------------------------------------------------------------
427 sub GetBudgetPeriod {
428 my ($budget_period_id) = @_;
429 my $dbh = C4::Context->dbh;
430 ## $total = number of records linked to the record that must be deleted
432 ## get information about the record that will be deleted
434 if ($budget_period_id) {
435 $sth = $dbh->prepare( qq|
438 WHERE budget_period_id=? |
440 $sth->execute($budget_period_id);
441 } else { # ACTIVE BUDGET
442 $sth = $dbh->prepare(qq|
445 WHERE budget_period_active=1 |
449 my $data = $sth->fetchrow_hashref;
454 my ($budget_period_id) = @_;
455 my $dbh = C4::Context->dbh;
456 ; ## $total = number of records linked to the record that must be deleted
459 ## get information about the record that will be deleted
460 my $sth = $dbh->prepare(qq|
463 WHERE budget_period_id=? |
465 return $sth->execute($budget_period_id);
468 # -------------------------------------------------------------------
469 sub ModBudgetPeriod {
470 my ($budget_period) = @_;
471 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
472 return unless($result);
474 $result = $result->update($budget_period);
475 return $result->in_storage;
478 # -------------------------------------------------------------------
479 sub GetBudgetHierarchy {
480 my ( $budget_period_id, $branchcode, $owner ) = @_;
482 my $dbh = C4::Context->dbh;
484 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
485 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
487 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
488 JOIN aqbudgetperiods USING (budget_period_id)|;
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
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 );
503 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
504 push @bind_params, $owner;
508 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
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);
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
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'} };
530 unless ( $parent->{'children'} ) {
531 # init child arrayref
532 $parent->{'children'} = [];
535 push @{ $parent->{'children'} }, $child;
538 push @first_parents, $child;
543 foreach my $first_parent (@first_parents) {
544 _add_budget_children(\@sort, $first_parent, 0);
547 # Get all the budgets totals in as few queries as possible
548 my $hr_budget_spent = $dbh->selectall_hashref(q|
549 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
550 SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS budget_spent
551 FROM aqorders JOIN aqbudgets USING (budget_id)
552 WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
553 GROUP BY budget_id, budget_parent_id
555 my $hr_budget_ordered = $dbh->selectall_hashref(q|
556 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
557 SUM(ecost_tax_included * quantity) AS budget_ordered
558 FROM aqorders JOIN aqbudgets USING (budget_id)
559 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
560 GROUP BY budget_id, budget_parent_id
562 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
563 SELECT shipmentcost_budgetid as budget_id,
564 SUM(shipmentcost) as shipmentcost
566 WHERE closedate IS NOT NULL
567 GROUP BY shipmentcost_budgetid
569 my $hr_budget_ordered_shipment = $dbh->selectall_hashref(q|
570 SELECT shipmentcost_budgetid as budget_id,
571 SUM(shipmentcost) as shipmentcost
573 WHERE closedate IS NULL
574 GROUP BY shipmentcost_budgetid
578 foreach my $budget (@sort) {
579 if ( not defined $budget->{budget_parent_id} ) {
580 _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment );
587 my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment ) = @_;
589 foreach my $child (@{$budget->{children}}){
590 _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment );
593 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
594 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
595 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
596 $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
598 $budget->{total_spent} += $budget->{budget_spent};
599 $budget->{total_ordered} += $budget->{budget_ordered};
602 $parent->{total_spent} += $budget->{total_spent};
603 $parent->{total_ordered} += $budget->{total_ordered};
607 # Recursive method to add a budget and its chidren to an array
608 sub _add_budget_children {
611 $budget->{budget_level} = shift;
613 my $children = $budget->{'children'} || [];
614 return unless @$children; # break recursivity
615 foreach my $child (@$children) {
616 _add_budget_children($res, $child, $budget->{budget_level} + 1);
620 # -------------------------------------------------------------------
624 return unless ($budget);
626 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
627 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
628 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
629 return $resultset->create($budget)->id;
632 # -------------------------------------------------------------------
635 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
636 return unless($result);
638 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
639 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
640 $result = $result->update($budget);
641 return $result->in_storage;
644 # -------------------------------------------------------------------
646 my ($budget_id) = @_;
647 my $dbh = C4::Context->dbh;
648 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
649 my $rc = $sth->execute($budget_id);
654 # -------------------------------------------------------------------
658 &GetBudget($budget_id);
660 get a specific budget
665 my ( $budget_id ) = @_;
666 my $dbh = C4::Context->dbh;
672 my $sth = $dbh->prepare($query);
673 $sth->execute( $budget_id );
674 my $result = $sth->fetchrow_hashref;
678 # -------------------------------------------------------------------
680 =head2 GetBudgetByOrderNumber
682 &GetBudgetByOrderNumber($ordernumber);
684 get a specific budget by order number
688 sub GetBudgetByOrderNumber {
689 my ( $ordernumber ) = @_;
690 my $dbh = C4::Context->dbh;
693 FROM aqbudgets, aqorders
695 AND aqorders.budget_id = aqbudgets.budget_id
697 my $sth = $dbh->prepare($query);
698 $sth->execute( $ordernumber );
699 my $result = $sth->fetchrow_hashref;
703 =head2 GetBudgetReport
705 &GetBudgetReport( [$budget_id] );
707 Get all orders for a specific budget, without cancelled orders.
709 Returns an array of hashrefs.
713 # --------------------------------------------------------------------
714 sub GetBudgetReport {
715 my ( $budget_id ) = @_;
716 my $dbh = C4::Context->dbh;
718 SELECT o.*, b.budget_name
720 INNER JOIN aqorders o
721 ON b.budget_id = o.budget_id
723 AND (o.orderstatus != "cancelled")
724 ORDER BY b.budget_name';
726 my $sth = $dbh->prepare($query);
727 $sth->execute( $budget_id );
730 while ( my $data = $sth->fetchrow_hashref ) {
731 push( @results, $data );
736 =head2 GetBudgetsByActivity
738 &GetBudgetsByActivity( $budget_period_active );
740 Get all active or inactive budgets, depending of the value
748 # --------------------------------------------------------------------
749 sub GetBudgetsByActivity {
750 my ( $budget_period_active ) = @_;
751 my $dbh = C4::Context->dbh;
754 FROM aqbudgetperiods bp
755 INNER JOIN aqbudgets b
756 ON bp.budget_period_id = b.budget_period_id
757 WHERE bp.budget_period_active=?
759 my $sth = $dbh->prepare($query);
760 $sth->execute( $budget_period_active );
762 while ( my $data = $sth->fetchrow_hashref ) {
763 push( @results, $data );
767 # --------------------------------------------------------------------
769 =head2 GetBudgetsReport
771 &GetBudgetsReport( [$activity] );
773 Get all but cancelled orders for all funds.
775 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
780 Returns an array of hashrefs.
784 sub GetBudgetsReport {
786 my $dbh = C4::Context->dbh;
788 SELECT o.*, b.budget_name
789 FROM aqbudgetperiods bp
790 INNER JOIN aqbudgets b
791 ON bp.budget_period_id = b.budget_period_id
792 INNER JOIN aqorders o
793 ON b.budget_id = o.budget_id ';
795 $query .= 'WHERE bp.budget_period_active=? ';
797 $query .= 'AND (o.orderstatus != "cancelled")
798 ORDER BY b.budget_name';
800 my $sth = $dbh->prepare($query);
802 $sth->execute($activity);
808 while ( my $data = $sth->fetchrow_hashref ) {
809 push( @results, $data );
814 =head2 GetBudgetByCode
816 my $budget = &GetBudgetByCode($budget_code);
818 Retrieve all aqbudgets fields as a hashref for the budget that has
823 sub GetBudgetByCode {
824 my ( $budget_code ) = @_;
826 my $dbh = C4::Context->dbh;
830 JOIN aqbudgetperiods USING (budget_period_id)
831 WHERE budget_code = ?
832 ORDER BY budget_period_active DESC, budget_id DESC
835 my $sth = $dbh->prepare( $query );
836 $sth->execute( $budget_code );
837 return $sth->fetchrow_hashref;
840 =head2 GetBudgetHierarchySpent
842 my $spent = GetBudgetHierarchySpent( $budget_id );
844 Gets the total spent of the level and sublevels of $budget_id
848 sub GetBudgetHierarchySpent {
849 my ( $budget_id ) = @_;
850 my $dbh = C4::Context->dbh;
851 my $children_ids = $dbh->selectcol_arrayref(q|
854 WHERE budget_parent_id = ?
857 my $total_spent = GetBudgetSpent( $budget_id );
858 for my $child_id ( @$children_ids ) {
859 $total_spent += GetBudgetHierarchySpent( $child_id );
864 =head2 GetBudgetHierarchyOrdered
866 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
868 Gets the total ordered of the level and sublevels of $budget_id
872 sub GetBudgetHierarchyOrdered {
873 my ( $budget_id ) = @_;
874 my $dbh = C4::Context->dbh;
875 my $children_ids = $dbh->selectcol_arrayref(q|
878 WHERE budget_parent_id = ?
881 my $total_ordered = GetBudgetOrdered( $budget_id );
882 for my $child_id ( @$children_ids ) {
883 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
885 return $total_ordered;
890 &GetBudgets($filter, $order_by);
896 # -------------------------------------------------------------------
898 my ($filters, $orderby) = @_;
899 $orderby = 'budget_name' unless($orderby);
901 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
902 $rs = $rs->search( $filters, { order_by => $orderby } );
903 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
907 =head2 GetBudgetUsers
909 my @borrowernumbers = &GetBudgetUsers($budget_id);
911 Return the list of borrowernumbers linked to a budget
916 my ($budget_id) = @_;
918 my $dbh = C4::Context->dbh;
920 SELECT borrowernumber
921 FROM aqbudgetborrowers
924 my $sth = $dbh->prepare($query);
925 $sth->execute($budget_id);
928 while (my ($borrowernumber) = $sth->fetchrow_array) {
929 push @borrowernumbers, $borrowernumber
932 return @borrowernumbers;
935 =head2 ModBudgetUsers
937 &ModBudgetUsers($budget_id, @borrowernumbers);
939 Modify the list of borrowernumbers linked to a budget
944 my ($budget_id, @budget_users_id) = @_;
946 return unless $budget_id;
948 my $dbh = C4::Context->dbh;
949 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
950 my $sth = $dbh->prepare($query);
951 $sth->execute($budget_id);
954 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
957 $sth = $dbh->prepare($query);
958 foreach my $borrowernumber (@budget_users_id) {
959 next unless $borrowernumber;
960 $sth->execute($budget_id, $borrowernumber);
964 sub CanUserUseBudget {
965 my ($borrower, $budget, $userflags) = @_;
967 if (not ref $borrower) {
968 $borrower = Koha::Patrons->find( $borrower );
969 return 0 unless $borrower;
970 $borrower = $borrower->unblessed;
972 if (not ref $budget) {
973 $budget = GetBudget($budget);
976 return 0 unless ($borrower and $budget);
978 if (not defined $userflags) {
979 $userflags = C4::Auth::getuserflags($borrower->{flags},
980 $borrower->{userid});
983 unless ($userflags->{superlibrarian}
984 || (ref $userflags->{acquisition}
985 && $userflags->{acquisition}->{budget_manage_all})
986 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
988 if (not exists $userflags->{acquisition}) {
992 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
996 # Budget restricted to owner
997 if ( $budget->{budget_permission} == 1 ) {
998 if ( $budget->{budget_owner_id}
999 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1005 # Budget restricted to owner, users and library
1006 elsif ( $budget->{budget_permission} == 2 ) {
1007 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1011 $budget->{budget_owner_id}
1012 and $budget->{budget_owner_id} !=
1013 $borrower->{borrowernumber}
1014 or not $budget->{budget_owner_id}
1016 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1018 and defined $budget->{budget_branchcode}
1019 and $budget->{budget_branchcode} ne
1020 C4::Context->userenv->{branch}
1027 # Budget restricted to owner and users
1028 elsif ( $budget->{budget_permission} == 3 ) {
1029 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1032 $budget->{budget_owner_id}
1033 and $budget->{budget_owner_id} !=
1034 $borrower->{borrowernumber}
1035 or not $budget->{budget_owner_id}
1037 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1049 sub CanUserModifyBudget {
1050 my ($borrower, $budget, $userflags) = @_;
1052 if (not ref $borrower) {
1053 $borrower = Koha::Patrons->find( $borrower );
1054 return 0 unless $borrower;
1055 $borrower = $borrower->unblessed;
1057 if (not ref $budget) {
1058 $budget = GetBudget($budget);
1061 return 0 unless ($borrower and $budget);
1063 if (not defined $userflags) {
1064 $userflags = C4::Auth::getuserflags($borrower->{flags},
1065 $borrower->{userid});
1068 unless ($userflags->{superlibrarian}
1069 || (ref $userflags->{acquisition}
1070 && $userflags->{acquisition}->{budget_manage_all})
1071 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1073 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1077 if (ref $userflags->{acquisition}
1078 && !$userflags->{acquisition}->{budget_modify}) {
1087 my ($value, $increment) = @_;
1089 if ($increment && $increment != 0) {
1090 $value = int($value / $increment) * $increment;
1096 =head2 CloneBudgetPeriod
1098 my $new_budget_period_id = CloneBudgetPeriod({
1099 budget_period_id => $budget_period_id,
1100 budget_period_startdate => $budget_period_startdate,
1101 budget_period_enddate => $budget_period_enddate,
1102 mark_original_budget_as_inactive => 1n
1103 reset_all_budgets => 1,
1106 Clone a budget period with all budgets.
1107 If the mark_origin_budget_as_inactive is set (0 by default),
1108 the original budget will be marked as inactive.
1110 If the reset_all_budgets is set (0 by default), all budget (fund)
1111 amounts will be reset.
1115 sub CloneBudgetPeriod {
1117 my $budget_period_id = $params->{budget_period_id};
1118 my $budget_period_startdate = $params->{budget_period_startdate};
1119 my $budget_period_enddate = $params->{budget_period_enddate};
1120 my $budget_period_description = $params->{budget_period_description};
1121 my $amount_change_percentage = $params->{amount_change_percentage};
1122 my $amount_change_round_increment = $params->{amount_change_round_increment};
1123 my $mark_original_budget_as_inactive =
1124 $params->{mark_original_budget_as_inactive} || 0;
1125 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1127 my $budget_period = GetBudgetPeriod($budget_period_id);
1129 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1130 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1131 $budget_period->{budget_period_description} = $budget_period_description;
1132 # The new budget (budget_period) should be active by default
1133 $budget_period->{budget_period_active} = 1;
1135 if ($amount_change_percentage) {
1136 my $total = $budget_period->{budget_period_total};
1137 $total += $total * $amount_change_percentage / 100;
1138 $total = _round($total, $amount_change_round_increment);
1139 $budget_period->{budget_period_total} = $total;
1142 my $original_budget_period_id = $budget_period->{budget_period_id};
1143 delete $budget_period->{budget_period_id};
1144 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1146 my $budgets = GetBudgetHierarchy($budget_period_id);
1147 CloneBudgetHierarchy(
1149 budgets => $budgets,
1150 new_budget_period_id => $new_budget_period_id
1154 if ($mark_original_budget_as_inactive) {
1157 budget_period_id => $budget_period_id,
1158 budget_period_active => 0,
1163 if ( $reset_all_budgets ) {
1164 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1165 for my $budget ( @$budgets ) {
1166 $budget->{budget_amount} = 0;
1167 ModBudget( $budget );
1169 } elsif ($amount_change_percentage) {
1170 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1171 for my $budget ( @$budgets ) {
1172 my $amount = $budget->{budget_amount};
1173 $amount += $amount * $amount_change_percentage / 100;
1174 $amount = _round($amount, $amount_change_round_increment);
1175 $budget->{budget_amount} = $amount;
1176 ModBudget( $budget );
1180 return $new_budget_period_id;
1183 =head2 CloneBudgetHierarchy
1185 CloneBudgetHierarchy({
1186 budgets => $budgets,
1187 new_budget_period_id => $new_budget_period_id;
1190 Clone a budget hierarchy.
1194 sub CloneBudgetHierarchy {
1196 my $budgets = $params->{budgets};
1197 my $new_budget_period_id = $params->{new_budget_period_id};
1198 next unless @$budgets or $new_budget_period_id;
1200 my $children_of = $params->{children_of};
1201 my $new_parent_id = $params->{new_parent_id};
1203 my @first_level_budgets =
1204 ( not defined $children_of )
1205 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1206 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1208 # get only the columns of aqbudgets
1209 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1211 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1212 @first_level_budgets )
1216 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1218 delete $tidy_budget->{timestamp};
1219 my $new_budget_id = AddBudget(
1223 budget_parent_id => $new_parent_id,
1224 budget_period_id => $new_budget_period_id
1227 CloneBudgetHierarchy(
1229 budgets => $budgets,
1230 new_budget_period_id => $new_budget_period_id,
1231 children_of => $budget->{budget_id},
1232 new_parent_id => $new_budget_id
1240 my $report = MoveOrders({
1241 from_budget_period_id => $from_budget_period_id,
1242 to_budget_period_id => $to_budget_period_id,
1245 Move orders from one budget period to another.
1251 my $from_budget_period_id = $params->{from_budget_period_id};
1252 my $to_budget_period_id = $params->{to_budget_period_id};
1253 my $move_remaining_unspent = $params->{move_remaining_unspent};
1255 if not $from_budget_period_id
1256 or not $to_budget_period_id
1257 or $from_budget_period_id == $to_budget_period_id;
1259 # Can't move orders to an inactive budget (budgetperiod)
1260 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1261 return unless $budget_period->{budget_period_active};
1264 my $dbh = C4::Context->dbh;
1265 my $sth_update_aqorders = $dbh->prepare(
1269 WHERE ordernumber = ?
1272 my $sth_update_budget_amount = $dbh->prepare(
1275 SET budget_amount = ?
1279 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1280 for my $from_budget (@$from_budgets) {
1281 my $new_budget_id = $dbh->selectcol_arrayref(
1285 WHERE budget_period_id = ?
1287 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1289 $new_budget_id = $new_budget_id->[0];
1290 my $new_budget = GetBudget( $new_budget_id );
1291 unless ( $new_budget ) {
1295 budget => $from_budget,
1296 error => 'budget_code_not_exists',
1300 my $orders_to_move = C4::Acquisition::SearchOrders(
1302 budget_id => $from_budget->{budget_id},
1308 for my $order (@$orders_to_move) {
1309 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1310 push @orders_moved, $order;
1313 my $unspent_moved = 0;
1314 if ($move_remaining_unspent) {
1315 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1316 my $unspent = $from_budget->{budget_amount} - $spent;
1317 my $new_budget_amount = $new_budget->{budget_amount};
1318 if ( $unspent > 0 ) {
1319 $new_budget_amount += $unspent;
1320 $unspent_moved = $unspent;
1322 $new_budget->{budget_amount} = $new_budget_amount;
1323 $sth_update_budget_amount->execute( $new_budget_amount,
1324 $new_budget->{budget_id} );
1329 budget => $new_budget,
1330 orders_moved => \@orders_moved,
1332 unspent_moved => $unspent_moved,
1338 END { } # module clean-up code here (global destructor)
1345 Koha Development Team <http://koha-community.org/>