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