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