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