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
25 use Koha::InvoiceAdjustments;
27 use vars qw(@ISA @EXPORT);
35 &GetBudgetByOrderNumber
49 GetBudgetHierarchySpent
50 GetBudgetHierarchyOrdered
70 &CheckBudgetParentPerm
77 # ----------------------------BUDGETS.PM-----------------------------";
79 =head1 FUNCTIONS ABOUT BUDGETS
84 my ( $authcat, @hide_cols ) = @_;
85 my $dbh = C4::Context->dbh;
87 my $sth1 = $dbh->prepare(
89 UPDATE aqbudgets_planning SET display = 0
93 foreach my $authvalue (@hide_cols) {
94 # $sth1->{TraceLevel} = 3;
95 $sth1->execute( $authcat, $authvalue );
100 my ( $authcat, $authvalue ) = @_;
102 my $dbh = C4::Context->dbh;
103 my $sth = $dbh->prepare(
105 SELECT count(display) as cnt from aqbudgets_planning
107 AND authvalue = ? and display = 0 |
110 # $sth->{TraceLevel} = 3;
111 $sth->execute( $authcat, $authvalue );
112 my $res = $sth->fetchrow_hashref;
114 return $res->{cnt} > 0 ? 0: 1
118 sub CheckBudgetParentPerm {
119 my ( $budget, $borrower_id ) = @_;
120 my $depth = $budget->{depth};
121 my $parent_id = $budget->{budget_parent_id};
123 my $parent = GetBudget($parent_id);
124 $parent_id = $parent->{budget_parent_id};
125 if ( $parent->{budget_owner_id} == $borrower_id ) {
133 sub AddBudgetPeriod {
134 my ($budgetperiod) = @_;
135 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
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;
353 my $adjustments = Koha::InvoiceAdjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
354 while ( my $adj = $adjustments->next ){
355 $sum += $adj->adjustment;
361 # -------------------------------------------------------------------
362 sub GetBudgetOrdered {
363 my ($budget_id) = @_;
364 my $dbh = C4::Context->dbh;
365 my $sth = $dbh->prepare(qq|
366 SELECT SUM(ecost_tax_included * quantity) AS sum FROM aqorders
367 WHERE budget_id = ? AND
368 quantityreceived = 0 AND
369 datecancellationprinted IS NULL
371 $sth->execute($budget_id);
372 my $sum = $sth->fetchrow_array;
374 $sth = $dbh->prepare(qq|
375 SELECT SUM(shipmentcost) AS sum
377 WHERE shipmentcost_budgetid = ?
378 AND closedate IS NULL
380 $sth->execute($budget_id);
381 my ($shipmentcost_sum) = $sth->fetchrow_array;
382 $sum += $shipmentcost_sum;
384 my $adjustments = Koha::InvoiceAdjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
385 while ( my $adj = $adjustments->next ){
386 $sum += $adj->adjustment;
394 my $budget_name = &GetBudgetName($budget_id);
396 get the budget_name for a given budget_id
401 my ( $budget_id ) = @_;
402 my $dbh = C4::Context->dbh;
403 my $sth = $dbh->prepare(
410 $sth->execute($budget_id);
411 return $sth->fetchrow_array;
414 =head2 GetBudgetAuthCats
416 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
418 Return the list of authcat for a given budget_period_id
422 sub GetBudgetAuthCats {
423 my ($budget_period_id) = shift;
424 # now, populate the auth_cats_loop used in the budget planning button
425 # we must retrieve all auth values used by at least one budget
426 my $dbh = C4::Context->dbh;
427 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
428 $sth->execute($budget_period_id);
430 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
431 $authcats{$sort1_authcat}=1 if $sort1_authcat;
432 $authcats{$sort2_authcat}=1 if $sort2_authcat;
434 return [ sort keys %authcats ];
437 # -------------------------------------------------------------------
438 sub GetBudgetPeriods {
439 my ($filters,$orderby) = @_;
441 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
442 $rs = $rs->search( $filters, { order_by => $orderby } );
443 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
446 # -------------------------------------------------------------------
447 sub GetBudgetPeriod {
448 my ($budget_period_id) = @_;
449 my $dbh = C4::Context->dbh;
450 ## $total = number of records linked to the record that must be deleted
452 ## get information about the record that will be deleted
454 if ($budget_period_id) {
455 $sth = $dbh->prepare( qq|
458 WHERE budget_period_id=? |
460 $sth->execute($budget_period_id);
461 } else { # ACTIVE BUDGET
462 $sth = $dbh->prepare(qq|
465 WHERE budget_period_active=1 |
469 my $data = $sth->fetchrow_hashref;
474 my ($budget_period_id) = @_;
475 my $dbh = C4::Context->dbh;
476 ; ## $total = number of records linked to the record that must be deleted
479 ## get information about the record that will be deleted
480 my $sth = $dbh->prepare(qq|
483 WHERE budget_period_id=? |
485 return $sth->execute($budget_period_id);
488 # -------------------------------------------------------------------
489 sub ModBudgetPeriod {
490 my ($budget_period) = @_;
491 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
492 return unless($result);
494 $result = $result->update($budget_period);
495 return $result->in_storage;
498 # -------------------------------------------------------------------
499 sub GetBudgetHierarchy {
500 my ( $budget_period_id, $branchcode, $owner ) = @_;
502 my $dbh = C4::Context->dbh;
504 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
505 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
507 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
508 JOIN aqbudgetperiods USING (budget_period_id)|;
511 # show only period X if requested
512 if ($budget_period_id) {
513 push @where_strings," aqbudgets.budget_period_id = ?";
514 push @bind_params, $budget_period_id;
516 # show only budgets owned by me, my branch or everyone
520 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="")))};
521 push @bind_params, ( $owner, $branchcode );
523 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
524 push @bind_params, $owner;
528 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
529 push @bind_params, $branchcode;
532 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
533 $debug && warn $query,join(",",@bind_params);
534 my $sth = $dbh->prepare($query);
535 $sth->execute(@bind_params);
538 # create hash with budget_id has key
539 while ( my $data = $sth->fetchrow_hashref ) {
540 $links{ $data->{'budget_id'} } = $data;
543 # link child to parent
545 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
546 my $child = $links{$budget->{budget_id}};
547 if ( $child->{'budget_parent_id'} ) {
548 my $parent = $links{ $child->{'budget_parent_id'} };
550 unless ( $parent->{'children'} ) {
551 # init child arrayref
552 $parent->{'children'} = [];
555 push @{ $parent->{'children'} }, $child;
558 push @first_parents, $child;
563 foreach my $first_parent (@first_parents) {
564 _add_budget_children(\@sort, $first_parent, 0);
567 # Get all the budgets totals in as few queries as possible
568 my $hr_budget_spent = $dbh->selectall_hashref(q|
569 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
570 SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS budget_spent
571 FROM aqorders JOIN aqbudgets USING (budget_id)
572 WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
575 my $hr_budget_ordered = $dbh->selectall_hashref(q|
576 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
577 SUM(ecost_tax_included * quantity) AS budget_ordered
578 FROM aqorders JOIN aqbudgets USING (budget_id)
579 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
582 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
583 SELECT shipmentcost_budgetid as budget_id,
584 SUM(shipmentcost) as shipmentcost
586 WHERE closedate IS NOT NULL
587 GROUP BY shipmentcost_budgetid
589 my $hr_budget_ordered_shipment = $dbh->selectall_hashref(q|
590 SELECT shipmentcost_budgetid as budget_id,
591 SUM(shipmentcost) as shipmentcost
593 WHERE closedate IS NULL
594 GROUP BY shipmentcost_budgetid
598 foreach my $budget (@sort) {
599 if ( not defined $budget->{budget_parent_id} ) {
600 _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment );
607 my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment ) = @_;
609 foreach my $child (@{$budget->{children}}){
610 _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment );
613 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
614 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
615 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
616 $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
618 $budget->{total_spent} += $budget->{budget_spent};
619 $budget->{total_ordered} += $budget->{budget_ordered};
622 $parent->{total_spent} += $budget->{total_spent};
623 $parent->{total_ordered} += $budget->{total_ordered};
627 # Recursive method to add a budget and its chidren to an array
628 sub _add_budget_children {
631 $budget->{budget_level} = shift;
633 my $children = $budget->{'children'} || [];
634 return unless @$children; # break recursivity
635 foreach my $child (@$children) {
636 _add_budget_children($res, $child, $budget->{budget_level} + 1);
640 # -------------------------------------------------------------------
644 return unless ($budget);
646 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
647 return $resultset->create($budget)->id;
650 # -------------------------------------------------------------------
653 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
654 return unless($result);
656 $result = $result->update($budget);
657 return $result->in_storage;
660 # -------------------------------------------------------------------
662 my ($budget_id) = @_;
663 my $dbh = C4::Context->dbh;
664 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
665 my $rc = $sth->execute($budget_id);
670 # -------------------------------------------------------------------
674 &GetBudget($budget_id);
676 get a specific budget
681 my ( $budget_id ) = @_;
682 my $dbh = C4::Context->dbh;
688 my $sth = $dbh->prepare($query);
689 $sth->execute( $budget_id );
690 my $result = $sth->fetchrow_hashref;
694 # -------------------------------------------------------------------
696 =head2 GetBudgetByOrderNumber
698 &GetBudgetByOrderNumber($ordernumber);
700 get a specific budget by order number
704 sub GetBudgetByOrderNumber {
705 my ( $ordernumber ) = @_;
706 my $dbh = C4::Context->dbh;
709 FROM aqbudgets, aqorders
711 AND aqorders.budget_id = aqbudgets.budget_id
713 my $sth = $dbh->prepare($query);
714 $sth->execute( $ordernumber );
715 my $result = $sth->fetchrow_hashref;
719 =head2 GetBudgetReport
721 &GetBudgetReport( [$budget_id] );
723 Get all orders for a specific budget, without cancelled orders.
725 Returns an array of hashrefs.
729 # --------------------------------------------------------------------
730 sub GetBudgetReport {
731 my ( $budget_id ) = @_;
732 my $dbh = C4::Context->dbh;
734 SELECT o.*, b.budget_name
736 INNER JOIN aqorders o
737 ON b.budget_id = o.budget_id
739 AND (o.orderstatus != "cancelled")
740 ORDER BY b.budget_name';
742 my $sth = $dbh->prepare($query);
743 $sth->execute( $budget_id );
746 while ( my $data = $sth->fetchrow_hashref ) {
747 push( @results, $data );
752 =head2 GetBudgetsByActivity
754 &GetBudgetsByActivity( $budget_period_active );
756 Get all active or inactive budgets, depending of the value
764 # --------------------------------------------------------------------
765 sub GetBudgetsByActivity {
766 my ( $budget_period_active ) = @_;
767 my $dbh = C4::Context->dbh;
770 FROM aqbudgetperiods bp
771 INNER JOIN aqbudgets b
772 ON bp.budget_period_id = b.budget_period_id
773 WHERE bp.budget_period_active=?
775 my $sth = $dbh->prepare($query);
776 $sth->execute( $budget_period_active );
778 while ( my $data = $sth->fetchrow_hashref ) {
779 push( @results, $data );
783 # --------------------------------------------------------------------
785 =head2 GetBudgetsReport
787 &GetBudgetsReport( [$activity] );
789 Get all but cancelled orders for all funds.
791 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
796 Returns an array of hashrefs.
800 sub GetBudgetsReport {
802 my $dbh = C4::Context->dbh;
804 SELECT o.*, b.budget_name
805 FROM aqbudgetperiods bp
806 INNER JOIN aqbudgets b
807 ON bp.budget_period_id = b.budget_period_id
808 INNER JOIN aqorders o
809 ON b.budget_id = o.budget_id ';
811 $query .= 'WHERE bp.budget_period_active=? ';
813 $query .= 'AND (o.orderstatus != "cancelled")
814 ORDER BY b.budget_name';
816 my $sth = $dbh->prepare($query);
818 $sth->execute($activity);
824 while ( my $data = $sth->fetchrow_hashref ) {
825 push( @results, $data );
830 =head2 GetBudgetByCode
832 my $budget = &GetBudgetByCode($budget_code);
834 Retrieve all aqbudgets fields as a hashref for the budget that has
839 sub GetBudgetByCode {
840 my ( $budget_code ) = @_;
842 my $dbh = C4::Context->dbh;
846 JOIN aqbudgetperiods USING (budget_period_id)
847 WHERE budget_code = ?
848 ORDER BY budget_period_active DESC, budget_id DESC
851 my $sth = $dbh->prepare( $query );
852 $sth->execute( $budget_code );
853 return $sth->fetchrow_hashref;
856 =head2 GetBudgetHierarchySpent
858 my $spent = GetBudgetHierarchySpent( $budget_id );
860 Gets the total spent of the level and sublevels of $budget_id
864 sub GetBudgetHierarchySpent {
865 my ( $budget_id ) = @_;
866 my $dbh = C4::Context->dbh;
867 my $children_ids = $dbh->selectcol_arrayref(q|
870 WHERE budget_parent_id = ?
873 my $total_spent = GetBudgetSpent( $budget_id );
874 for my $child_id ( @$children_ids ) {
875 $total_spent += GetBudgetHierarchySpent( $child_id );
880 =head2 GetBudgetHierarchyOrdered
882 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
884 Gets the total ordered of the level and sublevels of $budget_id
888 sub GetBudgetHierarchyOrdered {
889 my ( $budget_id ) = @_;
890 my $dbh = C4::Context->dbh;
891 my $children_ids = $dbh->selectcol_arrayref(q|
894 WHERE budget_parent_id = ?
897 my $total_ordered = GetBudgetOrdered( $budget_id );
898 for my $child_id ( @$children_ids ) {
899 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
901 return $total_ordered;
906 &GetBudgets($filter, $order_by);
912 # -------------------------------------------------------------------
914 my ($filters, $orderby) = @_;
915 $orderby = 'budget_name' unless($orderby);
917 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
918 $rs = $rs->search( $filters, { order_by => $orderby } );
919 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
923 =head2 GetBudgetUsers
925 my @borrowernumbers = &GetBudgetUsers($budget_id);
927 Return the list of borrowernumbers linked to a budget
932 my ($budget_id) = @_;
934 my $dbh = C4::Context->dbh;
936 SELECT borrowernumber
937 FROM aqbudgetborrowers
940 my $sth = $dbh->prepare($query);
941 $sth->execute($budget_id);
944 while (my ($borrowernumber) = $sth->fetchrow_array) {
945 push @borrowernumbers, $borrowernumber
948 return @borrowernumbers;
951 =head2 ModBudgetUsers
953 &ModBudgetUsers($budget_id, @borrowernumbers);
955 Modify the list of borrowernumbers linked to a budget
960 my ($budget_id, @budget_users_id) = @_;
962 return unless $budget_id;
964 my $dbh = C4::Context->dbh;
965 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
966 my $sth = $dbh->prepare($query);
967 $sth->execute($budget_id);
970 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
973 $sth = $dbh->prepare($query);
974 foreach my $borrowernumber (@budget_users_id) {
975 next unless $borrowernumber;
976 $sth->execute($budget_id, $borrowernumber);
980 sub CanUserUseBudget {
981 my ($borrower, $budget, $userflags) = @_;
983 if (not ref $borrower) {
984 $borrower = Koha::Patrons->find( $borrower );
985 return 0 unless $borrower;
986 $borrower = $borrower->unblessed;
988 if (not ref $budget) {
989 $budget = GetBudget($budget);
992 return 0 unless ($borrower and $budget);
994 if (not defined $userflags) {
995 $userflags = C4::Auth::getuserflags($borrower->{flags},
996 $borrower->{userid});
999 unless ($userflags->{superlibrarian}
1000 || (ref $userflags->{acquisition}
1001 && $userflags->{acquisition}->{budget_manage_all})
1002 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1004 if (not exists $userflags->{acquisition}) {
1008 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
1012 # Budget restricted to owner
1013 if ( $budget->{budget_permission} == 1 ) {
1014 if ( $budget->{budget_owner_id}
1015 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1021 # Budget restricted to owner, users and library
1022 elsif ( $budget->{budget_permission} == 2 ) {
1023 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1027 $budget->{budget_owner_id}
1028 and $budget->{budget_owner_id} !=
1029 $borrower->{borrowernumber}
1030 or not $budget->{budget_owner_id}
1032 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1034 and defined $budget->{budget_branchcode}
1035 and $budget->{budget_branchcode} ne
1036 C4::Context->userenv->{branch}
1043 # Budget restricted to owner and users
1044 elsif ( $budget->{budget_permission} == 3 ) {
1045 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1048 $budget->{budget_owner_id}
1049 and $budget->{budget_owner_id} !=
1050 $borrower->{borrowernumber}
1051 or not $budget->{budget_owner_id}
1053 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1065 sub CanUserModifyBudget {
1066 my ($borrower, $budget, $userflags) = @_;
1068 if (not ref $borrower) {
1069 $borrower = Koha::Patrons->find( $borrower );
1070 return 0 unless $borrower;
1071 $borrower = $borrower->unblessed;
1073 if (not ref $budget) {
1074 $budget = GetBudget($budget);
1077 return 0 unless ($borrower and $budget);
1079 if (not defined $userflags) {
1080 $userflags = C4::Auth::getuserflags($borrower->{flags},
1081 $borrower->{userid});
1084 unless ($userflags->{superlibrarian}
1085 || (ref $userflags->{acquisition}
1086 && $userflags->{acquisition}->{budget_manage_all})
1087 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1089 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1093 if (ref $userflags->{acquisition}
1094 && !$userflags->{acquisition}->{budget_modify}) {
1103 my ($value, $increment) = @_;
1105 if ($increment && $increment != 0) {
1106 $value = int($value / $increment) * $increment;
1112 =head2 CloneBudgetPeriod
1114 my $new_budget_period_id = CloneBudgetPeriod({
1115 budget_period_id => $budget_period_id,
1116 budget_period_startdate => $budget_period_startdate,
1117 budget_period_enddate => $budget_period_enddate,
1118 mark_original_budget_as_inactive => 1n
1119 reset_all_budgets => 1,
1122 Clone a budget period with all budgets.
1123 If the mark_origin_budget_as_inactive is set (0 by default),
1124 the original budget will be marked as inactive.
1126 If the reset_all_budgets is set (0 by default), all budget (fund)
1127 amounts will be reset.
1131 sub CloneBudgetPeriod {
1133 my $budget_period_id = $params->{budget_period_id};
1134 my $budget_period_startdate = $params->{budget_period_startdate};
1135 my $budget_period_enddate = $params->{budget_period_enddate};
1136 my $budget_period_description = $params->{budget_period_description};
1137 my $amount_change_percentage = $params->{amount_change_percentage};
1138 my $amount_change_round_increment = $params->{amount_change_round_increment};
1139 my $mark_original_budget_as_inactive =
1140 $params->{mark_original_budget_as_inactive} || 0;
1141 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1143 my $budget_period = GetBudgetPeriod($budget_period_id);
1145 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1146 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1147 $budget_period->{budget_period_description} = $budget_period_description;
1148 # The new budget (budget_period) should be active by default
1149 $budget_period->{budget_period_active} = 1;
1151 if ($amount_change_percentage) {
1152 my $total = $budget_period->{budget_period_total};
1153 $total += $total * $amount_change_percentage / 100;
1154 $total = _round($total, $amount_change_round_increment);
1155 $budget_period->{budget_period_total} = $total;
1158 my $original_budget_period_id = $budget_period->{budget_period_id};
1159 delete $budget_period->{budget_period_id};
1160 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1162 my $budgets = GetBudgetHierarchy($budget_period_id);
1163 CloneBudgetHierarchy(
1165 budgets => $budgets,
1166 new_budget_period_id => $new_budget_period_id
1170 if ($mark_original_budget_as_inactive) {
1173 budget_period_id => $budget_period_id,
1174 budget_period_active => 0,
1179 if ( $reset_all_budgets ) {
1180 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1181 for my $budget ( @$budgets ) {
1182 $budget->{budget_amount} = 0;
1183 ModBudget( $budget );
1185 } elsif ($amount_change_percentage) {
1186 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1187 for my $budget ( @$budgets ) {
1188 my $amount = $budget->{budget_amount};
1189 $amount += $amount * $amount_change_percentage / 100;
1190 $amount = _round($amount, $amount_change_round_increment);
1191 $budget->{budget_amount} = $amount;
1192 ModBudget( $budget );
1196 return $new_budget_period_id;
1199 =head2 CloneBudgetHierarchy
1201 CloneBudgetHierarchy({
1202 budgets => $budgets,
1203 new_budget_period_id => $new_budget_period_id;
1206 Clone a budget hierarchy.
1210 sub CloneBudgetHierarchy {
1212 my $budgets = $params->{budgets};
1213 my $new_budget_period_id = $params->{new_budget_period_id};
1214 next unless @$budgets or $new_budget_period_id;
1216 my $children_of = $params->{children_of};
1217 my $new_parent_id = $params->{new_parent_id};
1219 my @first_level_budgets =
1220 ( not defined $children_of )
1221 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1222 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1224 # get only the columns of aqbudgets
1225 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1227 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1228 @first_level_budgets )
1232 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1234 my $new_budget_id = AddBudget(
1238 budget_parent_id => $new_parent_id,
1239 budget_period_id => $new_budget_period_id
1242 CloneBudgetHierarchy(
1244 budgets => $budgets,
1245 new_budget_period_id => $new_budget_period_id,
1246 children_of => $budget->{budget_id},
1247 new_parent_id => $new_budget_id
1255 my $report = MoveOrders({
1256 from_budget_period_id => $from_budget_period_id,
1257 to_budget_period_id => $to_budget_period_id,
1260 Move orders from one budget period to another.
1266 my $from_budget_period_id = $params->{from_budget_period_id};
1267 my $to_budget_period_id = $params->{to_budget_period_id};
1268 my $move_remaining_unspent = $params->{move_remaining_unspent};
1270 if not $from_budget_period_id
1271 or not $to_budget_period_id
1272 or $from_budget_period_id == $to_budget_period_id;
1274 # Can't move orders to an inactive budget (budgetperiod)
1275 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1276 return unless $budget_period->{budget_period_active};
1279 my $dbh = C4::Context->dbh;
1280 my $sth_update_aqorders = $dbh->prepare(
1284 WHERE ordernumber = ?
1287 my $sth_update_budget_amount = $dbh->prepare(
1290 SET budget_amount = ?
1294 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1295 for my $from_budget (@$from_budgets) {
1296 my $new_budget_id = $dbh->selectcol_arrayref(
1300 WHERE budget_period_id = ?
1302 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1304 $new_budget_id = $new_budget_id->[0];
1305 my $new_budget = GetBudget( $new_budget_id );
1306 unless ( $new_budget ) {
1310 budget => $from_budget,
1311 error => 'budget_code_not_exists',
1315 my $orders_to_move = C4::Acquisition::SearchOrders(
1317 budget_id => $from_budget->{budget_id},
1323 for my $order (@$orders_to_move) {
1324 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1325 push @orders_moved, $order;
1328 my $unspent_moved = 0;
1329 if ($move_remaining_unspent) {
1330 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1331 my $unspent = $from_budget->{budget_amount} - $spent;
1332 my $new_budget_amount = $new_budget->{budget_amount};
1333 if ( $unspent > 0 ) {
1334 $new_budget_amount += $unspent;
1335 $unspent_moved = $unspent;
1337 $new_budget->{budget_amount} = $new_budget_amount;
1338 $sth_update_budget_amount->execute( $new_budget_amount,
1339 $new_budget->{budget_id} );
1344 budget => $new_budget,
1345 orders_moved => \@orders_moved,
1347 unspent_moved => $unspent_moved,
1353 END { } # module clean-up code here (global destructor)
1360 Koha Development Team <http://koha-community.org/>