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