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;
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 undef $budgetperiod->{budget_period_id};
138 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
139 return $resultset->create($budgetperiod)->id;
141 # -------------------------------------------------------------------
142 sub GetPeriodsCount {
143 my $dbh = C4::Context->dbh;
144 my $sth = $dbh->prepare("
145 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
147 my $res = $sth->fetchrow_hashref;
148 return $res->{'sum'};
151 # -------------------------------------------------------------------
152 sub CheckBudgetParent {
153 my ( $new_parent, $budget ) = @_;
154 my $new_parent_id = $new_parent->{'budget_id'};
155 my $budget_id = $budget->{'budget_id'};
156 my $dbh = C4::Context->dbh;
157 my $parent_id_tmp = $new_parent_id;
159 # check new-parent is not a child (or a child's child ;)
160 my $sth = $dbh->prepare(qq|
161 SELECT budget_parent_id FROM
162 aqbudgets where budget_id = ? | );
164 $sth->execute($parent_id_tmp);
165 my $res = $sth->fetchrow_hashref;
166 if ( $res->{'budget_parent_id'} == $budget_id ) {
169 if ( not defined $res->{'budget_parent_id'} ) {
172 $parent_id_tmp = $res->{'budget_parent_id'};
176 # -------------------------------------------------------------------
177 sub BudgetHasChildren {
178 my ( $budget_id ) = @_;
179 my $dbh = C4::Context->dbh;
180 my $sth = $dbh->prepare(qq|
181 SELECT count(*) as sum FROM aqbudgets
182 WHERE budget_parent_id = ? | );
183 $sth->execute( $budget_id );
184 my $sum = $sth->fetchrow_hashref;
185 return $sum->{'sum'};
188 sub GetBudgetChildren {
189 my ( $budget_id ) = @_;
190 my $dbh = C4::Context->dbh;
191 return $dbh->selectall_arrayref(q|
192 SELECT * FROM aqbudgets
193 WHERE budget_parent_id = ?
194 |, { Slice => {} }, $budget_id );
197 sub SetOwnerToFundHierarchy {
198 my ( $budget_id, $borrowernumber ) = @_;
200 my $budget = GetBudget( $budget_id );
201 $budget->{budget_owner_id} = $borrowernumber;
202 ModBudget( $budget );
203 my $children = GetBudgetChildren( $budget_id );
204 for my $child ( @$children ) {
205 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
209 # -------------------------------------------------------------------
210 sub GetBudgetsPlanCell {
211 my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period
213 my $dbh = C4::Context->dbh;
214 my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|);
215 if ( $cell->{'authcat'} eq 'MONTHS' ) {
216 # get the actual amount
217 # FIXME we should consider quantity
218 $sth = $dbh->prepare( qq|
220 SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders
221 WHERE budget_id = ? AND
222 entrydate like "$cell->{'authvalue'}%" |
224 $sth->execute( $cell->{'budget_id'} );
225 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
226 # get the actual amount
227 # FIXME we should consider quantity
228 $sth = $dbh->prepare( qq|
230 SELECT SUM(| . $roundsql . qq|) FROM aqorders
231 LEFT JOIN aqorders_items
232 ON (aqorders.ordernumber = aqorders_items.ordernumber)
234 ON (aqorders_items.itemnumber = items.itemnumber)
235 WHERE budget_id = ? AND homebranch = ? | );
237 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
238 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
239 # get the actual amount
240 $sth = $dbh->prepare( qq|
242 SELECT SUM( | . $roundsql . qq| * quantity) AS actual
243 FROM aqorders JOIN biblioitems
244 ON (biblioitems.biblionumber = aqorders.biblionumber )
245 WHERE aqorders.budget_id = ? and itemtype = ? |
247 $sth->execute( $cell->{'budget_id'},
248 $cell->{'authvalue'} );
250 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
252 # get the actual amount
253 $sth = $dbh->prepare( qq|
255 SELECT SUM(| . $roundsql . qq| * quantity) AS actual
257 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
258 WHERE aqorders.budget_id = ? AND
259 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
260 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
262 $sth->execute( $cell->{'budget_id'},
263 $budget->{'sort1_authcat'},
264 $cell->{'authvalue'},
265 $budget->{'sort2_authcat'},
269 $actual = $sth->fetchrow_array;
271 # get the estimated amount
272 $sth = $dbh->prepare( qq|
274 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
275 WHERE budget_period_id = ? AND
280 $sth->execute( $cell->{'budget_period_id'},
281 $cell->{'budget_id'},
282 $cell->{'authvalue'},
287 my $res = $sth->fetchrow_hashref;
288 # my $display = $res->{'display'};
289 my $estimated = $res->{'estimated'};
292 return $actual, $estimated;
295 # -------------------------------------------------------------------
297 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
298 my $dbh = C4::Context->dbh;
299 foreach my $buds (@$budget_plan) {
300 my $lines = $buds->{lines};
301 my $sth = $dbh->prepare( qq|
302 DELETE FROM aqbudgets_planning
303 WHERE budget_period_id = ? AND
307 #delete a aqplan line of cells, then insert new cells,
308 # these could be UPDATES rather than DEL/INSERTS...
309 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
311 foreach my $cell (@$lines) {
312 my $sth = $dbh->prepare( qq|
314 INSERT INTO aqbudgets_planning
316 budget_period_id = ?,
318 estimated_amount = ?,
322 $cell->{'budget_id'},
323 $cell->{'budget_period_id'},
325 $cell->{'estimated_amount'},
326 $cell->{'authvalue'},
332 # -------------------------------------------------------------------
334 my ($budget_id) = @_;
335 my $dbh = C4::Context->dbh;
336 # unitprice_tax_included should always been set here
337 # we should not need to retrieve ecost_tax_included
338 my $sth = $dbh->prepare(qq|
339 SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE(unitprice_tax_included, ecost_tax_included)") . qq| * quantity ) AS sum FROM aqorders
340 WHERE budget_id = ? AND
341 quantityreceived > 0 AND
342 datecancellationprinted IS NULL
344 $sth->execute($budget_id);
345 my $sum = 0 + $sth->fetchrow_array;
347 $sth = $dbh->prepare(qq|
348 SELECT SUM(shipmentcost) AS sum
350 WHERE shipmentcost_budgetid = ?
353 $sth->execute($budget_id);
354 my ($shipmentcost_sum) = $sth->fetchrow_array;
355 $sum += $shipmentcost_sum;
357 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
358 while ( my $adj = $adjustments->next ){
359 $sum += $adj->adjustment;
365 # -------------------------------------------------------------------
366 sub GetBudgetOrdered {
367 my ($budget_id) = @_;
368 my $dbh = C4::Context->dbh;
369 my $sth = $dbh->prepare(qq|
370 SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . qq| * quantity) AS sum FROM aqorders
371 WHERE budget_id = ? AND
372 quantityreceived = 0 AND
373 datecancellationprinted IS NULL
375 $sth->execute($budget_id);
376 my $sum = 0 + $sth->fetchrow_array;
378 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
379 while ( my $adj = $adjustments->next ){
380 $sum += $adj->adjustment;
388 my $budget_name = &GetBudgetName($budget_id);
390 get the budget_name for a given budget_id
395 my ( $budget_id ) = @_;
396 my $dbh = C4::Context->dbh;
397 my $sth = $dbh->prepare(
404 $sth->execute($budget_id);
405 return $sth->fetchrow_array;
408 =head2 GetBudgetAuthCats
410 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
412 Return the list of authcat for a given budget_period_id
416 sub GetBudgetAuthCats {
417 my ($budget_period_id) = shift;
418 # now, populate the auth_cats_loop used in the budget planning button
419 # we must retrieve all auth values used by at least one budget
420 my $dbh = C4::Context->dbh;
421 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
422 $sth->execute($budget_period_id);
424 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
425 $authcats{$sort1_authcat}=1 if $sort1_authcat;
426 $authcats{$sort2_authcat}=1 if $sort2_authcat;
428 return [ sort keys %authcats ];
431 # -------------------------------------------------------------------
432 sub GetBudgetPeriods {
433 my ($filters,$orderby) = @_;
435 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
436 $rs = $rs->search( $filters, { order_by => $orderby } );
437 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
440 # -------------------------------------------------------------------
441 sub GetBudgetPeriod {
442 my ($budget_period_id) = @_;
443 my $dbh = C4::Context->dbh;
444 my $sth = $dbh->prepare( qq|
447 WHERE budget_period_id=? |
449 $sth->execute($budget_period_id);
450 return $sth->fetchrow_hashref;
454 my ($budget_period_id) = @_;
455 my $dbh = C4::Context->dbh;
456 ; ## $total = number of records linked to the record that must be deleted
459 ## get information about the record that will be deleted
460 my $sth = $dbh->prepare(qq|
463 WHERE budget_period_id=? |
465 return $sth->execute($budget_period_id);
468 # -------------------------------------------------------------------
469 sub ModBudgetPeriod {
470 my ($budget_period) = @_;
471 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
472 return unless($result);
474 $result = $result->update($budget_period);
475 return $result->in_storage;
478 # -------------------------------------------------------------------
479 sub GetBudgetHierarchy {
480 my ( $budget_period_id, $branchcode, $owner ) = @_;
482 my $dbh = C4::Context->dbh;
484 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
485 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
487 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
488 JOIN aqbudgetperiods USING (budget_period_id)|;
491 # show only period X if requested
492 if ($budget_period_id) {
493 push @where_strings," aqbudgets.budget_period_id = ?";
494 push @bind_params, $budget_period_id;
496 # show only budgets owned by me, my branch or everyone
500 qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))};
501 push @bind_params, ( $owner, $branchcode );
503 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
504 push @bind_params, $owner;
508 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
509 push @bind_params, $branchcode;
512 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
513 $debug && warn $query,join(",",@bind_params);
514 my $sth = $dbh->prepare($query);
515 $sth->execute(@bind_params);
518 # create hash with budget_id has key
519 while ( my $data = $sth->fetchrow_hashref ) {
520 $links{ $data->{'budget_id'} } = $data;
523 # link child to parent
525 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
526 my $child = $links{$budget->{budget_id}};
527 if ( $child->{'budget_parent_id'} ) {
528 my $parent = $links{ $child->{'budget_parent_id'} };
530 unless ( $parent->{'children'} ) {
531 # init child arrayref
532 $parent->{'children'} = [];
535 push @{ $parent->{'children'} }, $child;
538 push @first_parents, $child;
543 foreach my $first_parent (@first_parents) {
544 _add_budget_children(\@sort, $first_parent, 0);
547 # Get all the budgets totals in as few queries as possible
548 my $hr_budget_spent = $dbh->selectall_hashref(q|
549 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
550 SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE(unitprice_tax_included, ecost_tax_included)|) . q| * quantity ) AS budget_spent
551 FROM aqorders JOIN aqbudgets USING (budget_id)
552 WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
553 GROUP BY budget_id, budget_parent_id
555 my $hr_budget_ordered = $dbh->selectall_hashref(q|
556 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
557 SUM( | . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . q| * quantity) AS budget_ordered
558 FROM aqorders JOIN aqbudgets USING (budget_id)
559 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
560 GROUP BY budget_id, budget_parent_id
562 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
563 SELECT shipmentcost_budgetid as budget_id,
564 SUM(shipmentcost) as shipmentcost
566 WHERE closedate IS NOT NULL
567 GROUP BY shipmentcost_budgetid
569 my $hr_budget_ordered_shipment = $dbh->selectall_hashref(q|
570 SELECT shipmentcost_budgetid as budget_id,
571 SUM(shipmentcost) as shipmentcost
573 WHERE closedate IS NULL
574 GROUP BY shipmentcost_budgetid
576 my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q|
578 SUM(adjustment) as adjustments
579 FROM aqinvoice_adjustments
580 JOIN aqinvoices USING (invoiceid)
581 WHERE closedate IS NOT NULL
584 my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q|
586 SUM(adjustment) as adjustments
587 FROM aqinvoice_adjustments
588 JOIN aqinvoices USING (invoiceid)
589 WHERE closedate IS NULL AND encumber_open = 1
594 foreach my $budget (@sort) {
595 if ( not defined $budget->{budget_parent_id} ) {
596 _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
603 my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment, $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_ordered_shipment, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
609 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
610 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
611 $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments};
612 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
613 $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
614 $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments};
616 $budget->{total_spent} += $budget->{budget_spent};
617 $budget->{total_ordered} += $budget->{budget_ordered};
620 $parent->{total_spent} += $budget->{total_spent};
621 $parent->{total_ordered} += $budget->{total_ordered};
625 # Recursive method to add a budget and its chidren to an array
626 sub _add_budget_children {
629 $budget->{budget_level} = shift;
631 my $children = $budget->{'children'} || [];
632 return unless @$children; # break recursivity
633 foreach my $child (@$children) {
634 _add_budget_children($res, $child, $budget->{budget_level} + 1);
638 # -------------------------------------------------------------------
642 return unless ($budget);
644 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
645 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
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 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
657 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
658 $result = $result->update($budget);
659 return $result->in_storage;
662 # -------------------------------------------------------------------
664 my ($budget_id) = @_;
665 my $dbh = C4::Context->dbh;
666 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
667 my $rc = $sth->execute($budget_id);
672 # -------------------------------------------------------------------
676 &GetBudget($budget_id);
678 get a specific budget
683 my ( $budget_id ) = @_;
684 my $dbh = C4::Context->dbh;
690 my $sth = $dbh->prepare($query);
691 $sth->execute( $budget_id );
692 my $result = $sth->fetchrow_hashref;
696 # -------------------------------------------------------------------
698 =head2 GetBudgetByOrderNumber
700 &GetBudgetByOrderNumber($ordernumber);
702 get a specific budget by order number
706 sub GetBudgetByOrderNumber {
707 my ( $ordernumber ) = @_;
708 my $dbh = C4::Context->dbh;
711 FROM aqbudgets, aqorders
713 AND aqorders.budget_id = aqbudgets.budget_id
715 my $sth = $dbh->prepare($query);
716 $sth->execute( $ordernumber );
717 my $result = $sth->fetchrow_hashref;
721 =head2 GetBudgetReport
723 &GetBudgetReport( [$budget_id] );
725 Get all orders for a specific budget, without cancelled orders.
727 Returns an array of hashrefs.
731 # --------------------------------------------------------------------
732 sub GetBudgetReport {
733 my ( $budget_id ) = @_;
734 my $dbh = C4::Context->dbh;
736 SELECT o.*, b.budget_name
738 INNER JOIN aqorders o
739 ON b.budget_id = o.budget_id
741 AND (o.orderstatus != "cancelled")
742 ORDER BY b.budget_name';
744 my $sth = $dbh->prepare($query);
745 $sth->execute( $budget_id );
748 while ( my $data = $sth->fetchrow_hashref ) {
749 push( @results, $data );
754 =head2 GetBudgetsByActivity
756 &GetBudgetsByActivity( $budget_period_active );
758 Get all active or inactive budgets, depending of the value
766 # --------------------------------------------------------------------
767 sub GetBudgetsByActivity {
768 my ( $budget_period_active ) = @_;
769 my $dbh = C4::Context->dbh;
772 FROM aqbudgetperiods bp
773 INNER JOIN aqbudgets b
774 ON bp.budget_period_id = b.budget_period_id
775 WHERE bp.budget_period_active=?
777 my $sth = $dbh->prepare($query);
778 $sth->execute( $budget_period_active );
780 while ( my $data = $sth->fetchrow_hashref ) {
781 push( @results, $data );
785 # --------------------------------------------------------------------
787 =head2 GetBudgetsReport
789 &GetBudgetsReport( [$activity] );
791 Get all but cancelled orders for all funds.
793 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
798 Returns an array of hashrefs.
802 sub GetBudgetsReport {
804 my $dbh = C4::Context->dbh;
806 SELECT o.*, b.budget_name
807 FROM aqbudgetperiods bp
808 INNER JOIN aqbudgets b
809 ON bp.budget_period_id = b.budget_period_id
810 INNER JOIN aqorders o
811 ON b.budget_id = o.budget_id ';
813 $query .= 'WHERE bp.budget_period_active=? ';
815 $query .= 'AND (o.orderstatus != "cancelled")
816 ORDER BY b.budget_name';
818 my $sth = $dbh->prepare($query);
820 $sth->execute($activity);
826 while ( my $data = $sth->fetchrow_hashref ) {
827 push( @results, $data );
832 =head2 GetBudgetByCode
834 my $budget = &GetBudgetByCode($budget_code);
836 Retrieve all aqbudgets fields as a hashref for the budget that has
841 sub GetBudgetByCode {
842 my ( $budget_code ) = @_;
844 my $dbh = C4::Context->dbh;
848 JOIN aqbudgetperiods USING (budget_period_id)
849 WHERE budget_code = ?
850 ORDER BY budget_period_active DESC, budget_id DESC
853 my $sth = $dbh->prepare( $query );
854 $sth->execute( $budget_code );
855 return $sth->fetchrow_hashref;
858 =head2 GetBudgetHierarchySpent
860 my $spent = GetBudgetHierarchySpent( $budget_id );
862 Gets the total spent of the level and sublevels of $budget_id
866 sub GetBudgetHierarchySpent {
867 my ( $budget_id ) = @_;
868 my $dbh = C4::Context->dbh;
869 my $children_ids = $dbh->selectcol_arrayref(q|
872 WHERE budget_parent_id = ?
875 my $total_spent = GetBudgetSpent( $budget_id );
876 for my $child_id ( @$children_ids ) {
877 $total_spent += GetBudgetHierarchySpent( $child_id );
882 =head2 GetBudgetHierarchyOrdered
884 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
886 Gets the total ordered of the level and sublevels of $budget_id
890 sub GetBudgetHierarchyOrdered {
891 my ( $budget_id ) = @_;
892 my $dbh = C4::Context->dbh;
893 my $children_ids = $dbh->selectcol_arrayref(q|
896 WHERE budget_parent_id = ?
899 my $total_ordered = GetBudgetOrdered( $budget_id );
900 for my $child_id ( @$children_ids ) {
901 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
903 return $total_ordered;
908 &GetBudgets($filter, $order_by);
914 # -------------------------------------------------------------------
916 my ($filters, $orderby) = @_;
917 $orderby = 'budget_name' unless($orderby);
919 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
920 $rs = $rs->search( $filters, { order_by => $orderby } );
921 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
925 =head2 GetBudgetUsers
927 my @borrowernumbers = &GetBudgetUsers($budget_id);
929 Return the list of borrowernumbers linked to a budget
934 my ($budget_id) = @_;
936 my $dbh = C4::Context->dbh;
938 SELECT borrowernumber
939 FROM aqbudgetborrowers
942 my $sth = $dbh->prepare($query);
943 $sth->execute($budget_id);
946 while (my ($borrowernumber) = $sth->fetchrow_array) {
947 push @borrowernumbers, $borrowernumber
950 return @borrowernumbers;
953 =head2 ModBudgetUsers
955 &ModBudgetUsers($budget_id, @borrowernumbers);
957 Modify the list of borrowernumbers linked to a budget
962 my ($budget_id, @budget_users_id) = @_;
964 return unless $budget_id;
966 my $dbh = C4::Context->dbh;
967 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
968 my $sth = $dbh->prepare($query);
969 $sth->execute($budget_id);
972 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
975 $sth = $dbh->prepare($query);
976 foreach my $borrowernumber (@budget_users_id) {
977 next unless $borrowernumber;
978 $sth->execute($budget_id, $borrowernumber);
982 sub CanUserUseBudget {
983 my ($borrower, $budget, $userflags) = @_;
985 if (not ref $borrower) {
986 $borrower = Koha::Patrons->find( $borrower );
987 return 0 unless $borrower;
988 $borrower = $borrower->unblessed;
990 if (not ref $budget) {
991 $budget = GetBudget($budget);
994 return 0 unless ($borrower and $budget);
996 if (not defined $userflags) {
997 $userflags = C4::Auth::getuserflags($borrower->{flags},
998 $borrower->{userid});
1001 unless ($userflags->{superlibrarian}
1002 || (ref $userflags->{acquisition}
1003 && $userflags->{acquisition}->{budget_manage_all})
1004 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1006 if (not exists $userflags->{acquisition}) {
1010 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
1014 # Budget restricted to owner
1015 if ( $budget->{budget_permission} == 1 ) {
1016 if ( $budget->{budget_owner_id}
1017 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1023 # Budget restricted to owner, users and library
1024 elsif ( $budget->{budget_permission} == 2 ) {
1025 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1029 $budget->{budget_owner_id}
1030 and $budget->{budget_owner_id} !=
1031 $borrower->{borrowernumber}
1032 or not $budget->{budget_owner_id}
1034 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1036 and defined $budget->{budget_branchcode}
1037 and $budget->{budget_branchcode} ne
1038 C4::Context->userenv->{branch}
1045 # Budget restricted to owner and users
1046 elsif ( $budget->{budget_permission} == 3 ) {
1047 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1050 $budget->{budget_owner_id}
1051 and $budget->{budget_owner_id} !=
1052 $borrower->{borrowernumber}
1053 or not $budget->{budget_owner_id}
1055 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1067 sub CanUserModifyBudget {
1068 my ($borrower, $budget, $userflags) = @_;
1070 if (not ref $borrower) {
1071 $borrower = Koha::Patrons->find( $borrower );
1072 return 0 unless $borrower;
1073 $borrower = $borrower->unblessed;
1075 if (not ref $budget) {
1076 $budget = GetBudget($budget);
1079 return 0 unless ($borrower and $budget);
1081 if (not defined $userflags) {
1082 $userflags = C4::Auth::getuserflags($borrower->{flags},
1083 $borrower->{userid});
1086 unless ($userflags->{superlibrarian}
1087 || (ref $userflags->{acquisition}
1088 && $userflags->{acquisition}->{budget_manage_all})
1089 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1091 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1095 if (ref $userflags->{acquisition}
1096 && !$userflags->{acquisition}->{budget_modify}) {
1105 my ($value, $increment) = @_;
1107 if ($increment && $increment != 0) {
1108 $value = int($value / $increment) * $increment;
1114 =head2 CloneBudgetPeriod
1116 my $new_budget_period_id = CloneBudgetPeriod({
1117 budget_period_id => $budget_period_id,
1118 budget_period_startdate => $budget_period_startdate,
1119 budget_period_enddate => $budget_period_enddate,
1120 mark_original_budget_as_inactive => 1n
1121 reset_all_budgets => 1,
1124 Clone a budget period with all budgets.
1125 If the mark_origin_budget_as_inactive is set (0 by default),
1126 the original budget will be marked as inactive.
1128 If the reset_all_budgets is set (0 by default), all budget (fund)
1129 amounts will be reset.
1133 sub CloneBudgetPeriod {
1135 my $budget_period_id = $params->{budget_period_id};
1136 my $budget_period_startdate = $params->{budget_period_startdate};
1137 my $budget_period_enddate = $params->{budget_period_enddate};
1138 my $budget_period_description = $params->{budget_period_description};
1139 my $amount_change_percentage = $params->{amount_change_percentage};
1140 my $amount_change_round_increment = $params->{amount_change_round_increment};
1141 my $mark_original_budget_as_inactive =
1142 $params->{mark_original_budget_as_inactive} || 0;
1143 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1145 my $budget_period = GetBudgetPeriod($budget_period_id);
1147 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1148 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1149 $budget_period->{budget_period_description} = $budget_period_description;
1150 # The new budget (budget_period) should be active by default
1151 $budget_period->{budget_period_active} = 1;
1153 if ($amount_change_percentage) {
1154 my $total = $budget_period->{budget_period_total};
1155 $total += $total * $amount_change_percentage / 100;
1156 $total = _round($total, $amount_change_round_increment);
1157 $budget_period->{budget_period_total} = $total;
1160 my $original_budget_period_id = $budget_period->{budget_period_id};
1161 delete $budget_period->{budget_period_id};
1162 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1164 my $budgets = GetBudgetHierarchy($budget_period_id);
1165 CloneBudgetHierarchy(
1167 budgets => $budgets,
1168 new_budget_period_id => $new_budget_period_id
1172 if ($mark_original_budget_as_inactive) {
1175 budget_period_id => $budget_period_id,
1176 budget_period_active => 0,
1181 if ( $reset_all_budgets ) {
1182 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1183 for my $budget ( @$budgets ) {
1184 $budget->{budget_amount} = 0;
1185 ModBudget( $budget );
1187 } elsif ($amount_change_percentage) {
1188 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1189 for my $budget ( @$budgets ) {
1190 my $amount = $budget->{budget_amount};
1191 $amount += $amount * $amount_change_percentage / 100;
1192 $amount = _round($amount, $amount_change_round_increment);
1193 $budget->{budget_amount} = $amount;
1194 ModBudget( $budget );
1198 return $new_budget_period_id;
1201 =head2 CloneBudgetHierarchy
1203 CloneBudgetHierarchy({
1204 budgets => $budgets,
1205 new_budget_period_id => $new_budget_period_id;
1208 Clone a budget hierarchy.
1212 sub CloneBudgetHierarchy {
1214 my $budgets = $params->{budgets};
1215 my $new_budget_period_id = $params->{new_budget_period_id};
1216 next unless @$budgets or $new_budget_period_id;
1218 my $children_of = $params->{children_of};
1219 my $new_parent_id = $params->{new_parent_id};
1221 my @first_level_budgets =
1222 ( not defined $children_of )
1223 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1224 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1226 # get only the columns of aqbudgets
1227 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1229 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1230 @first_level_budgets )
1234 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1236 delete $tidy_budget->{timestamp};
1237 my $new_budget_id = AddBudget(
1241 budget_parent_id => $new_parent_id,
1242 budget_period_id => $new_budget_period_id
1245 CloneBudgetHierarchy(
1247 budgets => $budgets,
1248 new_budget_period_id => $new_budget_period_id,
1249 children_of => $budget->{budget_id},
1250 new_parent_id => $new_budget_id
1258 my $report = MoveOrders({
1259 from_budget_period_id => $from_budget_period_id,
1260 to_budget_period_id => $to_budget_period_id,
1263 Move orders from one budget period to another.
1269 my $from_budget_period_id = $params->{from_budget_period_id};
1270 my $to_budget_period_id = $params->{to_budget_period_id};
1271 my $move_remaining_unspent = $params->{move_remaining_unspent};
1273 if not $from_budget_period_id
1274 or not $to_budget_period_id
1275 or $from_budget_period_id == $to_budget_period_id;
1277 # Can't move orders to an inactive budget (budgetperiod)
1278 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1279 return unless $budget_period->{budget_period_active};
1282 my $dbh = C4::Context->dbh;
1283 my $sth_update_aqorders = $dbh->prepare(
1287 WHERE ordernumber = ?
1290 my $sth_update_budget_amount = $dbh->prepare(
1293 SET budget_amount = ?
1297 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1298 for my $from_budget (@$from_budgets) {
1299 my $new_budget_id = $dbh->selectcol_arrayref(
1303 WHERE budget_period_id = ?
1305 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1307 $new_budget_id = $new_budget_id->[0];
1308 my $new_budget = GetBudget( $new_budget_id );
1309 unless ( $new_budget ) {
1313 budget => $from_budget,
1314 error => 'budget_code_not_exists',
1318 my $orders_to_move = C4::Acquisition::SearchOrders(
1320 budget_id => $from_budget->{budget_id},
1326 for my $order (@$orders_to_move) {
1327 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1328 push @orders_moved, $order;
1331 my $unspent_moved = 0;
1332 if ($move_remaining_unspent) {
1333 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1334 my $unspent = $from_budget->{budget_amount} - $spent;
1335 my $new_budget_amount = $new_budget->{budget_amount};
1336 if ( $unspent > 0 ) {
1337 $new_budget_amount += $unspent;
1338 $unspent_moved = $unspent;
1340 $new_budget->{budget_amount} = $new_budget_amount;
1341 $sth_update_budget_amount->execute( $new_budget_amount,
1342 $new_budget->{budget_id} );
1347 budget => $new_budget,
1348 orders_moved => \@orders_moved,
1350 unspent_moved => $unspent_moved,
1356 END { } # module clean-up code here (global destructor)
1363 Koha Development Team <http://koha-community.org/>