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