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>.
24 use Koha::Acquisition::Invoice::Adjustments;
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 ) = @_; #FIXME we don't use $period
212 my $dbh = C4::Context->dbh;
213 my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|);
214 if ( $cell->{'authcat'} eq 'MONTHS' ) {
215 # get the actual amount
216 # FIXME we should consider quantity
217 $sth = $dbh->prepare( qq|
219 SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders
220 WHERE budget_id = ? AND
221 entrydate like "$cell->{'authvalue'}%" |
223 $sth->execute( $cell->{'budget_id'} );
224 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
225 # get the actual amount
226 # FIXME we should consider quantity
227 $sth = $dbh->prepare( qq|
229 SELECT SUM(| . $roundsql . qq|) FROM aqorders
230 LEFT JOIN aqorders_items
231 ON (aqorders.ordernumber = aqorders_items.ordernumber)
233 ON (aqorders_items.itemnumber = items.itemnumber)
234 WHERE budget_id = ? AND homebranch = ? | );
236 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
237 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
238 # get the actual amount
239 $sth = $dbh->prepare( qq|
241 SELECT SUM( | . $roundsql . qq| * quantity) AS actual
242 FROM aqorders JOIN biblioitems
243 ON (biblioitems.biblionumber = aqorders.biblionumber )
244 WHERE aqorders.budget_id = ? and itemtype = ? |
246 $sth->execute( $cell->{'budget_id'},
247 $cell->{'authvalue'} );
249 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
251 # get the actual amount
252 $sth = $dbh->prepare( qq|
254 SELECT SUM(| . $roundsql . qq| * quantity) AS actual
256 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
257 WHERE aqorders.budget_id = ? AND
258 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
259 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
261 $sth->execute( $cell->{'budget_id'},
262 $budget->{'sort1_authcat'},
263 $cell->{'authvalue'},
264 $budget->{'sort2_authcat'},
268 $actual = $sth->fetchrow_array;
270 # get the estimated amount
271 $sth = $dbh->prepare( qq|
273 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
274 WHERE budget_period_id = ? AND
279 $sth->execute( $cell->{'budget_period_id'},
280 $cell->{'budget_id'},
281 $cell->{'authvalue'},
286 my $res = $sth->fetchrow_hashref;
287 # my $display = $res->{'display'};
288 my $estimated = $res->{'estimated'};
291 return $actual, $estimated;
294 # -------------------------------------------------------------------
296 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
297 my $dbh = C4::Context->dbh;
298 foreach my $buds (@$budget_plan) {
299 my $lines = $buds->{lines};
300 my $sth = $dbh->prepare( qq|
301 DELETE FROM aqbudgets_planning
302 WHERE budget_period_id = ? AND
306 #delete a aqplan line of cells, then insert new cells,
307 # these could be UPDATES rather than DEL/INSERTS...
308 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
310 foreach my $cell (@$lines) {
311 my $sth = $dbh->prepare( qq|
313 INSERT INTO aqbudgets_planning
315 budget_period_id = ?,
317 estimated_amount = ?,
321 $cell->{'budget_id'},
322 $cell->{'budget_period_id'},
324 $cell->{'estimated_amount'},
325 $cell->{'authvalue'},
331 # -------------------------------------------------------------------
333 my ($budget_id) = @_;
334 my $dbh = C4::Context->dbh;
335 # unitprice_tax_included should always been set here
336 # we should not need to retrieve ecost_tax_included
337 my $sth = $dbh->prepare(qq|
338 SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE(unitprice_tax_included, ecost_tax_included)") . qq| * quantity ) AS sum FROM aqorders
339 WHERE budget_id = ? AND
340 quantityreceived > 0 AND
341 datecancellationprinted IS NULL
343 $sth->execute($budget_id);
344 my $sum = ( $sth->fetchrow_array || 0 ) + 0;
346 $sth = $dbh->prepare(qq|
347 SELECT SUM(shipmentcost) AS sum
349 WHERE shipmentcost_budgetid = ?
352 $sth->execute($budget_id);
353 my ($shipmentcost_sum) = $sth->fetchrow_array;
354 $sum += ( $shipmentcost_sum || 0 ) + 0;
356 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
357 while ( my $adj = $adjustments->next ){
358 $sum += $adj->adjustment;
364 # -------------------------------------------------------------------
365 sub GetBudgetOrdered {
366 my ($budget_id) = @_;
367 my $dbh = C4::Context->dbh;
368 my $sth = $dbh->prepare(qq|
369 SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . qq| * quantity) AS sum FROM aqorders
370 WHERE budget_id = ? AND
371 quantityreceived = 0 AND
372 datecancellationprinted IS NULL
374 $sth->execute($budget_id);
375 my $sum = ( $sth->fetchrow_array || 0 ) + 0;
377 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
378 while ( my $adj = $adjustments->next ){
379 $sum += $adj->adjustment;
387 my $budget_name = &GetBudgetName($budget_id);
389 get the budget_name for a given budget_id
394 my ( $budget_id ) = @_;
395 my $dbh = C4::Context->dbh;
396 my $sth = $dbh->prepare(
403 $sth->execute($budget_id);
404 return $sth->fetchrow_array;
407 =head2 GetBudgetAuthCats
409 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
411 Return the list of authcat for a given budget_period_id
415 sub GetBudgetAuthCats {
416 my ($budget_period_id) = shift;
417 # now, populate the auth_cats_loop used in the budget planning button
418 # we must retrieve all auth values used by at least one budget
419 my $dbh = C4::Context->dbh;
420 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
421 $sth->execute($budget_period_id);
423 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
424 $authcats{$sort1_authcat}=1 if $sort1_authcat;
425 $authcats{$sort2_authcat}=1 if $sort2_authcat;
427 return [ sort keys %authcats ];
430 # -------------------------------------------------------------------
431 sub GetBudgetPeriods {
432 my ($filters,$orderby) = @_;
434 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
435 $rs = $rs->search( $filters, { order_by => $orderby } );
436 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
439 # -------------------------------------------------------------------
440 sub GetBudgetPeriod {
441 my ($budget_period_id) = @_;
442 my $dbh = C4::Context->dbh;
443 my $sth = $dbh->prepare( qq|
446 WHERE budget_period_id=? |
448 $sth->execute($budget_period_id);
449 return $sth->fetchrow_hashref;
453 my ($budget_period_id) = @_;
454 my $dbh = C4::Context->dbh;
455 ; ## $total = number of records linked to the record that must be deleted
458 ## get information about the record that will be deleted
459 my $sth = $dbh->prepare(qq|
462 WHERE budget_period_id=? |
464 return $sth->execute($budget_period_id);
467 # -------------------------------------------------------------------
468 sub ModBudgetPeriod {
469 my ($budget_period) = @_;
470 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
471 return unless($result);
473 $result = $result->update($budget_period);
474 return $result->in_storage;
477 # -------------------------------------------------------------------
478 sub GetBudgetHierarchy {
479 my ( $budget_period_id, $branchcode, $owner ) = @_;
481 my $dbh = C4::Context->dbh;
483 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
484 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
486 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
487 JOIN aqbudgetperiods USING (budget_period_id)|;
490 # show only period X if requested
491 if ($budget_period_id) {
492 push @where_strings," aqbudgets.budget_period_id = ?";
493 push @bind_params, $budget_period_id;
495 # show only budgets owned by me, my branch or everyone
499 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="")))};
500 push @bind_params, ( $owner, $branchcode );
502 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
503 push @bind_params, $owner;
507 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
508 push @bind_params, $branchcode;
511 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
512 my $sth = $dbh->prepare($query);
513 $sth->execute(@bind_params);
516 # create hash with budget_id has key
517 while ( my $data = $sth->fetchrow_hashref ) {
518 $links{ $data->{'budget_id'} } = $data;
521 # link child to parent
523 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
524 my $child = $links{$budget->{budget_id}};
525 if ( $child->{'budget_parent_id'} ) {
526 my $parent = $links{ $child->{'budget_parent_id'} };
528 unless ( $parent->{'children'} ) {
529 # init child arrayref
530 $parent->{'children'} = [];
533 push @{ $parent->{'children'} }, $child;
536 push @first_parents, $child;
541 foreach my $first_parent (@first_parents) {
542 _add_budget_children(\@sort, $first_parent, 0);
545 # Get all the budgets totals in as few queries as possible
546 my $hr_budget_spent = $dbh->selectall_hashref(q|
547 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
548 SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE(unitprice_tax_included, ecost_tax_included)|) . q| * quantity ) AS budget_spent
549 FROM aqorders JOIN aqbudgets USING (budget_id)
550 WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
551 GROUP BY budget_id, budget_parent_id
553 my $hr_budget_ordered = $dbh->selectall_hashref(q|
554 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
555 SUM( | . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . q| * quantity) AS budget_ordered
556 FROM aqorders JOIN aqbudgets USING (budget_id)
557 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
558 GROUP BY budget_id, budget_parent_id
560 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
561 SELECT shipmentcost_budgetid as budget_id,
562 SUM(shipmentcost) as shipmentcost
564 GROUP BY shipmentcost_budgetid
566 my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q|
568 SUM(adjustment) as adjustments
569 FROM aqinvoice_adjustments
570 JOIN aqinvoices USING (invoiceid)
571 WHERE closedate IS NOT NULL
574 my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q|
576 SUM(adjustment) as adjustments
577 FROM aqinvoice_adjustments
578 JOIN aqinvoices USING (invoiceid)
579 WHERE closedate IS NULL AND encumber_open = 1
584 foreach my $budget (@sort) {
585 if ( not defined $budget->{budget_parent_id} ) {
586 _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
593 my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ) = @_;
595 foreach my $child (@{$budget->{children}}){
596 _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
599 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent} || 0;
600 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost} || 0;
601 $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments} || 0;
602 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered} || 0;
603 $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments} || 0;
605 $budget->{total_spent} += $budget->{budget_spent};
606 $budget->{total_ordered} += $budget->{budget_ordered};
609 $parent->{total_spent} += $budget->{total_spent};
610 $parent->{total_ordered} += $budget->{total_ordered};
614 # Recursive method to add a budget and its chidren to an array
615 sub _add_budget_children {
618 $budget->{budget_level} = shift;
620 my $children = $budget->{'children'} || [];
621 return unless @$children; # break recursivity
622 foreach my $child (@$children) {
623 _add_budget_children($res, $child, $budget->{budget_level} + 1);
627 # -------------------------------------------------------------------
628 # FIXME Must be replaced by Koha::Acquisition::Fund->store
631 return unless ($budget);
633 undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq '';
634 undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq '';
635 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
636 return $resultset->create($budget)->id;
639 # -------------------------------------------------------------------
640 # FIXME Must be replaced by Koha::Acquisition::Fund->store
643 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
644 return unless($result);
646 undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq '';
647 undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq '';
648 $result = $result->update($budget);
649 return $result->in_storage;
652 # -------------------------------------------------------------------
653 # FIXME Must be replaced by Koha::Acquisition::Fund->delete
655 my ($budget_id) = @_;
656 my $dbh = C4::Context->dbh;
657 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
658 my $rc = $sth->execute($budget_id);
663 # -------------------------------------------------------------------
667 &GetBudget($budget_id);
669 get a specific budget
674 my ( $budget_id ) = @_;
675 my $dbh = C4::Context->dbh;
681 my $sth = $dbh->prepare($query);
682 $sth->execute( $budget_id );
683 my $result = $sth->fetchrow_hashref;
687 # -------------------------------------------------------------------
689 =head2 GetBudgetByOrderNumber
691 &GetBudgetByOrderNumber($ordernumber);
693 get a specific budget by order number
697 sub GetBudgetByOrderNumber {
698 my ( $ordernumber ) = @_;
699 my $dbh = C4::Context->dbh;
702 FROM aqbudgets, aqorders
704 AND aqorders.budget_id = aqbudgets.budget_id
706 my $sth = $dbh->prepare($query);
707 $sth->execute( $ordernumber );
708 my $result = $sth->fetchrow_hashref;
712 =head2 GetBudgetReport
714 &GetBudgetReport( [$budget_id] );
716 Get all orders for a specific budget, without cancelled orders.
718 Returns an array of hashrefs.
722 # --------------------------------------------------------------------
723 sub GetBudgetReport {
724 my ( $budget_id ) = @_;
725 my $dbh = C4::Context->dbh;
727 SELECT o.*, b.budget_name
729 INNER JOIN aqorders o
730 ON b.budget_id = o.budget_id
732 AND (o.orderstatus != "cancelled")
733 ORDER BY b.budget_name';
735 my $sth = $dbh->prepare($query);
736 $sth->execute( $budget_id );
739 while ( my $data = $sth->fetchrow_hashref ) {
740 push( @results, $data );
745 =head2 GetBudgetsByActivity
747 &GetBudgetsByActivity( $budget_period_active );
749 Get all active or inactive budgets, depending of the value
757 # --------------------------------------------------------------------
758 sub GetBudgetsByActivity {
759 my ( $budget_period_active ) = @_;
760 my $dbh = C4::Context->dbh;
763 FROM aqbudgetperiods bp
764 INNER JOIN aqbudgets b
765 ON bp.budget_period_id = b.budget_period_id
766 WHERE bp.budget_period_active=?
768 my $sth = $dbh->prepare($query);
769 $sth->execute( $budget_period_active );
771 while ( my $data = $sth->fetchrow_hashref ) {
772 push( @results, $data );
776 # --------------------------------------------------------------------
778 =head2 GetBudgetsReport
780 &GetBudgetsReport( [$activity] );
782 Get all but cancelled orders for all funds.
784 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
789 Returns an array of hashrefs.
793 sub GetBudgetsReport {
795 my $dbh = C4::Context->dbh;
797 SELECT o.*, b.budget_name
798 FROM aqbudgetperiods bp
799 INNER JOIN aqbudgets b
800 ON bp.budget_period_id = b.budget_period_id
801 INNER JOIN aqorders o
802 ON b.budget_id = o.budget_id ';
803 if ( $activity && $activity ne '' ) {
804 $query .= 'WHERE bp.budget_period_active=? ';
806 $query .= 'AND (o.orderstatus != "cancelled")
807 ORDER BY b.budget_name';
809 my $sth = $dbh->prepare($query);
810 if ( $activity && $activity ne '' ) {
811 $sth->execute($activity);
817 while ( my $data = $sth->fetchrow_hashref ) {
818 push( @results, $data );
823 =head2 GetBudgetByCode
825 my $budget = &GetBudgetByCode($budget_code);
827 Retrieve all aqbudgets fields as a hashref for the budget that has
832 sub GetBudgetByCode {
833 my ( $budget_code ) = @_;
835 my $dbh = C4::Context->dbh;
839 JOIN aqbudgetperiods USING (budget_period_id)
840 WHERE budget_code = ?
841 ORDER BY budget_period_active DESC, budget_id DESC
844 my $sth = $dbh->prepare( $query );
845 $sth->execute( $budget_code );
846 return $sth->fetchrow_hashref;
849 =head2 GetBudgetHierarchySpent
851 my $spent = GetBudgetHierarchySpent( $budget_id );
853 Gets the total spent of the level and sublevels of $budget_id
857 sub GetBudgetHierarchySpent {
858 my ( $budget_id ) = @_;
859 my $dbh = C4::Context->dbh;
860 my $children_ids = $dbh->selectcol_arrayref(q|
863 WHERE budget_parent_id = ?
866 my $total_spent = GetBudgetSpent( $budget_id );
867 for my $child_id ( @$children_ids ) {
868 $total_spent += GetBudgetHierarchySpent( $child_id );
873 =head2 GetBudgetHierarchyOrdered
875 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
877 Gets the total ordered of the level and sublevels of $budget_id
881 sub GetBudgetHierarchyOrdered {
882 my ( $budget_id ) = @_;
883 my $dbh = C4::Context->dbh;
884 my $children_ids = $dbh->selectcol_arrayref(q|
887 WHERE budget_parent_id = ?
890 my $total_ordered = GetBudgetOrdered( $budget_id );
891 for my $child_id ( @$children_ids ) {
892 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
894 return $total_ordered;
899 &GetBudgets($filter, $order_by);
905 # -------------------------------------------------------------------
907 my ($filters, $orderby) = @_;
908 $orderby = 'budget_name' unless($orderby);
910 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
911 $rs = $rs->search( $filters, { order_by => $orderby } );
912 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
916 =head2 GetBudgetUsers
918 my @borrowernumbers = &GetBudgetUsers($budget_id);
920 Return the list of borrowernumbers linked to a budget
925 my ($budget_id) = @_;
927 my $dbh = C4::Context->dbh;
929 SELECT borrowernumber
930 FROM aqbudgetborrowers
933 my $sth = $dbh->prepare($query);
934 $sth->execute($budget_id);
937 while (my ($borrowernumber) = $sth->fetchrow_array) {
938 push @borrowernumbers, $borrowernumber
941 return @borrowernumbers;
944 =head2 ModBudgetUsers
946 &ModBudgetUsers($budget_id, @borrowernumbers);
948 Modify the list of borrowernumbers linked to a budget
953 my ($budget_id, @budget_users_id) = @_;
955 return unless $budget_id;
957 my $dbh = C4::Context->dbh;
958 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
959 my $sth = $dbh->prepare($query);
960 $sth->execute($budget_id);
963 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
966 $sth = $dbh->prepare($query);
967 foreach my $borrowernumber (@budget_users_id) {
968 next unless $borrowernumber;
969 $sth->execute($budget_id, $borrowernumber);
973 sub CanUserUseBudget {
974 my ($borrower, $budget, $userflags) = @_;
976 if (not ref $borrower) {
977 $borrower = Koha::Patrons->find( $borrower );
978 return 0 unless $borrower;
979 $borrower = $borrower->unblessed;
981 if (not ref $budget) {
982 $budget = GetBudget($budget);
985 return 0 unless ($borrower and $budget);
987 if (not defined $userflags) {
988 $userflags = C4::Auth::getuserflags($borrower->{flags},
989 $borrower->{userid});
992 unless ($userflags->{superlibrarian}
993 || (ref $userflags->{acquisition}
994 && $userflags->{acquisition}->{budget_manage_all})
995 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
997 if (not exists $userflags->{acquisition}) {
1001 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
1005 # Budget restricted to owner
1006 if ( $budget->{budget_permission} == 1 ) {
1007 if ( $budget->{budget_owner_id}
1008 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1014 # Budget restricted to owner, users and library
1015 elsif ( $budget->{budget_permission} == 2 ) {
1016 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1020 $budget->{budget_owner_id}
1021 and $budget->{budget_owner_id} !=
1022 $borrower->{borrowernumber}
1023 or not $budget->{budget_owner_id}
1025 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1027 and defined $budget->{budget_branchcode}
1028 and $budget->{budget_branchcode} ne
1029 C4::Context->userenv->{branch}
1036 # Budget restricted to owner and users
1037 elsif ( $budget->{budget_permission} == 3 ) {
1038 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1041 $budget->{budget_owner_id}
1042 and $budget->{budget_owner_id} !=
1043 $borrower->{borrowernumber}
1044 or not $budget->{budget_owner_id}
1046 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1058 sub CanUserModifyBudget {
1059 my ($borrower, $budget, $userflags) = @_;
1061 if (not ref $borrower) {
1062 $borrower = Koha::Patrons->find( $borrower );
1063 return 0 unless $borrower;
1064 $borrower = $borrower->unblessed;
1066 if (not ref $budget) {
1067 $budget = GetBudget($budget);
1070 return 0 unless ($borrower and $budget);
1072 if (not defined $userflags) {
1073 $userflags = C4::Auth::getuserflags($borrower->{flags},
1074 $borrower->{userid});
1077 unless ($userflags->{superlibrarian}
1078 || (ref $userflags->{acquisition}
1079 && $userflags->{acquisition}->{budget_manage_all})
1080 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1082 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1086 if (ref $userflags->{acquisition}
1087 && !$userflags->{acquisition}->{budget_modify}) {
1096 my ($value, $increment) = @_;
1098 if ($increment && $increment != 0) {
1099 $value = int($value / $increment) * $increment;
1105 =head2 CloneBudgetPeriod
1107 my $new_budget_period_id = CloneBudgetPeriod({
1108 budget_period_id => $budget_period_id,
1109 budget_period_startdate => $budget_period_startdate,
1110 budget_period_enddate => $budget_period_enddate,
1111 mark_original_budget_as_inactive => 1n
1112 reset_all_budgets => 1,
1115 Clone a budget period with all budgets.
1116 If the mark_origin_budget_as_inactive is set (0 by default),
1117 the original budget will be marked as inactive.
1119 If the reset_all_budgets is set (0 by default), all budget (fund)
1120 amounts will be reset.
1124 sub CloneBudgetPeriod {
1126 my $budget_period_id = $params->{budget_period_id};
1127 my $budget_period_startdate = $params->{budget_period_startdate};
1128 my $budget_period_enddate = $params->{budget_period_enddate};
1129 my $budget_period_description = $params->{budget_period_description};
1130 my $amount_change_percentage = $params->{amount_change_percentage};
1131 my $amount_change_round_increment = $params->{amount_change_round_increment};
1132 my $mark_original_budget_as_inactive =
1133 $params->{mark_original_budget_as_inactive} || 0;
1134 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1136 my $budget_period = GetBudgetPeriod($budget_period_id);
1138 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1139 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1140 $budget_period->{budget_period_description} = $budget_period_description;
1141 # The new budget (budget_period) should be active by default
1142 $budget_period->{budget_period_active} = 1;
1144 if ($amount_change_percentage) {
1145 my $total = $budget_period->{budget_period_total};
1146 $total += $total * $amount_change_percentage / 100;
1147 $total = _round($total, $amount_change_round_increment);
1148 $budget_period->{budget_period_total} = $total;
1151 my $original_budget_period_id = $budget_period->{budget_period_id};
1152 delete $budget_period->{budget_period_id};
1153 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1155 my $budgets = GetBudgetHierarchy($budget_period_id);
1156 CloneBudgetHierarchy(
1158 budgets => $budgets,
1159 new_budget_period_id => $new_budget_period_id
1163 if ($mark_original_budget_as_inactive) {
1166 budget_period_id => $budget_period_id,
1167 budget_period_active => 0,
1172 if ( $reset_all_budgets ) {
1173 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1174 for my $budget ( @$budgets ) {
1175 $budget->{budget_amount} = 0;
1176 ModBudget( $budget );
1178 } elsif ($amount_change_percentage) {
1179 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1180 for my $budget ( @$budgets ) {
1181 my $amount = $budget->{budget_amount};
1182 $amount += $amount * $amount_change_percentage / 100;
1183 $amount = _round($amount, $amount_change_round_increment);
1184 $budget->{budget_amount} = $amount;
1185 ModBudget( $budget );
1189 return $new_budget_period_id;
1192 =head2 CloneBudgetHierarchy
1194 CloneBudgetHierarchy({
1195 budgets => $budgets,
1196 new_budget_period_id => $new_budget_period_id;
1199 Clone a budget hierarchy.
1203 sub CloneBudgetHierarchy {
1205 my $budgets = $params->{budgets};
1206 my $new_budget_period_id = $params->{new_budget_period_id};
1207 next unless @$budgets or $new_budget_period_id;
1209 my $children_of = $params->{children_of};
1210 my $new_parent_id = $params->{new_parent_id};
1212 my @first_level_budgets =
1213 ( not defined $children_of )
1214 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1215 : map { ( defined $_->{budget_parent_id} && $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1217 # get only the columns of aqbudgets
1218 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1220 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1221 @first_level_budgets )
1225 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1227 delete $tidy_budget->{timestamp};
1228 my $new_budget_id = AddBudget(
1232 budget_parent_id => $new_parent_id,
1233 budget_period_id => $new_budget_period_id
1236 CloneBudgetHierarchy(
1238 budgets => $budgets,
1239 new_budget_period_id => $new_budget_period_id,
1240 children_of => $budget->{budget_id},
1241 new_parent_id => $new_budget_id
1249 my $report = MoveOrders({
1250 from_budget_period_id => $from_budget_period_id,
1251 to_budget_period_id => $to_budget_period_id,
1254 Move orders from one budget period to another.
1260 my $from_budget_period_id = $params->{from_budget_period_id};
1261 my $to_budget_period_id = $params->{to_budget_period_id};
1262 my $move_remaining_unspent = $params->{move_remaining_unspent};
1264 if not $from_budget_period_id
1265 or not $to_budget_period_id
1266 or $from_budget_period_id == $to_budget_period_id;
1268 # Can't move orders to an inactive budget (budgetperiod)
1269 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1270 return unless $budget_period->{budget_period_active};
1273 my $dbh = C4::Context->dbh;
1274 my $sth_update_aqorders = $dbh->prepare(
1278 WHERE ordernumber = ?
1281 my $sth_update_budget_amount = $dbh->prepare(
1284 SET budget_amount = ?
1288 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1289 for my $from_budget (@$from_budgets) {
1290 my $new_budget_id = $dbh->selectcol_arrayref(
1294 WHERE budget_period_id = ?
1296 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1298 $new_budget_id = $new_budget_id->[0];
1299 my $new_budget = GetBudget( $new_budget_id );
1300 unless ( $new_budget ) {
1304 budget => $from_budget,
1305 error => 'budget_code_not_exists',
1309 my $orders_to_move = C4::Acquisition::SearchOrders(
1311 budget_id => $from_budget->{budget_id},
1317 for my $order (@$orders_to_move) {
1318 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1319 push @orders_moved, $order;
1322 my $unspent_moved = 0;
1323 if ($move_remaining_unspent) {
1324 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1325 my $unspent = $from_budget->{budget_amount} - $spent;
1326 my $new_budget_amount = $new_budget->{budget_amount};
1327 if ( $unspent > 0 ) {
1328 $new_budget_amount += $unspent;
1329 $unspent_moved = $unspent;
1331 $new_budget->{budget_amount} = $new_budget_amount;
1332 $sth_update_budget_amount->execute( $new_budget_amount,
1333 $new_budget->{budget_id} );
1338 budget => $new_budget,
1339 orders_moved => \@orders_moved,
1341 unspent_moved => $unspent_moved,
1347 END { } # module clean-up code here (global destructor)
1354 Koha Development Team <http://koha-community.org/>