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>.
25 use Koha::Acquisition::Invoice::Adjustments;
27 use C4::Log qw(logaction);
29 our (@ISA, @EXPORT_OK);
36 GetBudgetByOrderNumber
51 GetBudgetHierarchySpent
52 GetBudgetHierarchyOrdered
72 SetOwnerToFundHierarchy
85 # ----------------------------BUDGETS.PM-----------------------------";
87 =head1 FUNCTIONS ABOUT BUDGETS
92 my ( $authcat, @hide_cols ) = @_;
93 my $dbh = C4::Context->dbh;
95 my $sth1 = $dbh->prepare(
97 UPDATE aqbudgets_planning SET display = 0
101 foreach my $authvalue (@hide_cols) {
102 # $sth1->{TraceLevel} = 3;
103 $sth1->execute( $authcat, $authvalue );
108 my ( $authcat, $authvalue ) = @_;
110 my $dbh = C4::Context->dbh;
111 my $sth = $dbh->prepare(
113 SELECT count(display) as cnt from aqbudgets_planning
115 AND authvalue = ? and display = 0 |
118 # $sth->{TraceLevel} = 3;
119 $sth->execute( $authcat, $authvalue );
120 my $res = $sth->fetchrow_hashref;
122 return $res->{cnt} > 0 ? 0: 1
126 sub CheckBudgetParentPerm {
127 my ( $budget, $borrower_id ) = @_;
128 my $depth = $budget->{depth};
129 my $parent_id = $budget->{budget_parent_id};
131 my $parent = GetBudget($parent_id);
132 $parent_id = $parent->{budget_parent_id};
133 if ( $parent->{budget_owner_id} == $borrower_id ) {
141 sub AddBudgetPeriod {
142 my ($budgetperiod) = @_;
143 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
145 undef $budgetperiod->{budget_period_id};
146 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
147 return $resultset->create($budgetperiod)->id;
149 # -------------------------------------------------------------------
150 sub GetPeriodsCount {
151 my $dbh = C4::Context->dbh;
152 my $sth = $dbh->prepare("
153 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
155 my $res = $sth->fetchrow_hashref;
156 return $res->{'sum'};
159 # -------------------------------------------------------------------
160 sub CheckBudgetParent {
161 my ( $new_parent, $budget ) = @_;
162 my $new_parent_id = $new_parent->{'budget_id'};
163 my $budget_id = $budget->{'budget_id'};
164 my $dbh = C4::Context->dbh;
165 my $parent_id_tmp = $new_parent_id;
167 # check new-parent is not a child (or a child's child ;)
168 my $sth = $dbh->prepare(qq|
169 SELECT budget_parent_id FROM
170 aqbudgets where budget_id = ? | );
172 $sth->execute($parent_id_tmp);
173 my $res = $sth->fetchrow_hashref;
174 if ( $res->{'budget_parent_id'} == $budget_id ) {
177 if ( not defined $res->{'budget_parent_id'} ) {
180 $parent_id_tmp = $res->{'budget_parent_id'};
184 # -------------------------------------------------------------------
185 sub BudgetHasChildren {
186 my ( $budget_id ) = @_;
187 my $dbh = C4::Context->dbh;
188 my $sth = $dbh->prepare(qq|
189 SELECT count(*) as sum FROM aqbudgets
190 WHERE budget_parent_id = ? | );
191 $sth->execute( $budget_id );
192 my $sum = $sth->fetchrow_hashref;
193 return $sum->{'sum'};
196 sub GetBudgetChildren {
197 my ( $budget_id ) = @_;
198 my $dbh = C4::Context->dbh;
199 return $dbh->selectall_arrayref(q|
200 SELECT * FROM aqbudgets
201 WHERE budget_parent_id = ?
202 |, { Slice => {} }, $budget_id );
205 sub SetOwnerToFundHierarchy {
206 my ( $budget_id, $borrowernumber ) = @_;
208 my $budget = GetBudget( $budget_id );
209 $budget->{budget_owner_id} = $borrowernumber;
210 ModBudget( $budget );
211 my $children = GetBudgetChildren( $budget_id );
212 for my $child ( @$children ) {
213 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
217 # -------------------------------------------------------------------
218 sub GetBudgetsPlanCell {
219 my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period
221 my $dbh = C4::Context->dbh;
222 my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|);
223 if ( $cell->{'authcat'} eq 'MONTHS' ) {
224 # get the actual amount
225 # FIXME we should consider quantity
226 $sth = $dbh->prepare( qq|
228 SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders
229 WHERE budget_id = ? AND
230 entrydate like "$cell->{'authvalue'}%" |
232 $sth->execute( $cell->{'budget_id'} );
233 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
234 # get the actual amount
235 # FIXME we should consider quantity
236 $sth = $dbh->prepare( qq|
238 SELECT SUM(| . $roundsql . qq|) FROM aqorders
239 LEFT JOIN aqorders_items
240 ON (aqorders.ordernumber = aqorders_items.ordernumber)
242 ON (aqorders_items.itemnumber = items.itemnumber)
243 WHERE budget_id = ? AND homebranch = ? | );
245 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
246 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
247 # get the actual amount
248 $sth = $dbh->prepare( qq|
250 SELECT SUM( | . $roundsql . qq| * quantity) AS actual
251 FROM aqorders JOIN biblioitems
252 ON (biblioitems.biblionumber = aqorders.biblionumber )
253 WHERE aqorders.budget_id = ? and itemtype = ? |
255 $sth->execute( $cell->{'budget_id'},
256 $cell->{'authvalue'} );
258 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
260 # get the actual amount
261 $sth = $dbh->prepare( qq|
263 SELECT SUM(| . $roundsql . qq| * quantity) AS actual
265 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
266 WHERE aqorders.budget_id = ? AND
267 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
268 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
270 $sth->execute( $cell->{'budget_id'},
271 $budget->{'sort1_authcat'},
272 $cell->{'authvalue'},
273 $budget->{'sort2_authcat'},
277 $actual = $sth->fetchrow_array;
279 # get the estimated amount
280 $sth = $dbh->prepare( qq|
282 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
283 WHERE budget_period_id = ? AND
288 $sth->execute( $cell->{'budget_period_id'},
289 $cell->{'budget_id'},
290 $cell->{'authvalue'},
295 my $res = $sth->fetchrow_hashref;
296 # my $display = $res->{'display'};
297 my $estimated = $res->{'estimated'};
300 return $actual, $estimated;
303 # -------------------------------------------------------------------
305 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
306 my $dbh = C4::Context->dbh;
307 foreach my $buds (@$budget_plan) {
308 my $lines = $buds->{lines};
309 my $sth = $dbh->prepare( qq|
310 DELETE FROM aqbudgets_planning
311 WHERE budget_period_id = ? AND
315 #delete a aqplan line of cells, then insert new cells,
316 # these could be UPDATES rather than DEL/INSERTS...
317 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
319 foreach my $cell (@$lines) {
320 my $sth = $dbh->prepare( qq|
322 INSERT INTO aqbudgets_planning
324 budget_period_id = ?,
326 estimated_amount = ?,
330 $cell->{'budget_id'},
331 $cell->{'budget_period_id'},
333 $cell->{'estimated_amount'},
334 $cell->{'authvalue'},
340 # -------------------------------------------------------------------
342 my ($budget_id) = @_;
343 my $dbh = C4::Context->dbh;
344 # unitprice_tax_included should always been set here
345 # we should not need to retrieve ecost_tax_included
346 my $sth = $dbh->prepare(qq|
347 SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE(unitprice_tax_included, ecost_tax_included)") . qq| * quantity ) AS sum FROM aqorders
348 WHERE budget_id = ? AND
349 quantityreceived > 0 AND
350 datecancellationprinted IS NULL
352 $sth->execute($budget_id);
353 my $sum = ( $sth->fetchrow_array || 0 ) + 0;
355 $sth = $dbh->prepare(qq|
356 SELECT SUM(shipmentcost) AS sum
358 WHERE shipmentcost_budgetid = ?
361 $sth->execute($budget_id);
362 my ($shipmentcost_sum) = $sth->fetchrow_array;
363 $sum += ( $shipmentcost_sum || 0 ) + 0;
365 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
366 while ( my $adj = $adjustments->next ){
367 $sum += $adj->adjustment;
373 # -------------------------------------------------------------------
374 sub GetBudgetOrdered {
375 my ($budget_id) = @_;
376 my $dbh = C4::Context->dbh;
377 my $sth = $dbh->prepare(qq|
378 SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . qq| * quantity) AS sum FROM aqorders
379 WHERE budget_id = ? AND
380 quantityreceived = 0 AND
381 datecancellationprinted IS NULL
383 $sth->execute($budget_id);
384 my $sum = ( $sth->fetchrow_array || 0 ) + 0;
386 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
387 while ( my $adj = $adjustments->next ){
388 $sum += $adj->adjustment;
396 my $budget_name = &GetBudgetName($budget_id);
398 get the budget_name for a given budget_id
403 my ( $budget_id ) = @_;
404 my $dbh = C4::Context->dbh;
405 my $sth = $dbh->prepare(
412 $sth->execute($budget_id);
413 return $sth->fetchrow_array;
416 =head2 GetBudgetAuthCats
418 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
420 Return the list of authcat for a given budget_period_id
424 sub GetBudgetAuthCats {
425 my ($budget_period_id) = shift;
426 # now, populate the auth_cats_loop used in the budget planning button
427 # we must retrieve all auth values used by at least one budget
428 my $dbh = C4::Context->dbh;
429 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
430 $sth->execute($budget_period_id);
432 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
433 $authcats{$sort1_authcat}=1 if $sort1_authcat;
434 $authcats{$sort2_authcat}=1 if $sort2_authcat;
436 return [ sort keys %authcats ];
439 # -------------------------------------------------------------------
440 sub GetBudgetPeriods {
441 my ($filters,$orderby) = @_;
443 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
444 $rs = $rs->search( $filters, { order_by => $orderby } );
445 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
448 # -------------------------------------------------------------------
449 sub GetBudgetPeriod {
450 my ($budget_period_id) = @_;
451 my $dbh = C4::Context->dbh;
452 my $sth = $dbh->prepare( qq|
455 WHERE budget_period_id=? |
457 $sth->execute($budget_period_id);
458 return $sth->fetchrow_hashref;
462 my ($budget_period_id) = @_;
463 my $dbh = C4::Context->dbh;
464 ; ## $total = number of records linked to the record that must be deleted
467 ## get information about the record that will be deleted
468 my $sth = $dbh->prepare(qq|
471 WHERE budget_period_id=? |
473 return $sth->execute($budget_period_id);
476 # -------------------------------------------------------------------
477 sub ModBudgetPeriod {
478 my ($budget_period) = @_;
479 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
480 return unless($result);
482 $result = $result->update($budget_period);
483 return $result->in_storage;
486 # -------------------------------------------------------------------
487 sub GetBudgetHierarchy {
488 my ( $budget_period_id, $branchcode, $owner, $skiptotals ) = @_;
490 my $dbh = C4::Context->dbh;
492 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
493 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
495 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
496 JOIN aqbudgetperiods USING (budget_period_id)|;
499 # show only period X if requested
500 if ($budget_period_id) {
501 push @where_strings," aqbudgets.budget_period_id = ?";
502 push @bind_params, $budget_period_id;
504 # show only budgets owned by me, my branch or everyone
508 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="")))};
509 push @bind_params, ( $owner, $branchcode );
511 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
512 push @bind_params, $owner;
516 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
517 push @bind_params, $branchcode;
520 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
521 my $sth = $dbh->prepare($query);
522 $sth->execute(@bind_params);
525 # create hash with budget_id has key
526 while ( my $data = $sth->fetchrow_hashref ) {
527 $links{ $data->{'budget_id'} } = $data;
530 # link child to parent
532 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
533 my $child = $links{$budget->{budget_id}};
534 if ( $child->{'budget_parent_id'} ) {
535 my $parent = $links{ $child->{'budget_parent_id'} };
537 unless ( $parent->{'children'} ) {
538 # init child arrayref
539 $parent->{'children'} = [];
542 push @{ $parent->{'children'} }, $child;
545 push @first_parents, $child;
550 foreach my $first_parent (@first_parents) {
551 _add_budget_children(\@sort, $first_parent, 0);
554 # Get all the budgets totals in as few queries as possible
555 my $hr_budget_spent = $dbh->selectall_hashref(q|
556 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
557 SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE(unitprice_tax_included, ecost_tax_included)|) . q| * quantity ) AS budget_spent
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_ordered = $dbh->selectall_hashref(q|
563 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
564 SUM( | . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . q| * quantity) AS budget_ordered
565 FROM aqorders JOIN aqbudgets USING (budget_id)
566 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
567 GROUP BY budget_id, budget_parent_id
569 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
570 SELECT shipmentcost_budgetid as budget_id,
571 SUM(shipmentcost) as shipmentcost
573 GROUP BY shipmentcost_budgetid
575 my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q|
577 SUM(adjustment) as adjustments
578 FROM aqinvoice_adjustments
579 JOIN aqinvoices USING (invoiceid)
580 WHERE closedate IS NOT NULL
583 my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q|
585 SUM(adjustment) as adjustments
586 FROM aqinvoice_adjustments
587 JOIN aqinvoices USING (invoiceid)
588 WHERE closedate IS NULL AND encumber_open = 1
593 foreach my $budget (@sort) {
594 if ( not defined $budget->{budget_parent_id} ) {
595 _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
603 my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ) = @_;
605 foreach my $child (@{$budget->{children}}){
606 _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
609 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent} || 0;
610 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost} || 0;
611 $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments} || 0;
612 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered} || 0;
613 $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments} || 0;
615 $budget->{total_spent} += $budget->{budget_spent};
616 $budget->{total_ordered} += $budget->{budget_ordered};
619 $parent->{total_spent} += $budget->{total_spent};
620 $parent->{total_ordered} += $budget->{total_ordered};
624 # Recursive method to add a budget and its chidren to an array
625 sub _add_budget_children {
628 $budget->{budget_level} = shift;
630 my $children = $budget->{'children'} || [];
631 return unless @$children; # break recursivity
632 foreach my $child (@$children) {
633 _add_budget_children($res, $child, $budget->{budget_level} + 1);
637 # -------------------------------------------------------------------
638 # FIXME Must be replaced by Koha::Acquisition::Fund->store
641 return unless ($budget);
643 undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq '';
644 undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq '';
645 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
646 my $id = $resultset->create($budget)->id;
649 if (C4::Context->preference("AcquisitionLog")) {
651 budget_amount => $budget->{budget_amount},
652 budget_encumb => $budget->{budget_encumb},
653 budget_expend => $budget->{budget_expend}
665 # -------------------------------------------------------------------
666 # FIXME Must be replaced by Koha::Acquisition::Fund->store
669 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
670 return unless($result);
672 # Log this modification
673 if (C4::Context->preference("AcquisitionLog")) {
675 budget_amount_new => $budget->{budget_amount},
676 budget_encumb_new => $budget->{budget_encumb},
677 budget_expend_new => $budget->{budget_expend},
678 budget_amount_old => $result->budget_amount,
679 budget_encumb_old => $result->budget_encumb,
680 budget_expend_old => $result->budget_expend,
681 budget_amount_change => 0 - ($result->budget_amount - $budget->{budget_amount})
686 $budget->{budget_id},
691 undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq '';
692 undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq '';
693 $result = $result->update($budget);
694 return $result->in_storage;
697 # -------------------------------------------------------------------
698 # FIXME Must be replaced by Koha::Acquisition::Fund->delete
700 my ($budget_id) = @_;
701 my $dbh = C4::Context->dbh;
702 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
703 my $rc = $sth->execute($budget_id);
705 if (C4::Context->preference("AcquisitionLog")) {
716 # -------------------------------------------------------------------
720 &GetBudget($budget_id);
722 get a specific budget
727 my ( $budget_id ) = @_;
728 my $dbh = C4::Context->dbh;
734 my $sth = $dbh->prepare($query);
735 $sth->execute( $budget_id );
736 my $result = $sth->fetchrow_hashref;
740 # -------------------------------------------------------------------
742 =head2 GetBudgetByOrderNumber
744 &GetBudgetByOrderNumber($ordernumber);
746 get a specific budget by order number
750 sub GetBudgetByOrderNumber {
751 my ( $ordernumber ) = @_;
752 my $dbh = C4::Context->dbh;
755 FROM aqbudgets, aqorders
757 AND aqorders.budget_id = aqbudgets.budget_id
759 my $sth = $dbh->prepare($query);
760 $sth->execute( $ordernumber );
761 my $result = $sth->fetchrow_hashref;
765 =head2 GetBudgetReport
767 &GetBudgetReport( [$budget_id] );
769 Get all orders for a specific budget, without cancelled orders.
771 Returns an array of hashrefs.
775 # --------------------------------------------------------------------
776 sub GetBudgetReport {
777 my ( $budget_id ) = @_;
778 my $dbh = C4::Context->dbh;
780 SELECT o.*, b.budget_name
782 INNER JOIN aqorders o
783 ON b.budget_id = o.budget_id
785 AND (o.orderstatus != "cancelled")
786 ORDER BY b.budget_name';
788 my $sth = $dbh->prepare($query);
789 $sth->execute( $budget_id );
792 while ( my $data = $sth->fetchrow_hashref ) {
793 push( @results, $data );
798 =head2 GetBudgetsByActivity
800 &GetBudgetsByActivity( $budget_period_active );
802 Get all active or inactive budgets, depending of the value
810 # --------------------------------------------------------------------
811 sub GetBudgetsByActivity {
812 my ( $budget_period_active ) = @_;
813 my $dbh = C4::Context->dbh;
816 FROM aqbudgetperiods bp
817 INNER JOIN aqbudgets b
818 ON bp.budget_period_id = b.budget_period_id
819 WHERE bp.budget_period_active=?
821 my $sth = $dbh->prepare($query);
822 $sth->execute( $budget_period_active );
824 while ( my $data = $sth->fetchrow_hashref ) {
825 push( @results, $data );
829 # --------------------------------------------------------------------
831 =head2 GetBudgetsReport
833 &GetBudgetsReport( [$activity] );
835 Get all but cancelled orders for all funds.
837 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
842 Returns an array of hashrefs.
846 sub GetBudgetsReport {
848 my $dbh = C4::Context->dbh;
850 SELECT o.*, b.budget_name
851 FROM aqbudgetperiods bp
852 INNER JOIN aqbudgets b
853 ON bp.budget_period_id = b.budget_period_id
854 INNER JOIN aqorders o
855 ON b.budget_id = o.budget_id ';
856 if ( $activity && $activity ne '' ) {
857 $query .= 'WHERE bp.budget_period_active=? ';
859 $query .= 'AND (o.orderstatus != "cancelled")
860 ORDER BY b.budget_name';
862 my $sth = $dbh->prepare($query);
863 if ( $activity && $activity ne '' ) {
864 $sth->execute($activity);
870 while ( my $data = $sth->fetchrow_hashref ) {
871 push( @results, $data );
876 =head2 GetBudgetByCode
878 my $budget = &GetBudgetByCode($budget_code);
880 Retrieve all aqbudgets fields as a hashref for the budget that has
885 sub GetBudgetByCode {
886 my ( $budget_code ) = @_;
888 my $dbh = C4::Context->dbh;
892 JOIN aqbudgetperiods USING (budget_period_id)
893 WHERE budget_code = ?
894 ORDER BY budget_period_active DESC, budget_id DESC
897 my $sth = $dbh->prepare( $query );
898 $sth->execute( $budget_code );
899 return $sth->fetchrow_hashref;
902 =head2 GetBudgetHierarchySpent
904 my $spent = GetBudgetHierarchySpent( $budget_id );
906 Gets the total spent of the level and sublevels of $budget_id
910 sub GetBudgetHierarchySpent {
911 my ( $budget_id ) = @_;
912 my $dbh = C4::Context->dbh;
913 my $children_ids = $dbh->selectcol_arrayref(q|
916 WHERE budget_parent_id = ?
919 my $total_spent = GetBudgetSpent( $budget_id );
920 for my $child_id ( @$children_ids ) {
921 $total_spent += GetBudgetHierarchySpent( $child_id );
926 =head2 GetBudgetHierarchyOrdered
928 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
930 Gets the total ordered of the level and sublevels of $budget_id
934 sub GetBudgetHierarchyOrdered {
935 my ( $budget_id ) = @_;
936 my $dbh = C4::Context->dbh;
937 my $children_ids = $dbh->selectcol_arrayref(q|
940 WHERE budget_parent_id = ?
943 my $total_ordered = GetBudgetOrdered( $budget_id );
944 for my $child_id ( @$children_ids ) {
945 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
947 return $total_ordered;
952 &GetBudgets($filter, $order_by);
958 # -------------------------------------------------------------------
960 my ($filters, $orderby) = @_;
961 $orderby = 'budget_name' unless($orderby);
963 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
964 $rs = $rs->search( $filters, { order_by => $orderby } );
965 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
969 =head2 GetBudgetUsers
971 my @borrowernumbers = &GetBudgetUsers($budget_id);
973 Return the list of borrowernumbers linked to a budget
978 my ($budget_id) = @_;
980 my $dbh = C4::Context->dbh;
982 SELECT borrowernumber
983 FROM aqbudgetborrowers
986 my $sth = $dbh->prepare($query);
987 $sth->execute($budget_id);
990 while (my ($borrowernumber) = $sth->fetchrow_array) {
991 push @borrowernumbers, $borrowernumber
994 return @borrowernumbers;
997 =head2 ModBudgetUsers
999 &ModBudgetUsers($budget_id, @borrowernumbers);
1001 Modify the list of borrowernumbers linked to a budget
1005 sub ModBudgetUsers {
1006 my ($budget_id, @budget_users_id) = @_;
1008 return unless $budget_id;
1010 my $dbh = C4::Context->dbh;
1011 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
1012 my $sth = $dbh->prepare($query);
1013 $sth->execute($budget_id);
1016 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
1019 $sth = $dbh->prepare($query);
1020 foreach my $borrowernumber (@budget_users_id) {
1021 next unless $borrowernumber;
1022 $sth->execute($budget_id, $borrowernumber);
1026 sub CanUserUseBudget {
1027 my ($borrower, $budget, $userflags) = @_;
1029 if (not ref $borrower) {
1030 $borrower = Koha::Patrons->find( $borrower );
1031 return 0 unless $borrower;
1032 $borrower = $borrower->unblessed;
1034 if (not ref $budget) {
1035 $budget = GetBudget($budget);
1038 return 0 unless ($borrower and $budget);
1040 if (not defined $userflags) {
1041 $userflags = C4::Auth::getuserflags($borrower->{flags},
1042 $borrower->{userid});
1045 unless ($userflags->{superlibrarian}
1046 || (ref $userflags->{acquisition}
1047 && $userflags->{acquisition}->{budget_manage_all})
1048 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1050 if (not exists $userflags->{acquisition}) {
1054 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
1058 # Budget restricted to owner
1059 if ( $budget->{budget_permission} == 1 ) {
1060 if ( $budget->{budget_owner_id}
1061 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1067 # Budget restricted to owner, users and library
1068 elsif ( $budget->{budget_permission} == 2 ) {
1069 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1073 $budget->{budget_owner_id}
1074 and $budget->{budget_owner_id} !=
1075 $borrower->{borrowernumber}
1076 or not $budget->{budget_owner_id}
1078 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1080 and defined $budget->{budget_branchcode}
1081 and $budget->{budget_branchcode} ne
1082 C4::Context->userenv->{branch}
1089 # Budget restricted to owner and users
1090 elsif ( $budget->{budget_permission} == 3 ) {
1091 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1094 $budget->{budget_owner_id}
1095 and $budget->{budget_owner_id} !=
1096 $borrower->{borrowernumber}
1097 or not $budget->{budget_owner_id}
1099 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1111 sub CanUserModifyBudget {
1112 my ($borrower, $budget, $userflags) = @_;
1114 if (not ref $borrower) {
1115 $borrower = Koha::Patrons->find( $borrower );
1116 return 0 unless $borrower;
1117 $borrower = $borrower->unblessed;
1119 if (not ref $budget) {
1120 $budget = GetBudget($budget);
1123 return 0 unless ($borrower and $budget);
1125 if (not defined $userflags) {
1126 $userflags = C4::Auth::getuserflags($borrower->{flags},
1127 $borrower->{userid});
1130 unless ($userflags->{superlibrarian}
1131 || (ref $userflags->{acquisition}
1132 && $userflags->{acquisition}->{budget_manage_all})
1133 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1135 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1139 if (ref $userflags->{acquisition}
1140 && !$userflags->{acquisition}->{budget_modify}) {
1149 my ($value, $increment) = @_;
1151 if ($increment && $increment != 0) {
1152 $value = int($value / $increment) * $increment;
1158 =head2 CloneBudgetPeriod
1160 my $new_budget_period_id = CloneBudgetPeriod({
1161 budget_period_id => $budget_period_id,
1162 budget_period_startdate => $budget_period_startdate,
1163 budget_period_enddate => $budget_period_enddate,
1164 mark_original_budget_as_inactive => 1n
1165 reset_all_budgets => 1,
1168 Clone a budget period with all budgets.
1169 If the mark_origin_budget_as_inactive is set (0 by default),
1170 the original budget will be marked as inactive.
1172 If the reset_all_budgets is set (0 by default), all budget (fund)
1173 amounts will be reset.
1177 sub CloneBudgetPeriod {
1179 my $budget_period_id = $params->{budget_period_id};
1180 my $budget_period_startdate = $params->{budget_period_startdate};
1181 my $budget_period_enddate = $params->{budget_period_enddate};
1182 my $budget_period_description = $params->{budget_period_description};
1183 my $amount_change_percentage = $params->{amount_change_percentage};
1184 my $amount_change_round_increment = $params->{amount_change_round_increment};
1185 my $mark_original_budget_as_inactive =
1186 $params->{mark_original_budget_as_inactive} || 0;
1187 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1189 my $budget_period = GetBudgetPeriod($budget_period_id);
1191 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1192 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1193 $budget_period->{budget_period_description} = $budget_period_description;
1194 # The new budget (budget_period) should be active by default
1195 $budget_period->{budget_period_active} = 1;
1197 if ($amount_change_percentage) {
1198 my $total = $budget_period->{budget_period_total};
1199 $total += $total * $amount_change_percentage / 100;
1200 $total = _round($total, $amount_change_round_increment);
1201 $budget_period->{budget_period_total} = $total;
1204 my $original_budget_period_id = $budget_period->{budget_period_id};
1205 delete $budget_period->{budget_period_id};
1206 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1208 my $budgets = GetBudgetHierarchy($budget_period_id);
1209 CloneBudgetHierarchy(
1211 budgets => $budgets,
1212 new_budget_period_id => $new_budget_period_id
1216 if ($mark_original_budget_as_inactive) {
1219 budget_period_id => $budget_period_id,
1220 budget_period_active => 0,
1225 if ( $reset_all_budgets ) {
1226 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1227 for my $budget ( @$budgets ) {
1228 $budget->{budget_amount} = 0;
1229 ModBudget( $budget );
1231 } elsif ($amount_change_percentage) {
1232 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1233 for my $budget ( @$budgets ) {
1234 my $amount = $budget->{budget_amount};
1235 $amount += $amount * $amount_change_percentage / 100;
1236 $amount = _round($amount, $amount_change_round_increment);
1237 $budget->{budget_amount} = $amount;
1238 ModBudget( $budget );
1242 return $new_budget_period_id;
1245 =head2 CloneBudgetHierarchy
1247 CloneBudgetHierarchy({
1248 budgets => $budgets,
1249 new_budget_period_id => $new_budget_period_id;
1252 Clone a budget hierarchy.
1256 sub CloneBudgetHierarchy {
1258 my $budgets = $params->{budgets};
1259 my $new_budget_period_id = $params->{new_budget_period_id};
1260 next unless @$budgets or $new_budget_period_id;
1262 my $children_of = $params->{children_of};
1263 my $new_parent_id = $params->{new_parent_id};
1265 my @first_level_budgets =
1266 ( not defined $children_of )
1267 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1268 : map { ( defined $_->{budget_parent_id} && $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1270 # get only the columns of aqbudgets
1271 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1273 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1274 @first_level_budgets )
1278 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1280 delete $tidy_budget->{timestamp};
1281 my $new_budget_id = AddBudget(
1285 budget_parent_id => $new_parent_id,
1286 budget_period_id => $new_budget_period_id
1289 my @borrowernumbers = GetBudgetUsers($budget->{budget_id});
1290 ModBudgetUsers($new_budget_id, @borrowernumbers);
1291 CloneBudgetHierarchy(
1293 budgets => $budgets,
1294 new_budget_period_id => $new_budget_period_id,
1295 children_of => $budget->{budget_id},
1296 new_parent_id => $new_budget_id
1304 my $report = MoveOrders({
1305 from_budget_period_id => $from_budget_period_id,
1306 to_budget_period_id => $to_budget_period_id,
1309 Move orders from one budget period to another.
1315 my $from_budget_period_id = $params->{from_budget_period_id};
1316 my $to_budget_period_id = $params->{to_budget_period_id};
1317 my $move_remaining_unspent = $params->{move_remaining_unspent};
1319 if not $from_budget_period_id
1320 or not $to_budget_period_id
1321 or $from_budget_period_id == $to_budget_period_id;
1323 # Can't move orders to an inactive budget (budgetperiod)
1324 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1325 return unless $budget_period->{budget_period_active};
1328 my $dbh = C4::Context->dbh;
1329 my $sth_update_aqorders = $dbh->prepare(
1333 WHERE ordernumber = ?
1336 my $sth_update_budget_amount = $dbh->prepare(
1339 SET budget_amount = ?
1343 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1344 for my $from_budget (@$from_budgets) {
1345 my $new_budget_id = $dbh->selectcol_arrayref(
1349 WHERE budget_period_id = ?
1351 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1353 $new_budget_id = $new_budget_id->[0];
1354 my $new_budget = GetBudget( $new_budget_id );
1355 unless ( $new_budget ) {
1359 budget => $from_budget,
1360 error => 'budget_code_not_exists',
1364 my $orders_to_move = C4::Acquisition::SearchOrders(
1366 budget_id => $from_budget->{budget_id},
1372 for my $order (@$orders_to_move) {
1373 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1374 push @orders_moved, $order;
1377 my $unspent_moved = 0;
1378 if ($move_remaining_unspent) {
1379 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1380 my $unspent = $from_budget->{budget_amount} - $spent;
1381 my $new_budget_amount = $new_budget->{budget_amount};
1382 if ( $unspent > 0 ) {
1383 $new_budget_amount += $unspent;
1384 $unspent_moved = $unspent;
1386 $new_budget->{budget_amount} = $new_budget_amount;
1387 $sth_update_budget_amount->execute( $new_budget_amount,
1388 $new_budget->{budget_id} );
1393 budget => $new_budget,
1394 orders_moved => \@orders_moved,
1396 unspent_moved => $unspent_moved,
1402 END { } # module clean-up code here (global destructor)
1409 Koha Development Team <http://koha-community.org/>