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