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