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