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