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