Bug 22550: OPAC suggestion form doesn't require mandatory fields
[koha.git] / C4 / Budgets.pm
blob9c53236f7ddb777eb50476099a7cc770ddecb5a5
1 package C4::Budgets;
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>.
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use C4::Context;
23 use Koha::Database;
24 use Koha::Patrons;
25 use Koha::Acquisition::Invoice::Adjustments;
26 use C4::Debug;
27 use C4::Acquisition;
28 use vars qw(@ISA @EXPORT);
30 BEGIN {
31 require Exporter;
32 @ISA = qw(Exporter);
33 @EXPORT = qw(
35 &GetBudget
36 &GetBudgetByOrderNumber
37 &GetBudgetByCode
38 &GetBudgets
39 &BudgetsByActivity
40 &GetBudgetsReport
41 &GetBudgetReport
42 &GetBudgetHierarchy
43 &AddBudget
44 &ModBudget
45 &DelBudget
46 &GetBudgetSpent
47 &GetBudgetOrdered
48 &GetBudgetName
49 &GetPeriodsCount
50 GetBudgetHierarchySpent
51 GetBudgetHierarchyOrdered
53 &GetBudgetUsers
54 &ModBudgetUsers
55 &CanUserUseBudget
56 &CanUserModifyBudget
58 &GetBudgetPeriod
59 &GetBudgetPeriods
60 &ModBudgetPeriod
61 &AddBudgetPeriod
62 &DelBudgetPeriod
64 &ModBudgetPlan
66 &GetBudgetsPlanCell
67 &AddBudgetPlanValue
68 &GetBudgetAuthCats
69 &BudgetHasChildren
70 &CheckBudgetParent
71 &CheckBudgetParentPerm
73 &HideCols
74 &GetCols
78 # ----------------------------BUDGETS.PM-----------------------------";
80 =head1 FUNCTIONS ABOUT BUDGETS
82 =cut
84 sub HideCols {
85 my ( $authcat, @hide_cols ) = @_;
86 my $dbh = C4::Context->dbh;
88 my $sth1 = $dbh->prepare(
89 qq|
90 UPDATE aqbudgets_planning SET display = 0
91 WHERE authcat = ?
92 AND authvalue = ? |
94 foreach my $authvalue (@hide_cols) {
95 # $sth1->{TraceLevel} = 3;
96 $sth1->execute( $authcat, $authvalue );
100 sub GetCols {
101 my ( $authcat, $authvalue ) = @_;
103 my $dbh = C4::Context->dbh;
104 my $sth = $dbh->prepare(
106 SELECT count(display) as cnt from aqbudgets_planning
107 WHERE authcat = ?
108 AND authvalue = ? and display = 0 |
111 # $sth->{TraceLevel} = 3;
112 $sth->execute( $authcat, $authvalue );
113 my $res = $sth->fetchrow_hashref;
115 return $res->{cnt} > 0 ? 0: 1
119 sub CheckBudgetParentPerm {
120 my ( $budget, $borrower_id ) = @_;
121 my $depth = $budget->{depth};
122 my $parent_id = $budget->{budget_parent_id};
123 while ($depth) {
124 my $parent = GetBudget($parent_id);
125 $parent_id = $parent->{budget_parent_id};
126 if ( $parent->{budget_owner_id} == $borrower_id ) {
127 return 1;
129 $depth--
131 return 0;
134 sub AddBudgetPeriod {
135 my ($budgetperiod) = @_;
136 return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
138 undef $budgetperiod->{budget_period_id};
139 my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
140 return $resultset->create($budgetperiod)->id;
142 # -------------------------------------------------------------------
143 sub GetPeriodsCount {
144 my $dbh = C4::Context->dbh;
145 my $sth = $dbh->prepare("
146 SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
147 $sth->execute();
148 my $res = $sth->fetchrow_hashref;
149 return $res->{'sum'};
152 # -------------------------------------------------------------------
153 sub CheckBudgetParent {
154 my ( $new_parent, $budget ) = @_;
155 my $new_parent_id = $new_parent->{'budget_id'};
156 my $budget_id = $budget->{'budget_id'};
157 my $dbh = C4::Context->dbh;
158 my $parent_id_tmp = $new_parent_id;
160 # check new-parent is not a child (or a child's child ;)
161 my $sth = $dbh->prepare(qq|
162 SELECT budget_parent_id FROM
163 aqbudgets where budget_id = ? | );
164 while (1) {
165 $sth->execute($parent_id_tmp);
166 my $res = $sth->fetchrow_hashref;
167 if ( $res->{'budget_parent_id'} == $budget_id ) {
168 return 1;
170 if ( not defined $res->{'budget_parent_id'} ) {
171 return 0;
173 $parent_id_tmp = $res->{'budget_parent_id'};
177 # -------------------------------------------------------------------
178 sub BudgetHasChildren {
179 my ( $budget_id ) = @_;
180 my $dbh = C4::Context->dbh;
181 my $sth = $dbh->prepare(qq|
182 SELECT count(*) as sum FROM aqbudgets
183 WHERE budget_parent_id = ? | );
184 $sth->execute( $budget_id );
185 my $sum = $sth->fetchrow_hashref;
186 return $sum->{'sum'};
189 sub GetBudgetChildren {
190 my ( $budget_id ) = @_;
191 my $dbh = C4::Context->dbh;
192 return $dbh->selectall_arrayref(q|
193 SELECT * FROM aqbudgets
194 WHERE budget_parent_id = ?
195 |, { Slice => {} }, $budget_id );
198 sub SetOwnerToFundHierarchy {
199 my ( $budget_id, $borrowernumber ) = @_;
201 my $budget = GetBudget( $budget_id );
202 $budget->{budget_owner_id} = $borrowernumber;
203 ModBudget( $budget );
204 my $children = GetBudgetChildren( $budget_id );
205 for my $child ( @$children ) {
206 SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
210 # -------------------------------------------------------------------
211 sub GetBudgetsPlanCell {
212 my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period
213 my ($actual, $sth);
214 my $dbh = C4::Context->dbh;
215 my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|);
216 if ( $cell->{'authcat'} eq 'MONTHS' ) {
217 # get the actual amount
218 # FIXME we should consider quantity
219 $sth = $dbh->prepare( qq|
221 SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders
222 WHERE budget_id = ? AND
223 entrydate like "$cell->{'authvalue'}%" |
225 $sth->execute( $cell->{'budget_id'} );
226 } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
227 # get the actual amount
228 # FIXME we should consider quantity
229 $sth = $dbh->prepare( qq|
231 SELECT SUM(| . $roundsql . qq|) FROM aqorders
232 LEFT JOIN aqorders_items
233 ON (aqorders.ordernumber = aqorders_items.ordernumber)
234 LEFT JOIN items
235 ON (aqorders_items.itemnumber = items.itemnumber)
236 WHERE budget_id = ? AND homebranch = ? | );
238 $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
239 } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
240 # get the actual amount
241 $sth = $dbh->prepare( qq|
243 SELECT SUM( | . $roundsql . qq| * quantity) AS actual
244 FROM aqorders JOIN biblioitems
245 ON (biblioitems.biblionumber = aqorders.biblionumber )
246 WHERE aqorders.budget_id = ? and itemtype = ? |
248 $sth->execute( $cell->{'budget_id'},
249 $cell->{'authvalue'} );
251 # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
252 else {
253 # get the actual amount
254 $sth = $dbh->prepare( qq|
256 SELECT SUM(| . $roundsql . qq| * quantity) AS actual
257 FROM aqorders
258 JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
259 WHERE aqorders.budget_id = ? AND
260 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
261 (aqbudgets.sort2_authcat = ? AND sort2 =?)) |
263 $sth->execute( $cell->{'budget_id'},
264 $budget->{'sort1_authcat'},
265 $cell->{'authvalue'},
266 $budget->{'sort2_authcat'},
267 $cell->{'authvalue'}
270 $actual = $sth->fetchrow_array;
272 # get the estimated amount
273 $sth = $dbh->prepare( qq|
275 SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
276 WHERE budget_period_id = ? AND
277 budget_id = ? AND
278 authvalue = ? AND
279 authcat = ? |
281 $sth->execute( $cell->{'budget_period_id'},
282 $cell->{'budget_id'},
283 $cell->{'authvalue'},
284 $cell->{'authcat'},
288 my $res = $sth->fetchrow_hashref;
289 # my $display = $res->{'display'};
290 my $estimated = $res->{'estimated'};
293 return $actual, $estimated;
296 # -------------------------------------------------------------------
297 sub ModBudgetPlan {
298 my ( $budget_plan, $budget_period_id, $authcat ) = @_;
299 my $dbh = C4::Context->dbh;
300 foreach my $buds (@$budget_plan) {
301 my $lines = $buds->{lines};
302 my $sth = $dbh->prepare( qq|
303 DELETE FROM aqbudgets_planning
304 WHERE budget_period_id = ? AND
305 budget_id = ? AND
306 authcat = ? |
308 #delete a aqplan line of cells, then insert new cells,
309 # these could be UPDATES rather than DEL/INSERTS...
310 $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat );
312 foreach my $cell (@$lines) {
313 my $sth = $dbh->prepare( qq|
315 INSERT INTO aqbudgets_planning
316 SET budget_id = ?,
317 budget_period_id = ?,
318 authcat = ?,
319 estimated_amount = ?,
320 authvalue = ? |
322 $sth->execute(
323 $cell->{'budget_id'},
324 $cell->{'budget_period_id'},
325 $cell->{'authcat'},
326 $cell->{'estimated_amount'},
327 $cell->{'authvalue'},
333 # -------------------------------------------------------------------
334 sub GetBudgetSpent {
335 my ($budget_id) = @_;
336 my $dbh = C4::Context->dbh;
337 # unitprice_tax_included should always been set here
338 # we should not need to retrieve ecost_tax_included
339 my $sth = $dbh->prepare(qq|
340 SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE(unitprice_tax_included, ecost_tax_included)") . qq| * quantity ) AS sum FROM aqorders
341 WHERE budget_id = ? AND
342 quantityreceived > 0 AND
343 datecancellationprinted IS NULL
345 $sth->execute($budget_id);
346 my $sum = 0 + $sth->fetchrow_array;
348 $sth = $dbh->prepare(qq|
349 SELECT SUM(shipmentcost) AS sum
350 FROM aqinvoices
351 WHERE shipmentcost_budgetid = ?
354 $sth->execute($budget_id);
355 my ($shipmentcost_sum) = $sth->fetchrow_array;
356 $sum += $shipmentcost_sum;
358 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
359 while ( my $adj = $adjustments->next ){
360 $sum += $adj->adjustment;
363 return $sum;
366 # -------------------------------------------------------------------
367 sub GetBudgetOrdered {
368 my ($budget_id) = @_;
369 my $dbh = C4::Context->dbh;
370 my $sth = $dbh->prepare(qq|
371 SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . qq| * quantity) AS sum FROM aqorders
372 WHERE budget_id = ? AND
373 quantityreceived = 0 AND
374 datecancellationprinted IS NULL
376 $sth->execute($budget_id);
377 my $sum = 0 + $sth->fetchrow_array;
379 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
380 while ( my $adj = $adjustments->next ){
381 $sum += $adj->adjustment;
384 return $sum;
387 =head2 GetBudgetName
389 my $budget_name = &GetBudgetName($budget_id);
391 get the budget_name for a given budget_id
393 =cut
395 sub GetBudgetName {
396 my ( $budget_id ) = @_;
397 my $dbh = C4::Context->dbh;
398 my $sth = $dbh->prepare(
400 SELECT budget_name
401 FROM aqbudgets
402 WHERE budget_id = ?
405 $sth->execute($budget_id);
406 return $sth->fetchrow_array;
409 =head2 GetBudgetAuthCats
411 my $auth_cats = &GetBudgetAuthCats($budget_period_id);
413 Return the list of authcat for a given budget_period_id
415 =cut
417 sub GetBudgetAuthCats {
418 my ($budget_period_id) = shift;
419 # now, populate the auth_cats_loop used in the budget planning button
420 # we must retrieve all auth values used by at least one budget
421 my $dbh = C4::Context->dbh;
422 my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
423 $sth->execute($budget_period_id);
424 my %authcats;
425 while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
426 $authcats{$sort1_authcat}=1 if $sort1_authcat;
427 $authcats{$sort2_authcat}=1 if $sort2_authcat;
429 return [ sort keys %authcats ];
432 # -------------------------------------------------------------------
433 sub GetBudgetPeriods {
434 my ($filters,$orderby) = @_;
436 my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
437 $rs = $rs->search( $filters, { order_by => $orderby } );
438 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
439 return [ $rs->all ];
441 # -------------------------------------------------------------------
442 sub GetBudgetPeriod {
443 my ($budget_period_id) = @_;
444 my $dbh = C4::Context->dbh;
445 ## $total = number of records linked to the record that must be deleted
446 my $total = 0;
447 ## get information about the record that will be deleted
448 my $sth;
449 if ($budget_period_id) {
450 $sth = $dbh->prepare( qq|
451 SELECT *
452 FROM aqbudgetperiods
453 WHERE budget_period_id=? |
455 $sth->execute($budget_period_id);
456 } else { # ACTIVE BUDGET
457 $sth = $dbh->prepare(qq|
458 SELECT *
459 FROM aqbudgetperiods
460 WHERE budget_period_active=1 |
462 $sth->execute();
464 my $data = $sth->fetchrow_hashref;
465 return $data;
468 sub DelBudgetPeriod{
469 my ($budget_period_id) = @_;
470 my $dbh = C4::Context->dbh;
471 ; ## $total = number of records linked to the record that must be deleted
472 my $total = 0;
474 ## get information about the record that will be deleted
475 my $sth = $dbh->prepare(qq|
476 DELETE
477 FROM aqbudgetperiods
478 WHERE budget_period_id=? |
480 return $sth->execute($budget_period_id);
483 # -------------------------------------------------------------------
484 sub ModBudgetPeriod {
485 my ($budget_period) = @_;
486 my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
487 return unless($result);
489 $result = $result->update($budget_period);
490 return $result->in_storage;
493 # -------------------------------------------------------------------
494 sub GetBudgetHierarchy {
495 my ( $budget_period_id, $branchcode, $owner ) = @_;
496 my @bind_params;
497 my $dbh = C4::Context->dbh;
498 my $query = qq|
499 SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
500 b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
501 FROM aqbudgets
502 LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
503 JOIN aqbudgetperiods USING (budget_period_id)|;
505 my @where_strings;
506 # show only period X if requested
507 if ($budget_period_id) {
508 push @where_strings," aqbudgets.budget_period_id = ?";
509 push @bind_params, $budget_period_id;
511 # show only budgets owned by me, my branch or everyone
512 if ($owner) {
513 if ($branchcode) {
514 push @where_strings,
515 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="")))};
516 push @bind_params, ( $owner, $branchcode );
517 } else {
518 push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
519 push @bind_params, $owner;
521 } else {
522 if ($branchcode) {
523 push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
524 push @bind_params, $branchcode;
527 $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
528 $debug && warn $query,join(",",@bind_params);
529 my $sth = $dbh->prepare($query);
530 $sth->execute(@bind_params);
532 my %links;
533 # create hash with budget_id has key
534 while ( my $data = $sth->fetchrow_hashref ) {
535 $links{ $data->{'budget_id'} } = $data;
538 # link child to parent
539 my @first_parents;
540 foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
541 my $child = $links{$budget->{budget_id}};
542 if ( $child->{'budget_parent_id'} ) {
543 my $parent = $links{ $child->{'budget_parent_id'} };
544 if ($parent) {
545 unless ( $parent->{'children'} ) {
546 # init child arrayref
547 $parent->{'children'} = [];
549 # add as child
550 push @{ $parent->{'children'} }, $child;
552 } else {
553 push @first_parents, $child;
557 my @sort = ();
558 foreach my $first_parent (@first_parents) {
559 _add_budget_children(\@sort, $first_parent, 0);
562 # Get all the budgets totals in as few queries as possible
563 my $hr_budget_spent = $dbh->selectall_hashref(q|
564 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
565 SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE(unitprice_tax_included, ecost_tax_included)|) . q| * quantity ) AS budget_spent
566 FROM aqorders JOIN aqbudgets USING (budget_id)
567 WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
568 GROUP BY budget_id, budget_parent_id
569 |, 'budget_id');
570 my $hr_budget_ordered = $dbh->selectall_hashref(q|
571 SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
572 SUM( | . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . q| * quantity) AS budget_ordered
573 FROM aqorders JOIN aqbudgets USING (budget_id)
574 WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
575 GROUP BY budget_id, budget_parent_id
576 |, 'budget_id');
577 my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
578 SELECT shipmentcost_budgetid as budget_id,
579 SUM(shipmentcost) as shipmentcost
580 FROM aqinvoices
581 WHERE closedate IS NOT NULL
582 GROUP BY shipmentcost_budgetid
583 |, 'budget_id');
584 my $hr_budget_ordered_shipment = $dbh->selectall_hashref(q|
585 SELECT shipmentcost_budgetid as budget_id,
586 SUM(shipmentcost) as shipmentcost
587 FROM aqinvoices
588 WHERE closedate IS NULL
589 GROUP BY shipmentcost_budgetid
590 |, 'budget_id');
591 my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q|
592 SELECT budget_id,
593 SUM(adjustment) as adjustments
594 FROM aqinvoice_adjustments
595 JOIN aqinvoices USING (invoiceid)
596 WHERE closedate IS NOT NULL
597 GROUP BY budget_id
598 |, 'budget_id');
599 my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q|
600 SELECT budget_id,
601 SUM(adjustment) as adjustments
602 FROM aqinvoice_adjustments
603 JOIN aqinvoices USING (invoiceid)
604 WHERE closedate IS NULL AND encumber_open = 1
605 GROUP BY budget_id
606 |, 'budget_id');
609 foreach my $budget (@sort) {
610 if ( not defined $budget->{budget_parent_id} ) {
611 _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 );
614 return \@sort;
617 sub _recursiveAdd {
618 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 ) = @_;
620 foreach my $child (@{$budget->{children}}){
621 _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 );
624 $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
625 $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
626 $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments};
627 $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
628 $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
629 $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments};
631 $budget->{total_spent} += $budget->{budget_spent};
632 $budget->{total_ordered} += $budget->{budget_ordered};
634 if ($parent) {
635 $parent->{total_spent} += $budget->{total_spent};
636 $parent->{total_ordered} += $budget->{total_ordered};
640 # Recursive method to add a budget and its chidren to an array
641 sub _add_budget_children {
642 my $res = shift;
643 my $budget = shift;
644 $budget->{budget_level} = shift;
645 push @$res, $budget;
646 my $children = $budget->{'children'} || [];
647 return unless @$children; # break recursivity
648 foreach my $child (@$children) {
649 _add_budget_children($res, $child, $budget->{budget_level} + 1);
653 # -------------------------------------------------------------------
655 sub AddBudget {
656 my ($budget) = @_;
657 return unless ($budget);
659 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
660 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
661 my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
662 return $resultset->create($budget)->id;
665 # -------------------------------------------------------------------
666 sub ModBudget {
667 my ($budget) = @_;
668 my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
669 return unless($result);
671 undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
672 undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
673 $result = $result->update($budget);
674 return $result->in_storage;
677 # -------------------------------------------------------------------
678 sub DelBudget {
679 my ($budget_id) = @_;
680 my $dbh = C4::Context->dbh;
681 my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?");
682 my $rc = $sth->execute($budget_id);
683 return $rc;
687 # -------------------------------------------------------------------
689 =head2 GetBudget
691 &GetBudget($budget_id);
693 get a specific budget
695 =cut
697 sub GetBudget {
698 my ( $budget_id ) = @_;
699 my $dbh = C4::Context->dbh;
700 my $query = "
701 SELECT *
702 FROM aqbudgets
703 WHERE budget_id=?
705 my $sth = $dbh->prepare($query);
706 $sth->execute( $budget_id );
707 my $result = $sth->fetchrow_hashref;
708 return $result;
711 # -------------------------------------------------------------------
713 =head2 GetBudgetByOrderNumber
715 &GetBudgetByOrderNumber($ordernumber);
717 get a specific budget by order number
719 =cut
721 sub GetBudgetByOrderNumber {
722 my ( $ordernumber ) = @_;
723 my $dbh = C4::Context->dbh;
724 my $query = "
725 SELECT aqbudgets.*
726 FROM aqbudgets, aqorders
727 WHERE ordernumber=?
728 AND aqorders.budget_id = aqbudgets.budget_id
730 my $sth = $dbh->prepare($query);
731 $sth->execute( $ordernumber );
732 my $result = $sth->fetchrow_hashref;
733 return $result;
736 =head2 GetBudgetReport
738 &GetBudgetReport( [$budget_id] );
740 Get all orders for a specific budget, without cancelled orders.
742 Returns an array of hashrefs.
744 =cut
746 # --------------------------------------------------------------------
747 sub GetBudgetReport {
748 my ( $budget_id ) = @_;
749 my $dbh = C4::Context->dbh;
750 my $query = '
751 SELECT o.*, b.budget_name
752 FROM aqbudgets b
753 INNER JOIN aqorders o
754 ON b.budget_id = o.budget_id
755 WHERE b.budget_id=?
756 AND (o.orderstatus != "cancelled")
757 ORDER BY b.budget_name';
759 my $sth = $dbh->prepare($query);
760 $sth->execute( $budget_id );
762 my @results = ();
763 while ( my $data = $sth->fetchrow_hashref ) {
764 push( @results, $data );
766 return @results;
769 =head2 GetBudgetsByActivity
771 &GetBudgetsByActivity( $budget_period_active );
773 Get all active or inactive budgets, depending of the value
774 of the parameter.
776 1 = active
777 0 = inactive
779 =cut
781 # --------------------------------------------------------------------
782 sub GetBudgetsByActivity {
783 my ( $budget_period_active ) = @_;
784 my $dbh = C4::Context->dbh;
785 my $query = "
786 SELECT DISTINCT b.*
787 FROM aqbudgetperiods bp
788 INNER JOIN aqbudgets b
789 ON bp.budget_period_id = b.budget_period_id
790 WHERE bp.budget_period_active=?
792 my $sth = $dbh->prepare($query);
793 $sth->execute( $budget_period_active );
794 my @results = ();
795 while ( my $data = $sth->fetchrow_hashref ) {
796 push( @results, $data );
798 return @results;
800 # --------------------------------------------------------------------
802 =head2 GetBudgetsReport
804 &GetBudgetsReport( [$activity] );
806 Get all but cancelled orders for all funds.
808 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
810 active = 1
811 inactive = 0
813 Returns an array of hashrefs.
815 =cut
817 sub GetBudgetsReport {
818 my ($activity) = @_;
819 my $dbh = C4::Context->dbh;
820 my $query = '
821 SELECT o.*, b.budget_name
822 FROM aqbudgetperiods bp
823 INNER JOIN aqbudgets b
824 ON bp.budget_period_id = b.budget_period_id
825 INNER JOIN aqorders o
826 ON b.budget_id = o.budget_id ';
827 if($activity ne ''){
828 $query .= 'WHERE bp.budget_period_active=? ';
830 $query .= 'AND (o.orderstatus != "cancelled")
831 ORDER BY b.budget_name';
833 my $sth = $dbh->prepare($query);
834 if($activity ne ''){
835 $sth->execute($activity);
837 else{
838 $sth->execute;
840 my @results = ();
841 while ( my $data = $sth->fetchrow_hashref ) {
842 push( @results, $data );
844 return @results;
847 =head2 GetBudgetByCode
849 my $budget = &GetBudgetByCode($budget_code);
851 Retrieve all aqbudgets fields as a hashref for the budget that has
852 given budget_code
854 =cut
856 sub GetBudgetByCode {
857 my ( $budget_code ) = @_;
859 my $dbh = C4::Context->dbh;
860 my $query = qq{
861 SELECT aqbudgets.*
862 FROM aqbudgets
863 JOIN aqbudgetperiods USING (budget_period_id)
864 WHERE budget_code = ?
865 ORDER BY budget_period_active DESC, budget_id DESC
866 LIMIT 1
868 my $sth = $dbh->prepare( $query );
869 $sth->execute( $budget_code );
870 return $sth->fetchrow_hashref;
873 =head2 GetBudgetHierarchySpent
875 my $spent = GetBudgetHierarchySpent( $budget_id );
877 Gets the total spent of the level and sublevels of $budget_id
879 =cut
881 sub GetBudgetHierarchySpent {
882 my ( $budget_id ) = @_;
883 my $dbh = C4::Context->dbh;
884 my $children_ids = $dbh->selectcol_arrayref(q|
885 SELECT budget_id
886 FROM aqbudgets
887 WHERE budget_parent_id = ?
888 |, {}, $budget_id );
890 my $total_spent = GetBudgetSpent( $budget_id );
891 for my $child_id ( @$children_ids ) {
892 $total_spent += GetBudgetHierarchySpent( $child_id );
894 return $total_spent;
897 =head2 GetBudgetHierarchyOrdered
899 my $ordered = GetBudgetHierarchyOrdered( $budget_id );
901 Gets the total ordered of the level and sublevels of $budget_id
903 =cut
905 sub GetBudgetHierarchyOrdered {
906 my ( $budget_id ) = @_;
907 my $dbh = C4::Context->dbh;
908 my $children_ids = $dbh->selectcol_arrayref(q|
909 SELECT budget_id
910 FROM aqbudgets
911 WHERE budget_parent_id = ?
912 |, {}, $budget_id );
914 my $total_ordered = GetBudgetOrdered( $budget_id );
915 for my $child_id ( @$children_ids ) {
916 $total_ordered += GetBudgetHierarchyOrdered( $child_id );
918 return $total_ordered;
921 =head2 GetBudgets
923 &GetBudgets($filter, $order_by);
925 gets all budgets
927 =cut
929 # -------------------------------------------------------------------
930 sub GetBudgets {
931 my ($filters, $orderby) = @_;
932 $orderby = 'budget_name' unless($orderby);
934 my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
935 $rs = $rs->search( $filters, { order_by => $orderby } );
936 $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
937 return [ $rs->all ];
940 =head2 GetBudgetUsers
942 my @borrowernumbers = &GetBudgetUsers($budget_id);
944 Return the list of borrowernumbers linked to a budget
946 =cut
948 sub GetBudgetUsers {
949 my ($budget_id) = @_;
951 my $dbh = C4::Context->dbh;
952 my $query = qq{
953 SELECT borrowernumber
954 FROM aqbudgetborrowers
955 WHERE budget_id = ?
957 my $sth = $dbh->prepare($query);
958 $sth->execute($budget_id);
960 my @borrowernumbers;
961 while (my ($borrowernumber) = $sth->fetchrow_array) {
962 push @borrowernumbers, $borrowernumber
965 return @borrowernumbers;
968 =head2 ModBudgetUsers
970 &ModBudgetUsers($budget_id, @borrowernumbers);
972 Modify the list of borrowernumbers linked to a budget
974 =cut
976 sub ModBudgetUsers {
977 my ($budget_id, @budget_users_id) = @_;
979 return unless $budget_id;
981 my $dbh = C4::Context->dbh;
982 my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
983 my $sth = $dbh->prepare($query);
984 $sth->execute($budget_id);
986 $query = qq{
987 INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
988 VALUES (?,?)
990 $sth = $dbh->prepare($query);
991 foreach my $borrowernumber (@budget_users_id) {
992 next unless $borrowernumber;
993 $sth->execute($budget_id, $borrowernumber);
997 sub CanUserUseBudget {
998 my ($borrower, $budget, $userflags) = @_;
1000 if (not ref $borrower) {
1001 $borrower = Koha::Patrons->find( $borrower );
1002 return 0 unless $borrower;
1003 $borrower = $borrower->unblessed;
1005 if (not ref $budget) {
1006 $budget = GetBudget($budget);
1009 return 0 unless ($borrower and $budget);
1011 if (not defined $userflags) {
1012 $userflags = C4::Auth::getuserflags($borrower->{flags},
1013 $borrower->{userid});
1016 unless ($userflags->{superlibrarian}
1017 || (ref $userflags->{acquisition}
1018 && $userflags->{acquisition}->{budget_manage_all})
1019 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1021 if (not exists $userflags->{acquisition}) {
1022 return 0;
1025 if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
1026 return 0;
1029 # Budget restricted to owner
1030 if ( $budget->{budget_permission} == 1 ) {
1031 if ( $budget->{budget_owner_id}
1032 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
1034 return 0;
1038 # Budget restricted to owner, users and library
1039 elsif ( $budget->{budget_permission} == 2 ) {
1040 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1042 if (
1044 $budget->{budget_owner_id}
1045 and $budget->{budget_owner_id} !=
1046 $borrower->{borrowernumber}
1047 or not $budget->{budget_owner_id}
1049 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1050 @budget_users )
1051 and defined $budget->{budget_branchcode}
1052 and $budget->{budget_branchcode} ne
1053 C4::Context->userenv->{branch}
1056 return 0;
1060 # Budget restricted to owner and users
1061 elsif ( $budget->{budget_permission} == 3 ) {
1062 my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1063 if (
1065 $budget->{budget_owner_id}
1066 and $budget->{budget_owner_id} !=
1067 $borrower->{borrowernumber}
1068 or not $budget->{budget_owner_id}
1070 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1071 @budget_users )
1074 return 0;
1079 return 1;
1082 sub CanUserModifyBudget {
1083 my ($borrower, $budget, $userflags) = @_;
1085 if (not ref $borrower) {
1086 $borrower = Koha::Patrons->find( $borrower );
1087 return 0 unless $borrower;
1088 $borrower = $borrower->unblessed;
1090 if (not ref $budget) {
1091 $budget = GetBudget($budget);
1094 return 0 unless ($borrower and $budget);
1096 if (not defined $userflags) {
1097 $userflags = C4::Auth::getuserflags($borrower->{flags},
1098 $borrower->{userid});
1101 unless ($userflags->{superlibrarian}
1102 || (ref $userflags->{acquisition}
1103 && $userflags->{acquisition}->{budget_manage_all})
1104 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1106 if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1107 return 0;
1110 if (ref $userflags->{acquisition}
1111 && !$userflags->{acquisition}->{budget_modify}) {
1112 return 0;
1116 return 1;
1119 sub _round {
1120 my ($value, $increment) = @_;
1122 if ($increment && $increment != 0) {
1123 $value = int($value / $increment) * $increment;
1126 return $value;
1129 =head2 CloneBudgetPeriod
1131 my $new_budget_period_id = CloneBudgetPeriod({
1132 budget_period_id => $budget_period_id,
1133 budget_period_startdate => $budget_period_startdate,
1134 budget_period_enddate => $budget_period_enddate,
1135 mark_original_budget_as_inactive => 1n
1136 reset_all_budgets => 1,
1139 Clone a budget period with all budgets.
1140 If the mark_origin_budget_as_inactive is set (0 by default),
1141 the original budget will be marked as inactive.
1143 If the reset_all_budgets is set (0 by default), all budget (fund)
1144 amounts will be reset.
1146 =cut
1148 sub CloneBudgetPeriod {
1149 my ($params) = @_;
1150 my $budget_period_id = $params->{budget_period_id};
1151 my $budget_period_startdate = $params->{budget_period_startdate};
1152 my $budget_period_enddate = $params->{budget_period_enddate};
1153 my $budget_period_description = $params->{budget_period_description};
1154 my $amount_change_percentage = $params->{amount_change_percentage};
1155 my $amount_change_round_increment = $params->{amount_change_round_increment};
1156 my $mark_original_budget_as_inactive =
1157 $params->{mark_original_budget_as_inactive} || 0;
1158 my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1160 my $budget_period = GetBudgetPeriod($budget_period_id);
1162 $budget_period->{budget_period_startdate} = $budget_period_startdate;
1163 $budget_period->{budget_period_enddate} = $budget_period_enddate;
1164 $budget_period->{budget_period_description} = $budget_period_description;
1165 # The new budget (budget_period) should be active by default
1166 $budget_period->{budget_period_active} = 1;
1168 if ($amount_change_percentage) {
1169 my $total = $budget_period->{budget_period_total};
1170 $total += $total * $amount_change_percentage / 100;
1171 $total = _round($total, $amount_change_round_increment);
1172 $budget_period->{budget_period_total} = $total;
1175 my $original_budget_period_id = $budget_period->{budget_period_id};
1176 delete $budget_period->{budget_period_id};
1177 my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1179 my $budgets = GetBudgetHierarchy($budget_period_id);
1180 CloneBudgetHierarchy(
1182 budgets => $budgets,
1183 new_budget_period_id => $new_budget_period_id
1187 if ($mark_original_budget_as_inactive) {
1188 ModBudgetPeriod(
1190 budget_period_id => $budget_period_id,
1191 budget_period_active => 0,
1196 if ( $reset_all_budgets ) {
1197 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1198 for my $budget ( @$budgets ) {
1199 $budget->{budget_amount} = 0;
1200 ModBudget( $budget );
1202 } elsif ($amount_change_percentage) {
1203 my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1204 for my $budget ( @$budgets ) {
1205 my $amount = $budget->{budget_amount};
1206 $amount += $amount * $amount_change_percentage / 100;
1207 $amount = _round($amount, $amount_change_round_increment);
1208 $budget->{budget_amount} = $amount;
1209 ModBudget( $budget );
1213 return $new_budget_period_id;
1216 =head2 CloneBudgetHierarchy
1218 CloneBudgetHierarchy({
1219 budgets => $budgets,
1220 new_budget_period_id => $new_budget_period_id;
1223 Clone a budget hierarchy.
1225 =cut
1227 sub CloneBudgetHierarchy {
1228 my ($params) = @_;
1229 my $budgets = $params->{budgets};
1230 my $new_budget_period_id = $params->{new_budget_period_id};
1231 next unless @$budgets or $new_budget_period_id;
1233 my $children_of = $params->{children_of};
1234 my $new_parent_id = $params->{new_parent_id};
1236 my @first_level_budgets =
1237 ( not defined $children_of )
1238 ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets
1239 : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1241 # get only the columns of aqbudgets
1242 my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1244 for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1245 @first_level_budgets )
1248 my $tidy_budget =
1249 { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1250 keys %$budget };
1251 delete $tidy_budget->{timestamp};
1252 my $new_budget_id = AddBudget(
1254 %$tidy_budget,
1255 budget_id => undef,
1256 budget_parent_id => $new_parent_id,
1257 budget_period_id => $new_budget_period_id
1260 CloneBudgetHierarchy(
1262 budgets => $budgets,
1263 new_budget_period_id => $new_budget_period_id,
1264 children_of => $budget->{budget_id},
1265 new_parent_id => $new_budget_id
1271 =head2 MoveOrders
1273 my $report = MoveOrders({
1274 from_budget_period_id => $from_budget_period_id,
1275 to_budget_period_id => $to_budget_period_id,
1278 Move orders from one budget period to another.
1280 =cut
1282 sub MoveOrders {
1283 my ($params) = @_;
1284 my $from_budget_period_id = $params->{from_budget_period_id};
1285 my $to_budget_period_id = $params->{to_budget_period_id};
1286 my $move_remaining_unspent = $params->{move_remaining_unspent};
1287 return
1288 if not $from_budget_period_id
1289 or not $to_budget_period_id
1290 or $from_budget_period_id == $to_budget_period_id;
1292 # Can't move orders to an inactive budget (budgetperiod)
1293 my $budget_period = GetBudgetPeriod($to_budget_period_id);
1294 return unless $budget_period->{budget_period_active};
1296 my @report;
1297 my $dbh = C4::Context->dbh;
1298 my $sth_update_aqorders = $dbh->prepare(
1300 UPDATE aqorders
1301 SET budget_id = ?
1302 WHERE ordernumber = ?
1305 my $sth_update_budget_amount = $dbh->prepare(
1307 UPDATE aqbudgets
1308 SET budget_amount = ?
1309 WHERE budget_id = ?
1312 my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1313 for my $from_budget (@$from_budgets) {
1314 my $new_budget_id = $dbh->selectcol_arrayref(
1316 SELECT budget_id
1317 FROM aqbudgets
1318 WHERE budget_period_id = ?
1319 AND budget_code = ?
1320 |, {}, $to_budget_period_id, $from_budget->{budget_code}
1322 $new_budget_id = $new_budget_id->[0];
1323 my $new_budget = GetBudget( $new_budget_id );
1324 unless ( $new_budget ) {
1325 push @report,
1327 moved => 0,
1328 budget => $from_budget,
1329 error => 'budget_code_not_exists',
1331 next;
1333 my $orders_to_move = C4::Acquisition::SearchOrders(
1335 budget_id => $from_budget->{budget_id},
1336 pending => 1,
1340 my @orders_moved;
1341 for my $order (@$orders_to_move) {
1342 $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1343 push @orders_moved, $order;
1346 my $unspent_moved = 0;
1347 if ($move_remaining_unspent) {
1348 my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1349 my $unspent = $from_budget->{budget_amount} - $spent;
1350 my $new_budget_amount = $new_budget->{budget_amount};
1351 if ( $unspent > 0 ) {
1352 $new_budget_amount += $unspent;
1353 $unspent_moved = $unspent;
1355 $new_budget->{budget_amount} = $new_budget_amount;
1356 $sth_update_budget_amount->execute( $new_budget_amount,
1357 $new_budget->{budget_id} );
1360 push @report,
1362 budget => $new_budget,
1363 orders_moved => \@orders_moved,
1364 moved => 1,
1365 unspent_moved => $unspent_moved,
1368 return \@report;
1371 END { } # module clean-up code here (global destructor)
1374 __END__
1376 =head1 AUTHOR
1378 Koha Development Team <http://koha-community.org/>
1380 =cut