Bug 18999: Modified SQL query in GetBudgetSpent() in C4/Budgets.pm
[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                     FROM aqbudgets 
485                     JOIN aqbudgetperiods USING (budget_period_id)|;
486                         
487         my @where_strings;
488     # show only period X if requested
489     if ($budget_period_id) {
490         push @where_strings," aqbudgets.budget_period_id = ?";
491         push @bind_params, $budget_period_id;
492     }
493         # show only budgets owned by me, my branch or everyone
494     if ($owner) {
495         if ($branchcode) {
496             push @where_strings,
497             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="")))};
498             push @bind_params, ( $owner, $branchcode );
499         } else {
500             push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
501             push @bind_params, $owner;
502         }
503     } else {
504         if ($branchcode) {
505             push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
506             push @bind_params, $branchcode;
507         }
508     }
509         $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
510         $debug && warn $query,join(",",@bind_params);
511         my $sth = $dbh->prepare($query);
512         $sth->execute(@bind_params);
513
514     my %links;
515     # create hash with budget_id has key
516     while ( my $data = $sth->fetchrow_hashref ) {
517         $links{ $data->{'budget_id'} } = $data;
518     }
519
520     # link child to parent
521     my @first_parents;
522     foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) {
523         my $child = $links{$budget->{budget_id}};
524         if ( $child->{'budget_parent_id'} ) {
525             my $parent = $links{ $child->{'budget_parent_id'} };
526             if ($parent) {
527                 unless ( $parent->{'children'} ) {
528                     # init child arrayref
529                     $parent->{'children'} = [];
530                 }
531                 # add as child
532                 push @{ $parent->{'children'} }, $child;
533             }
534         } else {
535             push @first_parents, $child;
536         }
537     }
538
539     my @sort = ();
540     foreach my $first_parent (@first_parents) {
541         _add_budget_children(\@sort, $first_parent, 0);
542     }
543
544     foreach my $budget (@sort) {
545         $budget->{budget_spent}   = GetBudgetSpent( $budget->{budget_id} );
546         $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
547         $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
548         $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
549     }
550     return \@sort;
551 }
552
553 # Recursive method to add a budget and its chidren to an array
554 sub _add_budget_children {
555     my $res = shift;
556     my $budget = shift;
557     $budget->{budget_level} = shift;
558     push @$res, $budget;
559     my $children = $budget->{'children'} || [];
560     return unless @$children; # break recursivity
561     foreach my $child (@$children) {
562         _add_budget_children($res, $child, $budget->{budget_level} + 1);
563     }
564 }
565
566 # -------------------------------------------------------------------
567
568 sub AddBudget {
569     my ($budget) = @_;
570     return unless ($budget);
571
572     my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
573     return $resultset->create($budget)->id;
574 }
575
576 # -------------------------------------------------------------------
577 sub ModBudget {
578     my ($budget) = @_;
579     my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
580     return unless($result);
581
582     $result = $result->update($budget);
583     return $result->in_storage;
584 }
585
586 # -------------------------------------------------------------------
587 sub DelBudget {
588         my ($budget_id) = @_;
589         my $dbh         = C4::Context->dbh;
590         my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
591         my $rc          = $sth->execute($budget_id);
592         return $rc;
593 }
594
595
596 # -------------------------------------------------------------------
597
598 =head2 GetBudget
599
600   &GetBudget($budget_id);
601
602 get a specific budget
603
604 =cut
605
606 sub GetBudget {
607     my ( $budget_id ) = @_;
608     my $dbh = C4::Context->dbh;
609     my $query = "
610         SELECT *
611         FROM   aqbudgets
612         WHERE  budget_id=?
613         ";
614     my $sth = $dbh->prepare($query);
615     $sth->execute( $budget_id );
616     my $result = $sth->fetchrow_hashref;
617     return $result;
618 }
619
620 # -------------------------------------------------------------------
621
622 =head2 GetBudgetByOrderNumber
623
624   &GetBudgetByOrderNumber($ordernumber);
625
626 get a specific budget by order number
627
628 =cut
629
630 sub GetBudgetByOrderNumber {
631     my ( $ordernumber ) = @_;
632     my $dbh = C4::Context->dbh;
633     my $query = "
634         SELECT aqbudgets.*
635         FROM   aqbudgets, aqorders
636         WHERE  ordernumber=?
637         AND    aqorders.budget_id = aqbudgets.budget_id
638         ";
639     my $sth = $dbh->prepare($query);
640     $sth->execute( $ordernumber );
641     my $result = $sth->fetchrow_hashref;
642     return $result;
643 }
644
645 =head2 GetBudgetReport
646
647   &GetBudgetReport( [$budget_id] );
648
649 Get all orders for a specific budget, without cancelled orders.
650
651 Returns an array of hashrefs.
652
653 =cut
654
655 # --------------------------------------------------------------------
656 sub GetBudgetReport {
657     my ( $budget_id ) = @_;
658     my $dbh = C4::Context->dbh;
659     my $query = '
660         SELECT o.*, b.budget_name
661         FROM   aqbudgets b
662         INNER JOIN aqorders o
663         ON b.budget_id = o.budget_id
664         WHERE  b.budget_id=?
665         AND (o.orderstatus != "cancelled")
666         ORDER BY b.budget_name';
667
668     my $sth = $dbh->prepare($query);
669     $sth->execute( $budget_id );
670
671     my @results = ();
672     while ( my $data = $sth->fetchrow_hashref ) {
673         push( @results, $data );
674     }
675     return @results;
676 }
677
678 =head2 GetBudgetsByActivity
679
680   &GetBudgetsByActivity( $budget_period_active );
681
682 Get all active or inactive budgets, depending of the value
683 of the parameter.
684
685 1 = active
686 0 = inactive
687
688 =cut
689
690 # --------------------------------------------------------------------
691 sub GetBudgetsByActivity {
692     my ( $budget_period_active ) = @_;
693     my $dbh = C4::Context->dbh;
694     my $query = "
695         SELECT DISTINCT b.*
696         FROM   aqbudgetperiods bp
697         INNER JOIN aqbudgets b
698         ON bp.budget_period_id = b.budget_period_id
699         WHERE  bp.budget_period_active=?
700         ";
701     my $sth = $dbh->prepare($query);
702     $sth->execute( $budget_period_active );
703     my @results = ();
704     while ( my $data = $sth->fetchrow_hashref ) {
705         push( @results, $data );
706     }
707     return @results;
708 }
709 # --------------------------------------------------------------------
710
711 =head2 GetBudgetsReport
712
713   &GetBudgetsReport( [$activity] );
714
715 Get all but cancelled orders for all funds.
716
717 If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
718
719 active = 1
720 inactive = 0
721
722 Returns an array of hashrefs.
723
724 =cut
725
726 sub GetBudgetsReport {
727     my ($activity) = @_;
728     my $dbh = C4::Context->dbh;
729     my $query = '
730         SELECT o.*, b.budget_name
731         FROM   aqbudgetperiods bp
732         INNER JOIN aqbudgets b
733         ON bp.budget_period_id = b.budget_period_id
734         INNER JOIN aqorders o
735         ON b.budget_id = o.budget_id ';
736     if($activity ne ''){
737         $query .= 'WHERE  bp.budget_period_active=? ';
738     }
739     $query .= 'AND (o.orderstatus != "cancelled")
740                ORDER BY b.budget_name';
741
742     my $sth = $dbh->prepare($query);
743     if($activity ne ''){
744         $sth->execute($activity);
745     }
746     else{
747         $sth->execute;
748     }
749     my @results = ();
750     while ( my $data = $sth->fetchrow_hashref ) {
751         push( @results, $data );
752     }
753     return @results;
754 }
755
756 =head2 GetBudgetByCode
757
758     my $budget = &GetBudgetByCode($budget_code);
759
760 Retrieve all aqbudgets fields as a hashref for the budget that has
761 given budget_code
762
763 =cut
764
765 sub GetBudgetByCode {
766     my ( $budget_code ) = @_;
767
768     my $dbh = C4::Context->dbh;
769     my $query = qq{
770         SELECT aqbudgets.*
771         FROM aqbudgets
772         JOIN aqbudgetperiods USING (budget_period_id)
773         WHERE budget_code = ?
774         ORDER BY budget_period_active DESC, budget_id DESC
775         LIMIT 1
776     };
777     my $sth = $dbh->prepare( $query );
778     $sth->execute( $budget_code );
779     return $sth->fetchrow_hashref;
780 }
781
782 =head2 GetBudgetHierarchySpent
783
784   my $spent = GetBudgetHierarchySpent( $budget_id );
785
786 Gets the total spent of the level and sublevels of $budget_id
787
788 =cut
789
790 sub GetBudgetHierarchySpent {
791     my ( $budget_id ) = @_;
792     my $dbh = C4::Context->dbh;
793     my $children_ids = $dbh->selectcol_arrayref(q|
794         SELECT budget_id
795         FROM   aqbudgets
796         WHERE  budget_parent_id = ?
797     |, {}, $budget_id );
798
799     my $total_spent = GetBudgetSpent( $budget_id );
800     for my $child_id ( @$children_ids ) {
801         $total_spent += GetBudgetHierarchySpent( $child_id );
802     }
803     return $total_spent;
804 }
805
806 =head2 GetBudgetHierarchyOrdered
807
808   my $ordered = GetBudgetHierarchyOrdered( $budget_id );
809
810 Gets the total ordered of the level and sublevels of $budget_id
811
812 =cut
813
814 sub GetBudgetHierarchyOrdered {
815     my ( $budget_id ) = @_;
816     my $dbh = C4::Context->dbh;
817     my $children_ids = $dbh->selectcol_arrayref(q|
818         SELECT budget_id
819         FROM   aqbudgets
820         WHERE  budget_parent_id = ?
821     |, {}, $budget_id );
822
823     my $total_ordered = GetBudgetOrdered( $budget_id );
824     for my $child_id ( @$children_ids ) {
825         $total_ordered += GetBudgetHierarchyOrdered( $child_id );
826     }
827     return $total_ordered;
828 }
829
830 =head2 GetBudgets
831
832   &GetBudgets($filter, $order_by);
833
834 gets all budgets
835
836 =cut
837
838 # -------------------------------------------------------------------
839 sub GetBudgets {
840     my ($filters, $orderby) = @_;
841     $orderby = 'budget_name' unless($orderby);
842
843     my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
844     $rs = $rs->search( $filters, { order_by => $orderby } );
845     $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
846     return [ $rs->all  ];
847 }
848
849 =head2 GetBudgetUsers
850
851     my @borrowernumbers = &GetBudgetUsers($budget_id);
852
853 Return the list of borrowernumbers linked to a budget
854
855 =cut
856
857 sub GetBudgetUsers {
858     my ($budget_id) = @_;
859
860     my $dbh = C4::Context->dbh;
861     my $query = qq{
862         SELECT borrowernumber
863         FROM aqbudgetborrowers
864         WHERE budget_id = ?
865     };
866     my $sth = $dbh->prepare($query);
867     $sth->execute($budget_id);
868
869     my @borrowernumbers;
870     while (my ($borrowernumber) = $sth->fetchrow_array) {
871         push @borrowernumbers, $borrowernumber
872     }
873
874     return @borrowernumbers;
875 }
876
877 =head2 ModBudgetUsers
878
879     &ModBudgetUsers($budget_id, @borrowernumbers);
880
881 Modify the list of borrowernumbers linked to a budget
882
883 =cut
884
885 sub ModBudgetUsers {
886     my ($budget_id, @budget_users_id) = @_;
887
888     return unless $budget_id;
889
890     my $dbh = C4::Context->dbh;
891     my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
892     my $sth = $dbh->prepare($query);
893     $sth->execute($budget_id);
894
895     $query = qq{
896         INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
897         VALUES (?,?)
898     };
899     $sth = $dbh->prepare($query);
900     foreach my $borrowernumber (@budget_users_id) {
901         next unless $borrowernumber;
902         $sth->execute($budget_id, $borrowernumber);
903     }
904 }
905
906 sub CanUserUseBudget {
907     my ($borrower, $budget, $userflags) = @_;
908
909     if (not ref $borrower) {
910         $borrower = Koha::Patrons->find( $borrower );
911         return 0 unless $borrower;
912         $borrower = $borrower->unblessed;
913     }
914     if (not ref $budget) {
915         $budget = GetBudget($budget);
916     }
917
918     return 0 unless ($borrower and $budget);
919
920     if (not defined $userflags) {
921         $userflags = C4::Auth::getuserflags($borrower->{flags},
922             $borrower->{userid});
923     }
924
925     unless ($userflags->{superlibrarian}
926     || (ref $userflags->{acquisition}
927         && $userflags->{acquisition}->{budget_manage_all})
928     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
929     {
930         if (not exists $userflags->{acquisition}) {
931             return 0;
932         }
933
934         if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
935             return 0;
936         }
937
938         # Budget restricted to owner
939         if ( $budget->{budget_permission} == 1 ) {
940             if (    $budget->{budget_owner_id}
941                 and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
942             {
943                 return 0;
944             }
945         }
946
947         # Budget restricted to owner, users and library
948         elsif ( $budget->{budget_permission} == 2 ) {
949             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
950
951             if (
952                 (
953                         $budget->{budget_owner_id}
954                     and $budget->{budget_owner_id} !=
955                     $borrower->{borrowernumber}
956                     or not $budget->{budget_owner_id}
957                 )
958                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
959                     @budget_users )
960                 and defined $budget->{budget_branchcode}
961                 and $budget->{budget_branchcode} ne
962                 C4::Context->userenv->{branch}
963               )
964             {
965                 return 0;
966             }
967         }
968
969         # Budget restricted to owner and users
970         elsif ( $budget->{budget_permission} == 3 ) {
971             my @budget_users = GetBudgetUsers( $budget->{budget_id} );
972             if (
973                 (
974                         $budget->{budget_owner_id}
975                     and $budget->{budget_owner_id} !=
976                     $borrower->{borrowernumber}
977                     or not $budget->{budget_owner_id}
978                 )
979                 and ( 0 == grep { $borrower->{borrowernumber} == $_ }
980                     @budget_users )
981               )
982             {
983                 return 0;
984             }
985         }
986     }
987
988     return 1;
989 }
990
991 sub CanUserModifyBudget {
992     my ($borrower, $budget, $userflags) = @_;
993
994     if (not ref $borrower) {
995         $borrower = Koha::Patrons->find( $borrower );
996         return 0 unless $borrower;
997         $borrower = $borrower->unblessed;
998     }
999     if (not ref $budget) {
1000         $budget = GetBudget($budget);
1001     }
1002
1003     return 0 unless ($borrower and $budget);
1004
1005     if (not defined $userflags) {
1006         $userflags = C4::Auth::getuserflags($borrower->{flags},
1007             $borrower->{userid});
1008     }
1009
1010     unless ($userflags->{superlibrarian}
1011     || (ref $userflags->{acquisition}
1012         && $userflags->{acquisition}->{budget_manage_all})
1013     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
1014     {
1015         if (!CanUserUseBudget($borrower, $budget, $userflags)) {
1016             return 0;
1017         }
1018
1019         if (ref $userflags->{acquisition}
1020         && !$userflags->{acquisition}->{budget_modify}) {
1021             return 0;
1022         }
1023     }
1024
1025     return 1;
1026 }
1027
1028 sub _round {
1029     my ($value, $increment) = @_;
1030
1031     if ($increment && $increment != 0) {
1032         $value = int($value / $increment) * $increment;
1033     }
1034
1035     return $value;
1036 }
1037
1038 =head2 CloneBudgetPeriod
1039
1040   my $new_budget_period_id = CloneBudgetPeriod({
1041     budget_period_id => $budget_period_id,
1042     budget_period_startdate => $budget_period_startdate,
1043     budget_period_enddate   => $budget_period_enddate,
1044     mark_original_budget_as_inactive => 1n
1045     reset_all_budgets => 1,
1046   });
1047
1048 Clone a budget period with all budgets.
1049 If the mark_origin_budget_as_inactive is set (0 by default),
1050 the original budget will be marked as inactive.
1051
1052 If the reset_all_budgets is set (0 by default), all budget (fund)
1053 amounts will be reset.
1054
1055 =cut
1056
1057 sub CloneBudgetPeriod {
1058     my ($params)                  = @_;
1059     my $budget_period_id          = $params->{budget_period_id};
1060     my $budget_period_startdate   = $params->{budget_period_startdate};
1061     my $budget_period_enddate     = $params->{budget_period_enddate};
1062     my $budget_period_description = $params->{budget_period_description};
1063     my $amount_change_percentage  = $params->{amount_change_percentage};
1064     my $amount_change_round_increment = $params->{amount_change_round_increment};
1065     my $mark_original_budget_as_inactive =
1066       $params->{mark_original_budget_as_inactive} || 0;
1067     my $reset_all_budgets = $params->{reset_all_budgets} || 0;
1068
1069     my $budget_period = GetBudgetPeriod($budget_period_id);
1070
1071     $budget_period->{budget_period_startdate}   = $budget_period_startdate;
1072     $budget_period->{budget_period_enddate}     = $budget_period_enddate;
1073     $budget_period->{budget_period_description} = $budget_period_description;
1074     # The new budget (budget_period) should be active by default
1075     $budget_period->{budget_period_active}    = 1;
1076
1077     if ($amount_change_percentage) {
1078         my $total = $budget_period->{budget_period_total};
1079         $total += $total * $amount_change_percentage / 100;
1080         $total = _round($total, $amount_change_round_increment);
1081         $budget_period->{budget_period_total} = $total;
1082     }
1083
1084     my $original_budget_period_id = $budget_period->{budget_period_id};
1085     delete $budget_period->{budget_period_id};
1086     my $new_budget_period_id = AddBudgetPeriod( $budget_period );
1087
1088     my $budgets = GetBudgetHierarchy($budget_period_id);
1089     CloneBudgetHierarchy(
1090         {
1091             budgets              => $budgets,
1092             new_budget_period_id => $new_budget_period_id
1093         }
1094     );
1095
1096     if ($mark_original_budget_as_inactive) {
1097         ModBudgetPeriod(
1098             {
1099                 budget_period_id     => $budget_period_id,
1100                 budget_period_active => 0,
1101             }
1102         );
1103     }
1104
1105     if ( $reset_all_budgets ) {
1106         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1107         for my $budget ( @$budgets ) {
1108             $budget->{budget_amount} = 0;
1109             ModBudget( $budget );
1110         }
1111     } elsif ($amount_change_percentage) {
1112         my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
1113         for my $budget ( @$budgets ) {
1114             my $amount = $budget->{budget_amount};
1115             $amount += $amount * $amount_change_percentage / 100;
1116             $amount = _round($amount, $amount_change_round_increment);
1117             $budget->{budget_amount} = $amount;
1118             ModBudget( $budget );
1119         }
1120     }
1121
1122     return $new_budget_period_id;
1123 }
1124
1125 =head2 CloneBudgetHierarchy
1126
1127   CloneBudgetHierarchy({
1128     budgets => $budgets,
1129     new_budget_period_id => $new_budget_period_id;
1130   });
1131
1132 Clone a budget hierarchy.
1133
1134 =cut
1135
1136 sub CloneBudgetHierarchy {
1137     my ($params)             = @_;
1138     my $budgets              = $params->{budgets};
1139     my $new_budget_period_id = $params->{new_budget_period_id};
1140     next unless @$budgets or $new_budget_period_id;
1141
1142     my $children_of   = $params->{children_of};
1143     my $new_parent_id = $params->{new_parent_id};
1144
1145     my @first_level_budgets =
1146       ( not defined $children_of )
1147       ? map { ( not $_->{budget_parent_id} )             ? $_ : () } @$budgets
1148       : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
1149
1150     # get only the columns of aqbudgets
1151     my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
1152
1153     for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
1154         @first_level_budgets )
1155     {
1156
1157         my $tidy_budget =
1158           { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
1159               keys %$budget };
1160         my $new_budget_id = AddBudget(
1161             {
1162                 %$tidy_budget,
1163                 budget_id        => undef,
1164                 budget_parent_id => $new_parent_id,
1165                 budget_period_id => $new_budget_period_id
1166             }
1167         );
1168         CloneBudgetHierarchy(
1169             {
1170                 budgets              => $budgets,
1171                 new_budget_period_id => $new_budget_period_id,
1172                 children_of          => $budget->{budget_id},
1173                 new_parent_id        => $new_budget_id
1174             }
1175         );
1176     }
1177 }
1178
1179 =head2 MoveOrders
1180
1181   my $report = MoveOrders({
1182     from_budget_period_id => $from_budget_period_id,
1183     to_budget_period_id   => $to_budget_period_id,
1184   });
1185
1186 Move orders from one budget period to another.
1187
1188 =cut
1189
1190 sub MoveOrders {
1191     my ($params)              = @_;
1192     my $from_budget_period_id = $params->{from_budget_period_id};
1193     my $to_budget_period_id   = $params->{to_budget_period_id};
1194     my $move_remaining_unspent = $params->{move_remaining_unspent};
1195     return
1196       if not $from_budget_period_id
1197           or not $to_budget_period_id
1198           or $from_budget_period_id == $to_budget_period_id;
1199
1200     # Can't move orders to an inactive budget (budgetperiod)
1201     my $budget_period = GetBudgetPeriod($to_budget_period_id);
1202     return unless $budget_period->{budget_period_active};
1203
1204     my @report;
1205     my $dbh     = C4::Context->dbh;
1206     my $sth_update_aqorders = $dbh->prepare(
1207         q|
1208             UPDATE aqorders
1209             SET budget_id = ?
1210             WHERE ordernumber = ?
1211         |
1212     );
1213     my $sth_update_budget_amount = $dbh->prepare(
1214         q|
1215             UPDATE aqbudgets
1216             SET budget_amount = ?
1217             WHERE budget_id = ?
1218         |
1219     );
1220     my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
1221     for my $from_budget (@$from_budgets) {
1222         my $new_budget_id = $dbh->selectcol_arrayref(
1223             q|
1224                 SELECT budget_id
1225                 FROM aqbudgets
1226                 WHERE budget_period_id = ?
1227                     AND budget_code = ?
1228             |, {}, $to_budget_period_id, $from_budget->{budget_code}
1229         );
1230         $new_budget_id = $new_budget_id->[0];
1231         my $new_budget = GetBudget( $new_budget_id );
1232         unless ( $new_budget ) {
1233             push @report,
1234               {
1235                 moved       => 0,
1236                 budget      => $from_budget,
1237                 error       => 'budget_code_not_exists',
1238               };
1239             next;
1240         }
1241         my $orders_to_move = C4::Acquisition::SearchOrders(
1242             {
1243                 budget_id => $from_budget->{budget_id},
1244                 pending   => 1,
1245             }
1246         );
1247
1248         my @orders_moved;
1249         for my $order (@$orders_to_move) {
1250             $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
1251             push @orders_moved, $order;
1252         }
1253
1254         my $unspent_moved = 0;
1255         if ($move_remaining_unspent) {
1256             my $spent   = GetBudgetHierarchySpent( $from_budget->{budget_id} );
1257             my $unspent = $from_budget->{budget_amount} - $spent;
1258             my $new_budget_amount = $new_budget->{budget_amount};
1259             if ( $unspent > 0 ) {
1260                 $new_budget_amount += $unspent;
1261                 $unspent_moved = $unspent;
1262             }
1263             $new_budget->{budget_amount} = $new_budget_amount;
1264             $sth_update_budget_amount->execute( $new_budget_amount,
1265                 $new_budget->{budget_id} );
1266         }
1267
1268         push @report,
1269           {
1270             budget        => $new_budget,
1271             orders_moved  => \@orders_moved,
1272             moved         => 1,
1273             unspent_moved => $unspent_moved,
1274           };
1275     }
1276     return \@report;
1277 }
1278
1279 END { }    # module clean-up code here (global destructor)
1280
1281 1;
1282 __END__
1283
1284 =head1 AUTHOR
1285
1286 Koha Development Team <http://koha-community.org/>
1287
1288 =cut