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