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