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