Bug 19792: Performance boost for GetBudgetHierarchy
[koha.git] / C4 / Budgets.pm
1 package C4::Budgets;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
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.
11 #
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.
16 #
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>.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use C4::Context;
23 use Koha::Database;
24 use Koha::Patrons;
25 use C4::Debug;
26 use vars qw(@ISA @EXPORT);
27
28 BEGIN {
29         require Exporter;
30         @ISA    = qw(Exporter);
31         @EXPORT = qw(
32
33         &GetBudget
34         &GetBudgetByOrderNumber
35         &GetBudgetByCode
36         &GetBudgets
37         &BudgetsByActivity
38         &GetBudgetsReport
39         &GetBudgetReport
40         &GetBudgetHierarchy
41             &AddBudget
42         &ModBudget
43         &DelBudget
44         &GetBudgetSpent
45         &GetBudgetOrdered
46         &GetBudgetName
47         &GetPeriodsCount
48         GetBudgetHierarchySpent
49         GetBudgetHierarchyOrdered
50
51         &GetBudgetUsers
52         &ModBudgetUsers
53         &CanUserUseBudget
54         &CanUserModifyBudget
55
56             &GetBudgetPeriod
57         &GetBudgetPeriods
58         &ModBudgetPeriod
59         &AddBudgetPeriod
60             &DelBudgetPeriod
61
62         &ModBudgetPlan
63
64                 &GetBudgetsPlanCell
65         &AddBudgetPlanValue
66         &GetBudgetAuthCats
67         &BudgetHasChildren
68         &CheckBudgetParent
69         &CheckBudgetParentPerm
70
71         &HideCols
72         &GetCols
73         );
74 }
75
76 # ----------------------------BUDGETS.PM-----------------------------";
77
78 =head1 FUNCTIONS ABOUT BUDGETS
79
80 =cut
81
82 sub HideCols {
83     my ( $authcat, @hide_cols ) = @_;
84     my $dbh = C4::Context->dbh;
85
86     my $sth1 = $dbh->prepare(
87         qq|
88         UPDATE aqbudgets_planning SET display = 0 
89         WHERE authcat = ? 
90         AND  authvalue = ? |
91     );
92     foreach my $authvalue (@hide_cols) {
93 #        $sth1->{TraceLevel} = 3;
94         $sth1->execute(  $authcat, $authvalue );
95     }
96 }
97
98 sub GetCols {
99     my ( $authcat, $authvalue ) = @_;
100
101     my $dbh = C4::Context->dbh;
102     my $sth = $dbh->prepare(
103         qq|
104         SELECT count(display) as cnt from aqbudgets_planning
105         WHERE  authcat = ? 
106         AND authvalue = ? and display  = 0   |
107     );
108
109 #    $sth->{TraceLevel} = 3;
110     $sth->execute( $authcat, $authvalue );
111     my $res  = $sth->fetchrow_hashref;
112
113     return  $res->{cnt} > 0 ? 0: 1
114
115 }
116
117 sub CheckBudgetParentPerm {
118     my ( $budget, $borrower_id ) = @_;
119     my $depth = $budget->{depth};
120     my $parent_id = $budget->{budget_parent_id};
121     while ($depth) {
122         my $parent = GetBudget($parent_id);
123         $parent_id = $parent->{budget_parent_id};
124         if ( $parent->{budget_owner_id} == $borrower_id ) {
125             return 1;
126         }
127         $depth--
128     }
129     return 0;
130 }
131
132 sub AddBudgetPeriod {
133     my ($budgetperiod) = @_;
134     return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
135
136     my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
137     return $resultset->create($budgetperiod)->id;
138 }
139 # -------------------------------------------------------------------
140 sub GetPeriodsCount {
141     my $dbh = C4::Context->dbh;
142     my $sth = $dbh->prepare("
143         SELECT COUNT(*) AS sum FROM aqbudgetperiods ");
144     $sth->execute();
145     my $res = $sth->fetchrow_hashref;
146     return $res->{'sum'};
147 }
148
149 # -------------------------------------------------------------------
150 sub CheckBudgetParent {
151     my ( $new_parent, $budget ) = @_;
152     my $new_parent_id = $new_parent->{'budget_id'};
153     my $budget_id     = $budget->{'budget_id'};
154     my $dbh           = C4::Context->dbh;
155     my $parent_id_tmp = $new_parent_id;
156
157     # check new-parent is not a child (or a child's child ;)
158     my $sth = $dbh->prepare(qq|
159         SELECT budget_parent_id FROM
160             aqbudgets where budget_id = ? | );
161     while (1) {
162         $sth->execute($parent_id_tmp);
163         my $res = $sth->fetchrow_hashref;
164         if ( $res->{'budget_parent_id'} == $budget_id ) {
165             return 1;
166         }
167         if ( not defined $res->{'budget_parent_id'} ) {
168             return 0;
169         }
170         $parent_id_tmp = $res->{'budget_parent_id'};
171     }
172 }
173
174 # -------------------------------------------------------------------
175 sub BudgetHasChildren {
176     my ( $budget_id  ) = @_;
177     my $dbh = C4::Context->dbh;
178     my $sth = $dbh->prepare(qq|
179        SELECT count(*) as sum FROM  aqbudgets
180         WHERE budget_parent_id = ?   | );
181     $sth->execute( $budget_id );
182     my $sum = $sth->fetchrow_hashref;
183     return $sum->{'sum'};
184 }
185
186 sub GetBudgetChildren {
187     my ( $budget_id ) = @_;
188     my $dbh = C4::Context->dbh;
189     return $dbh->selectall_arrayref(q|
190        SELECT  * FROM  aqbudgets
191         WHERE budget_parent_id = ?
192     |, { Slice => {} }, $budget_id );
193 }
194
195 sub SetOwnerToFundHierarchy {
196     my ( $budget_id, $borrowernumber ) = @_;
197
198     my $budget = GetBudget( $budget_id );
199     $budget->{budget_owner_id} = $borrowernumber;
200     ModBudget( $budget );
201     my $children = GetBudgetChildren( $budget_id );
202     for my $child ( @$children ) {
203         SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber );
204     }
205 }
206
207 # -------------------------------------------------------------------
208 sub GetBudgetsPlanCell {
209     my ( $cell, $period, $budget ) = @_;
210     my ($actual, $sth);
211     my $dbh = C4::Context->dbh;
212     if ( $cell->{'authcat'} eq 'MONTHS' ) {
213         # get the actual amount
214         $sth = $dbh->prepare( qq|
215
216             SELECT SUM(ecost_tax_included) AS actual FROM aqorders
217                 WHERE    budget_id = ? AND
218                 entrydate like "$cell->{'authvalue'}%"  |
219         );
220         $sth->execute( $cell->{'budget_id'} );
221     } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
222         # get the actual amount
223         $sth = $dbh->prepare( qq|
224
225             SELECT SUM(ecost_tax_included) FROM aqorders
226                 LEFT JOIN aqorders_items
227                 ON (aqorders.ordernumber = aqorders_items.ordernumber)
228                 LEFT JOIN items
229                 ON (aqorders_items.itemnumber = items.itemnumber)
230                 WHERE budget_id = ? AND homebranch = ? |          );
231
232         $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} );
233     } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) {
234         # get the actual amount
235         $sth = $dbh->prepare(  qq|
236
237             SELECT SUM( ecost_tax_included *  quantity) AS actual
238                 FROM aqorders JOIN biblioitems
239                 ON (biblioitems.biblionumber = aqorders.biblionumber )
240                 WHERE aqorders.budget_id = ? and itemtype  = ? |
241         );
242         $sth->execute(  $cell->{'budget_id'},
243                         $cell->{'authvalue'} );
244     }
245     # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT.
246     else {
247         # get the actual amount
248         $sth = $dbh->prepare( qq|
249
250         SELECT  SUM(ecost_tax_included * quantity) AS actual
251             FROM aqorders
252             JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
253             WHERE  aqorders.budget_id = ? AND
254                 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
255                 (aqbudgets.sort2_authcat = ? AND sort2 =?))    |
256         );
257         $sth->execute(  $cell->{'budget_id'},
258                         $budget->{'sort1_authcat'},
259                         $cell->{'authvalue'},
260                         $budget->{'sort2_authcat'},
261                         $cell->{'authvalue'}
262         );
263     }
264     $actual = $sth->fetchrow_array;
265
266     # get the estimated amount
267     $sth = $dbh->prepare( qq|
268
269         SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
270             WHERE budget_period_id = ? AND
271                 budget_id = ? AND
272                 authvalue = ? AND
273                 authcat = ?         |
274     );
275     $sth->execute(  $cell->{'budget_period_id'},
276                     $cell->{'budget_id'},
277                     $cell->{'authvalue'},
278                     $cell->{'authcat'},
279     );
280
281
282     my $res  = $sth->fetchrow_hashref;
283   #  my $display = $res->{'display'};
284     my $estimated = $res->{'estimated'};
285
286
287     return $actual, $estimated;
288 }
289
290 # -------------------------------------------------------------------
291 sub ModBudgetPlan {
292     my ( $budget_plan, $budget_period_id, $authcat ) = @_;
293     my $dbh = C4::Context->dbh;
294     foreach my $buds (@$budget_plan) {
295         my $lines = $buds->{lines};
296         my $sth = $dbh->prepare( qq|
297                 DELETE FROM aqbudgets_planning
298                     WHERE   budget_period_id   = ? AND
299                             budget_id   = ? AND
300                             authcat            = ? |
301         );
302     #delete a aqplan line of cells, then insert new cells, 
303     # these could be UPDATES rather than DEL/INSERTS...
304         $sth->execute( $budget_period_id,  $lines->[0]{budget_id}   , $authcat );
305
306         foreach my $cell (@$lines) {
307             my $sth = $dbh->prepare( qq|
308
309                 INSERT INTO aqbudgets_planning
310                      SET   budget_id     = ?,
311                      budget_period_id  = ?,
312                      authcat          = ?,
313                      estimated_amount  = ?,
314                      authvalue       = ?  |
315             );
316             $sth->execute(
317                             $cell->{'budget_id'},
318                             $cell->{'budget_period_id'},
319                             $cell->{'authcat'},
320                             $cell->{'estimated_amount'},
321                             $cell->{'authvalue'},
322             );
323         }
324     }
325 }
326
327 # -------------------------------------------------------------------
328 sub GetBudgetSpent {
329     my ($budget_id) = @_;
330     my $dbh = C4::Context->dbh;
331     # unitprice_tax_included should always been set here
332     # we should not need to retrieve ecost_tax_included
333     my $sth = $dbh->prepare(qq|
334         SELECT SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS sum FROM aqorders
335             WHERE budget_id = ? AND
336             quantityreceived > 0 AND
337             datecancellationprinted IS NULL
338     |);
339         $sth->execute($budget_id);
340         my $sum =  $sth->fetchrow_array;
341
342     $sth = $dbh->prepare(qq|
343         SELECT SUM(shipmentcost) AS sum
344         FROM aqinvoices
345         WHERE shipmentcost_budgetid = ?
346     |);
347
348     $sth->execute($budget_id);
349     my ($shipmentcost_sum) = $sth->fetchrow_array;
350     $sum += $shipmentcost_sum;
351
352         return $sum;
353 }
354
355 # -------------------------------------------------------------------
356 sub GetBudgetOrdered {
357         my ($budget_id) = @_;
358         my $dbh = C4::Context->dbh;
359         my $sth = $dbh->prepare(qq|
360         SELECT SUM(ecost_tax_included *  quantity) AS sum FROM aqorders
361             WHERE budget_id = ? AND
362             quantityreceived = 0 AND
363             datecancellationprinted IS NULL
364     |);
365         $sth->execute($budget_id);
366         my $sum =  $sth->fetchrow_array;
367
368         return $sum;
369 }
370
371 =head2 GetBudgetName
372
373   my $budget_name = &GetBudgetName($budget_id);
374
375 get the budget_name for a given budget_id
376
377 =cut
378
379 sub GetBudgetName {
380     my ( $budget_id ) = @_;
381     my $dbh         = C4::Context->dbh;
382     my $sth         = $dbh->prepare(
383         qq|
384         SELECT budget_name
385         FROM aqbudgets
386         WHERE budget_id = ?
387     |);
388
389     $sth->execute($budget_id);
390     return $sth->fetchrow_array;
391 }
392
393 =head2 GetBudgetAuthCats
394
395   my $auth_cats = &GetBudgetAuthCats($budget_period_id);
396
397 Return the list of authcat for a given budget_period_id
398
399 =cut
400
401 sub GetBudgetAuthCats  {
402     my ($budget_period_id) = shift;
403     # now, populate the auth_cats_loop used in the budget planning button
404     # we must retrieve all auth values used by at least one budget
405     my $dbh = C4::Context->dbh;
406     my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?");
407     $sth->execute($budget_period_id);
408     my %authcats;
409     while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
410         $authcats{$sort1_authcat}=1 if $sort1_authcat;
411         $authcats{$sort2_authcat}=1 if $sort2_authcat;
412     }
413     return [ sort keys %authcats ];
414 }
415
416 # -------------------------------------------------------------------
417 sub GetBudgetPeriods {
418         my ($filters,$orderby) = @_;
419
420     my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
421     $rs = $rs->search( $filters, { order_by => $orderby } );
422     $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
423     return [ $rs->all ];
424 }
425 # -------------------------------------------------------------------
426 sub GetBudgetPeriod {
427         my ($budget_period_id) = @_;
428         my $dbh = C4::Context->dbh;
429         ## $total = number of records linked to the record that must be deleted
430         my $total = 0;
431         ## get information about the record that will be deleted
432         my $sth;
433         if ($budget_period_id) {
434                 $sth = $dbh->prepare( qq|
435               SELECT      *
436                 FROM aqbudgetperiods
437                 WHERE budget_period_id=? |
438                 );
439                 $sth->execute($budget_period_id);
440         } else {         # ACTIVE BUDGET
441                 $sth = $dbh->prepare(qq|
442                           SELECT      *
443                 FROM aqbudgetperiods
444                 WHERE budget_period_active=1 |
445                 );
446                 $sth->execute();
447         }
448         my $data = $sth->fetchrow_hashref;
449         return $data;
450 }
451
452 sub DelBudgetPeriod{
453         my ($budget_period_id) = @_;
454         my $dbh = C4::Context->dbh;
455           ; ## $total = number of records linked to the record that must be deleted
456     my $total = 0;
457
458         ## get information about the record that will be deleted
459         my $sth = $dbh->prepare(qq|
460                 DELETE 
461          FROM aqbudgetperiods
462          WHERE budget_period_id=? |
463         );
464         return $sth->execute($budget_period_id);
465 }
466
467 # -------------------------------------------------------------------
468 sub ModBudgetPeriod {
469     my ($budget_period) = @_;
470     my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
471     return unless($result);
472
473     $result = $result->update($budget_period);
474     return $result->in_storage;
475 }
476
477 # -------------------------------------------------------------------
478 sub GetBudgetHierarchy {
479     my ( $budget_period_id, $branchcode, $owner ) = @_;
480     my @bind_params;
481     my $dbh   = C4::Context->dbh;
482     my $query = qq|
483                     SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
484                            b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
485                     FROM aqbudgets 
486                     LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
487                     JOIN aqbudgetperiods USING (budget_period_id)|;
488
489         my @where_strings;
490     # show only period X if requested
491     if ($budget_period_id) {
492         push @where_strings," aqbudgets.budget_period_id = ?";
493         push @bind_params, $budget_period_id;
494     }
495         # show only budgets owned by me, my branch or everyone
496     if ($owner) {
497         if ($branchcode) {
498             push @where_strings,
499             qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))};
500             push @bind_params, ( $owner, $branchcode );
501         } else {
502             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
503             push @bind_params, $owner;
504         }
505     } else {
506         if ($branchcode) {
507             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
508             push @bind_params, $branchcode;
509         }
510     }
511         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
512         $debug && warn $query,join(",",@bind_params);
513         my $sth = $dbh->prepare($query);
514         $sth->execute(@bind_params);
515
516     my %links;
517     # create hash with budget_id has key
518     while ( my $data = $sth->fetchrow_hashref ) {
519         $links{ $data->{'budget_id'} } = $data;
520     }
521
522     # link child to parent
523     my @first_parents;
524     foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
525         my $child = $links{$budget->{budget_id}};
526         if ( $child->{'budget_parent_id'} ) {
527             my $parent = $links{ $child->{'budget_parent_id'} };
528             if ($parent) {
529                 unless ( $parent->{'children'} ) {
530                     # init child arrayref
531                     $parent->{'children'} = [];
532                 }
533                 # add as child
534                 push @{ $parent->{'children'} }, $child;
535             }
536         } else {
537             push @first_parents, $child;
538         }
539     }
540
541     my @sort = ();
542     foreach my $first_parent (@first_parents) {
543         _add_budget_children(\@sort, $first_parent, 0);
544     }
545
546     # Get all the budgets totals in as few queries as possible
547     my $hr_budget_spent = $dbh->selectall_hashref(qq|
548         SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
549                SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS budget_spent
550         FROM aqorders JOIN aqbudgets USING (budget_id)
551         WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
552         GROUP BY budget_id
553         |, 'budget_id');
554     my $hr_budget_ordered = $dbh->selectall_hashref(qq|
555         SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
556                SUM(ecost_tax_included *  quantity) AS budget_ordered
557         FROM aqorders JOIN aqbudgets USING (budget_id)
558         WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
559         GROUP BY budget_id
560         |, 'budget_id');
561     my $hr_budget_spent_shipment = $dbh->selectall_hashref(qq|
562         SELECT shipmentcost_budgetid as budget_id,
563                SUM(shipmentcost) as shipmentcost
564         FROM aqinvoices
565         WHERE closedate IS NOT NULL
566         GROUP BY shipmentcost_budgetid
567         |, 'budget_id');
568     my $hr_budget_ordered_shipment = $dbh->selectall_hashref(qq|
569         SELECT shipmentcost_budgetid as budget_id,
570                SUM(shipmentcost) as shipmentcost
571         FROM aqinvoices
572         WHERE closedate IS NULL
573         GROUP BY shipmentcost_budgetid
574         |, 'budget_id');
575
576     my $recursiveAdd;
577     $recursiveAdd = sub {
578         my ($budget, $parent) = @_;
579
580         foreach my $child (@{$budget->{children}}){
581             $recursiveAdd->($child, $budget);
582         }
583
584         $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
585         $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
586         $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
587         $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
588
589         $budget->{total_spent} += $budget->{budget_spent};
590         $budget->{total_ordered} += $budget->{budget_ordered};
591
592         if ($parent) {
593             $parent->{total_spent} += $budget->{total_spent};
594             $parent->{total_ordered} += $budget->{total_ordered};
595         }
596     };
597
598     foreach my $budget (@sort) {
599         if ($budget->{budget_parent_id} == undef) {
600             $recursiveAdd->($budget);
601         }
602     }
603
604     return \@sort;
605 }
606
607 # Recursive method to add a budget and its chidren to an array
608 sub _add_budget_children {
609     my $res = shift;
610     my $budget = shift;
611     $budget->{budget_level} = shift;
612     push @$res, $budget;
613     my $children = $budget->{'children'} || [];
614     return unless @$children; # break recursivity
615     foreach my $child (@$children) {
616         _add_budget_children($res, $child, $budget->{budget_level} + 1);
617     }
618 }
619
620 # -------------------------------------------------------------------
621
622 sub AddBudget {
623     my ($budget) = @_;
624     return unless ($budget);
625
626     my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
627     return $resultset->create($budget)->id;
628 }
629
630 # -------------------------------------------------------------------
631 sub ModBudget {
632     my ($budget) = @_;
633     my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
634     return unless($result);
635
636     $result = $result->update($budget);
637     return $result->in_storage;
638 }
639
640 # -------------------------------------------------------------------
641 sub DelBudget {
642         my ($budget_id) = @_;
643         my $dbh         = C4::Context->dbh;
644         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
645         my $rc          = $sth->execute($budget_id);
646         return $rc;
647 }
648
649
650 # -------------------------------------------------------------------
651
652 =head2 GetBudget
653
654   &GetBudget($budget_id);
655
656 get a specific budget
657
658 =cut
659
660 sub GetBudget {
661     my ( $budget_id ) = @_;
662     my $dbh = C4::Context->dbh;
663     my $query = "
664         SELECT *
665         FROM   aqbudgets
666         WHERE  budget_id=?
667         ";
668     my $sth = $dbh->prepare($query);
669     $sth->execute( $budget_id );
670     my $result = $sth->fetchrow_hashref;
671     return $result;
672 }
673
674 # -------------------------------------------------------------------
675
676 =head2 GetBudgetByOrderNumber
677
678   &GetBudgetByOrderNumber($ordernumber);
679
680 get a specific budget by order number
681
682 =cut
683
684 sub GetBudgetByOrderNumber {
685     my ( $ordernumber ) = @_;
686     my $dbh = C4::Context->dbh;
687     my $query = "
688         SELECT aqbudgets.*
689         FROM   aqbudgets, aqorders
690         WHERE  ordernumber=?
691         AND    aqorders.budget_id = aqbudgets.budget_id
692         ";
693     my $sth = $dbh->prepare($query);
694     $sth->execute( $ordernumber );
695     my $result = $sth->fetchrow_hashref;
696     return $result;
697 }
698
699 =head2 GetBudgetReport
700
701   &GetBudgetReport( [$budget_id] );
702
703 Get all orders for a specific budget, without cancelled orders.
704
705 Returns an array of hashrefs.
706
707 =cut
708
709 # --------------------------------------------------------------------
710 sub GetBudgetReport {
711     my ( $budget_id ) = @_;
712     my $dbh = C4::Context->dbh;
713     my $query = '
714         SELECT o.*, b.budget_name
715         FROM   aqbudgets b
716         INNER JOIN aqorders o
717         ON b.budget_id = o.budget_id
718         WHERE  b.budget_id=?
719         AND (o.orderstatus != "cancelled")
720         ORDER BY b.budget_name';
721
722     my $sth = $dbh->prepare($query);
723     $sth->execute( $budget_id );
724
725     my @results = ();
726     while ( my $data = $sth->fetchrow_hashref ) {
727         push( @results, $data );
728     }
729     return @results;
730 }
731
732 =head2 GetBudgetsByActivity
733
734   &GetBudgetsByActivity( $budget_period_active );
735
736 Get all active or inactive budgets, depending of the value
737 of the parameter.
738
739 1 = active
740 0 = inactive
741
742 =cut
743
744 # --------------------------------------------------------------------
745 sub GetBudgetsByActivity {
746     my ( $budget_period_active ) = @_;
747     my $dbh = C4::Context->dbh;
748     my $query = "
749         SELECT DISTINCT b.*
750         FROM   aqbudgetperiods bp
751         INNER JOIN aqbudgets b
752         ON bp.budget_period_id = b.budget_period_id
753         WHERE  bp.budget_period_active=?
754         ";
755     my $sth = $dbh->prepare($query);
756     $sth->execute( $budget_period_active );
757     my @results = ();
758     while ( my $data = $sth->fetchrow_hashref ) {
759         push( @results, $data );
760     }
761     return @results;
762 }
763 # --------------------------------------------------------------------
764
765 =head2 GetBudgetsReport
766
767   &GetBudgetsReport( [$activity] );
768
769 Get all but cancelled orders for all funds.
770
771 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
772
773 active = 1
774 inactive = 0
775
776 Returns an array of hashrefs.
777
778 =cut
779
780 sub GetBudgetsReport {
781     my ($activity) = @_;
782     my $dbh = C4::Context->dbh;
783     my $query = '
784         SELECT o.*, b.budget_name
785         FROM   aqbudgetperiods bp
786         INNER JOIN aqbudgets b
787         ON bp.budget_period_id = b.budget_period_id
788         INNER JOIN aqorders o
789         ON b.budget_id = o.budget_id ';
790     if($activity ne ''){
791         $query .= 'WHERE  bp.budget_period_active=? ';
792     }
793     $query .= 'AND (o.orderstatus != "cancelled")
794                ORDER BY b.budget_name';
795
796     my $sth = $dbh->prepare($query);
797     if($activity ne ''){
798         $sth->execute($activity);
799     }
800     else{
801         $sth->execute;
802     }
803     my @results = ();
804     while ( my $data = $sth->fetchrow_hashref ) {
805         push( @results, $data );
806     }
807     return @results;
808 }
809
810 =head2 GetBudgetByCode
811
812     my $budget = &GetBudgetByCode($budget_code);
813
814 Retrieve all aqbudgets fields as a hashref for the budget that has
815 given budget_code
816
817 =cut
818
819 sub GetBudgetByCode {
820     my ( $budget_code ) = @_;
821
822     my $dbh = C4::Context->dbh;
823     my $query = qq{
824         SELECT aqbudgets.*
825         FROM aqbudgets
826         JOIN aqbudgetperiods USING (budget_period_id)
827         WHERE budget_code = ?
828         ORDER BY budget_period_active DESC, budget_id DESC
829         LIMIT 1
830     };
831     my $sth = $dbh->prepare( $query );
832     $sth->execute( $budget_code );
833     return $sth->fetchrow_hashref;
834 }
835
836 =head2 GetBudgetHierarchySpent
837
838   my $spent = GetBudgetHierarchySpent( $budget_id );
839
840 Gets the total spent of the level and sublevels of $budget_id
841
842 =cut
843
844 sub GetBudgetHierarchySpent {
845     my ( $budget_id ) = @_;
846     my $dbh = C4::Context->dbh;
847     my $children_ids = $dbh->selectcol_arrayref(q|
848         SELECT budget_id
849         FROM   aqbudgets
850         WHERE  budget_parent_id = ?
851     |, {}, $budget_id );
852
853     my $total_spent = GetBudgetSpent( $budget_id );
854     for my $child_id ( @$children_ids ) {
855         $total_spent += GetBudgetHierarchySpent( $child_id );
856     }
857     return $total_spent;
858 }
859
860 =head2 GetBudgetHierarchyOrdered
861
862   my $ordered = GetBudgetHierarchyOrdered( $budget_id );
863
864 Gets the total ordered of the level and sublevels of $budget_id
865
866 =cut
867
868 sub GetBudgetHierarchyOrdered {
869     my ( $budget_id ) = @_;
870     my $dbh = C4::Context->dbh;
871     my $children_ids = $dbh->selectcol_arrayref(q|
872         SELECT budget_id
873         FROM   aqbudgets
874         WHERE  budget_parent_id = ?
875     |, {}, $budget_id );
876
877     my $total_ordered = GetBudgetOrdered( $budget_id );
878     for my $child_id ( @$children_ids ) {
879         $total_ordered += GetBudgetHierarchyOrdered( $child_id );
880     }
881     return $total_ordered;
882 }
883
884 =head2 GetBudgets
885
886   &GetBudgets($filter, $order_by);
887
888 gets all budgets
889
890 =cut
891
892 # -------------------------------------------------------------------
893 sub GetBudgets {
894     my ($filters, $orderby) = @_;
895     $orderby = 'budget_name' unless($orderby);
896
897     my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
898     $rs = $rs->search( $filters, { order_by => $orderby } );
899     $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
900     return [ $rs->all  ];
901 }
902
903 =head2 GetBudgetUsers
904
905     my @borrowernumbers = &GetBudgetUsers($budget_id);
906
907 Return the list of borrowernumbers linked to a budget
908
909 =cut
910
911 sub GetBudgetUsers {
912     my ($budget_id) = @_;
913
914     my $dbh = C4::Context->dbh;
915     my $query = qq{
916         SELECT borrowernumber
917         FROM aqbudgetborrowers
918         WHERE budget_id = ?
919     };
920     my $sth = $dbh->prepare($query);
921     $sth->execute($budget_id);
922
923     my @borrowernumbers;
924     while (my ($borrowernumber) = $sth->fetchrow_array) {
925         push @borrowernumbers, $borrowernumber
926     }
927
928     return @borrowernumbers;
929 }
930
931 =head2 ModBudgetUsers
932
933     &ModBudgetUsers($budget_id, @borrowernumbers);
934
935 Modify the list of borrowernumbers linked to a budget
936
937 =cut
938
939 sub ModBudgetUsers {
940     my ($budget_id, @budget_users_id) = @_;
941
942     return unless $budget_id;
943
944     my $dbh = C4::Context->dbh;
945     my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
946     my $sth = $dbh->prepare($query);
947     $sth->execute($budget_id);
948
949     $query = qq{
950         INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
951         VALUES (?,?)
952     };
953     $sth = $dbh->prepare($query);
954     foreach my $borrowernumber (@budget_users_id) {
955         next unless $borrowernumber;
956         $sth->execute($budget_id, $borrowernumber);
957     }
958 }
959
960 sub CanUserUseBudget {
961     my ($borrower, $budget, $userflags) = @_;
962
963     if (not ref $borrower) {
964         $borrower = Koha::Patrons->find( $borrower );
965         return 0 unless $borrower;
966         $borrower = $borrower->unblessed;
967     }
968     if (not ref $budget) {
969         $budget = GetBudget($budget);
970     }
971
972     return 0 unless ($borrower and $budget);
973
974     if (not defined $userflags) {
975         $userflags = C4::Auth::getuserflags($borrower->{flags},
976             $borrower->{userid});
977     }
978
979     unless ($userflags->{superlibrarian}
980     || (ref $userflags->{acquisition}
981         && $userflags->{acquisition}->{budget_manage_all})
982     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
983     {
984         if (not exists $userflags->{acquisition}) {
985             return 0;
986         }
987
988         if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
989             return 0;
990         }
991
992         # Budget restricted to owner
993         if ( $budget->{budget_permission} == 1 ) {
994             if (    $budget->{budget_owner_id}
995                 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
996             {
997                 return 0;
998             }
999         }
1000
1001         # Budget restricted to owner, users and library
1002         elsif ( $budget->{budget_permission} == 2 ) {
1003             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1004
1005             if (
1006                 (
1007                         $budget->{budget_owner_id}
1008                     and $budget->{budget_owner_id} !=
1009                     $borrower->{borrowernumber}
1010                     or not $budget->{budget_owner_id}
1011                 )
1012                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1013                     @budget_users )
1014                 and defined $budget->{budget_branchcode}
1015                 and $budget->{budget_branchcode} ne
1016                 C4::Context->userenv->{branch}
1017               )
1018             {
1019                 return 0;
1020             }
1021         }
1022
1023         # Budget restricted to owner and users
1024         elsif ( $budget->{budget_permission} == 3 ) {
1025             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
1026             if (
1027                 (
1028                         $budget->{budget_owner_id}
1029                     and $budget->{budget_owner_id} !=
1030                     $borrower->{borrowernumber}
1031                     or not $budget->{budget_owner_id}
1032                 )
1033                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
1034                     @budget_users )
1035               )
1036             {
1037                 return 0;
1038             }
1039         }
1040     }
1041
1042     return 1;
1043 }
1044
1045 sub CanUserModifyBudget {
1046     my ($borrower, $budget, $userflags) = @_;
1047
1048     if (not ref $borrower) {
1049         $borrower = Koha::Patrons->find( $borrower );
1050         return 0 unless $borrower;
1051         $borrower = $borrower->unblessed;
1052     }
1053     if (not ref $budget) {
1054         $budget = GetBudget($budget);
1055     }
1056
1057     return 0 unless ($borrower and $budget);
1058
1059     if (not defined $userflags) {
1060         $userflags = C4::Auth::getuserflags($borrower->{flags},
1061             $borrower->{userid});
1062     }
1063
1064     unless ($userflags->{superlibrarian}
1065     || (ref $userflags->{acquisition}
1066         && $userflags->{acquisition}->{budget_manage_all})
1067     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1068     {
1069         if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1070             return 0;
1071         }
1072
1073         if (ref $userflags->{acquisition}
1074         && !$userflags->{acquisition}->{budget_modify}) {
1075             return 0;
1076         }
1077     }
1078
1079     return 1;
1080 }
1081
1082 sub _round {
1083     my ($value, $increment) = @_;
1084
1085     if ($increment && $increment != 0) {
1086         $value = int($value / $increment) * $increment;
1087     }
1088
1089     return $value;
1090 }
1091
1092 =head2 CloneBudgetPeriod
1093
1094   my $new_budget_period_id = CloneBudgetPeriod({
1095     budget_period_id => $budget_period_id,
1096     budget_period_startdate => $budget_period_startdate,
1097     budget_period_enddate   => $budget_period_enddate,
1098     mark_original_budget_as_inactive => 1n
1099     reset_all_budgets => 1,
1100   });
1101
1102 Clone a budget period with all budgets.
1103 If the mark_origin_budget_as_inactive is set (0 by default),
1104 the original budget will be marked as inactive.
1105
1106 If the reset_all_budgets is set (0 by default), all budget (fund)
1107 amounts will be reset.
1108
1109 =cut
1110
1111 sub CloneBudgetPeriod {
1112     my ($params)                  = @_;
1113     my $budget_period_id          = $params->{budget_period_id};
1114     my $budget_period_startdate   = $params->{budget_period_startdate};
1115     my $budget_period_enddate     = $params->{budget_period_enddate};
1116     my $budget_period_description = $params->{budget_period_description};
1117     my $amount_change_percentage  = $params->{amount_change_percentage};
1118     my $amount_change_round_increment = $params->{amount_change_round_increment};
1119     my $mark_original_budget_as_inactive =
1120       $params->{mark_original_budget_as_inactive} || 0;
1121     my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1122
1123     my $budget_period = GetBudgetPeriod($budget_period_id);
1124
1125     $budget_period->{budget_period_startdate}   = $budget_period_startdate;
1126     $budget_period->{budget_period_enddate}     = $budget_period_enddate;
1127     $budget_period->{budget_period_description} = $budget_period_description;
1128     # The new budget (budget_period) should be active by default
1129     $budget_period->{budget_period_active}    = 1;
1130
1131     if ($amount_change_percentage) {
1132         my $total = $budget_period->{budget_period_total};
1133         $total += $total * $amount_change_percentage / 100;
1134         $total = _round($total, $amount_change_round_increment);
1135         $budget_period->{budget_period_total} = $total;
1136     }
1137
1138     my $original_budget_period_id = $budget_period->{budget_period_id};
1139     delete $budget_period->{budget_period_id};
1140     my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1141
1142     my $budgets = GetBudgetHierarchy($budget_period_id);
1143     CloneBudgetHierarchy(
1144         {
1145             budgets              => $budgets,
1146             new_budget_period_id => $new_budget_period_id
1147         }
1148     );
1149
1150     if ($mark_original_budget_as_inactive) {
1151         ModBudgetPeriod(
1152             {
1153                 budget_period_id     => $budget_period_id,
1154                 budget_period_active => 0,
1155             }
1156         );
1157     }
1158
1159     if ( $reset_all_budgets ) {
1160         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1161         for my $budget ( @$budgets ) {
1162             $budget->{budget_amount} = 0;
1163             ModBudget( $budget );
1164         }
1165     } elsif ($amount_change_percentage) {
1166         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1167         for my $budget ( @$budgets ) {
1168             my $amount = $budget->{budget_amount};
1169             $amount += $amount * $amount_change_percentage / 100;
1170             $amount = _round($amount, $amount_change_round_increment);
1171             $budget->{budget_amount} = $amount;
1172             ModBudget( $budget );
1173         }
1174     }
1175
1176     return $new_budget_period_id;
1177 }
1178
1179 =head2 CloneBudgetHierarchy
1180
1181   CloneBudgetHierarchy({
1182     budgets => $budgets,
1183     new_budget_period_id => $new_budget_period_id;
1184   });
1185
1186 Clone a budget hierarchy.
1187
1188 =cut
1189
1190 sub CloneBudgetHierarchy {
1191     my ($params)             = @_;
1192     my $budgets              = $params->{budgets};
1193     my $new_budget_period_id = $params->{new_budget_period_id};
1194     next unless @$budgets or $new_budget_period_id;
1195
1196     my $children_of   = $params->{children_of};
1197     my $new_parent_id = $params->{new_parent_id};
1198
1199     my @first_level_budgets =
1200       ( not defined $children_of )
1201       ? map { ( not $_->{budget_parent_id} )             ? $_ : () } @$budgets
1202       : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1203
1204     # get only the columns of aqbudgets
1205     my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1206
1207     for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1208         @first_level_budgets )
1209     {
1210
1211         my $tidy_budget =
1212           { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1213               keys %$budget };
1214         my $new_budget_id = AddBudget(
1215             {
1216                 %$tidy_budget,
1217                 budget_id        => undef,
1218                 budget_parent_id => $new_parent_id,
1219                 budget_period_id => $new_budget_period_id
1220             }
1221         );
1222         CloneBudgetHierarchy(
1223             {
1224                 budgets              => $budgets,
1225                 new_budget_period_id => $new_budget_period_id,
1226                 children_of          => $budget->{budget_id},
1227                 new_parent_id        => $new_budget_id
1228             }
1229         );
1230     }
1231 }
1232
1233 =head2 MoveOrders
1234
1235   my $report = MoveOrders({
1236     from_budget_period_id => $from_budget_period_id,
1237     to_budget_period_id   => $to_budget_period_id,
1238   });
1239
1240 Move orders from one budget period to another.
1241
1242 =cut
1243
1244 sub MoveOrders {
1245     my ($params)              = @_;
1246     my $from_budget_period_id = $params->{from_budget_period_id};
1247     my $to_budget_period_id   = $params->{to_budget_period_id};
1248     my $move_remaining_unspent = $params->{move_remaining_unspent};
1249     return
1250       if not $from_budget_period_id
1251           or not $to_budget_period_id
1252           or $from_budget_period_id == $to_budget_period_id;
1253
1254     # Can't move orders to an inactive budget (budgetperiod)
1255     my $budget_period = GetBudgetPeriod($to_budget_period_id);
1256     return unless $budget_period->{budget_period_active};
1257
1258     my @report;
1259     my $dbh     = C4::Context->dbh;
1260     my $sth_update_aqorders = $dbh->prepare(
1261         q|
1262             UPDATE aqorders
1263             SET budget_id = ?
1264             WHERE ordernumber = ?
1265         |
1266     );
1267     my $sth_update_budget_amount = $dbh->prepare(
1268         q|
1269             UPDATE aqbudgets
1270             SET budget_amount = ?
1271             WHERE budget_id = ?
1272         |
1273     );
1274     my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1275     for my $from_budget (@$from_budgets) {
1276         my $new_budget_id = $dbh->selectcol_arrayref(
1277             q|
1278                 SELECT budget_id
1279                 FROM aqbudgets
1280                 WHERE budget_period_id = ?
1281                     AND budget_code = ?
1282             |, {}, $to_budget_period_id, $from_budget->{budget_code}
1283         );
1284         $new_budget_id = $new_budget_id->[0];
1285         my $new_budget = GetBudget( $new_budget_id );
1286         unless ( $new_budget ) {
1287             push @report,
1288               {
1289                 moved       => 0,
1290                 budget      => $from_budget,
1291                 error       => 'budget_code_not_exists',
1292               };
1293             next;
1294         }
1295         my $orders_to_move = C4::Acquisition::SearchOrders(
1296             {
1297                 budget_id => $from_budget->{budget_id},
1298                 pending   => 1,
1299             }
1300         );
1301
1302         my @orders_moved;
1303         for my $order (@$orders_to_move) {
1304             $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1305             push @orders_moved, $order;
1306         }
1307
1308         my $unspent_moved = 0;
1309         if ($move_remaining_unspent) {
1310             my $spent   = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1311             my $unspent = $from_budget->{budget_amount} - $spent;
1312             my $new_budget_amount = $new_budget->{budget_amount};
1313             if ( $unspent > 0 ) {
1314                 $new_budget_amount += $unspent;
1315                 $unspent_moved = $unspent;
1316             }
1317             $new_budget->{budget_amount} = $new_budget_amount;
1318             $sth_update_budget_amount->execute( $new_budget_amount,
1319                 $new_budget->{budget_id} );
1320         }
1321
1322         push @report,
1323           {
1324             budget        => $new_budget,
1325             orders_moved  => \@orders_moved,
1326             moved         => 1,
1327             unspent_moved => $unspent_moved,
1328           };
1329     }
1330     return \@report;
1331 }
1332
1333 END { }    # module clean-up code here (global destructor)
1334
1335 1;
1336 __END__
1337
1338 =head1 AUTHOR
1339
1340 Koha Development Team <http://koha-community.org/>
1341
1342 =cut