Bug 19575: Rebase and fix tests
[koha.git] / t / db_dependent / Budgets.t
1 #!/usr/bin/perl
2 use Modern::Perl;
3 use Test::More tests => 146;
4
5 BEGIN {
6     use_ok('C4::Budgets')
7 }
8 use C4::Context;
9 use C4::Biblio;
10 use C4::Acquisition;
11
12 use Koha::Acquisition::Booksellers;
13 use Koha::Acquisition::Orders;
14 use Koha::Acquisition::Funds;
15 use Koha::Patrons;
16
17 use t::lib::TestBuilder;
18 use t::lib::Mocks;
19 use Koha::DateUtils;
20
21 use YAML;
22
23 my $schema  = Koha::Database->new->schema;
24 $schema->storage->txn_begin;
25 my $builder = t::lib::TestBuilder->new;
26 my $dbh = C4::Context->dbh;
27 $dbh->do(q|DELETE FROM aqbudgetperiods|);
28 $dbh->do(q|DELETE FROM aqbudgets|);
29
30 my $library = $builder->build({
31     source => 'Branch',
32 });
33
34 t::lib::Mocks::mock_userenv(
35     {
36         flags => 1,
37         userid => 'my_userid',
38         branch => $library->{branchcode},
39     }
40 );
41
42 #
43 # Budget Periods :
44 #
45
46 is( AddBudgetPeriod(), undef, 'AddBugetPeriod without argument returns undef' );
47 is( AddBudgetPeriod( { }  ), undef, 'AddBugetPeriod with an empty argument returns undef' );
48 my $bpid = AddBudgetPeriod({
49     budget_period_startdate => '2008-01-01',
50 });
51 is( $bpid, undef, 'AddBugetPeriod without end date returns undef' );
52 $bpid = AddBudgetPeriod({
53     budget_period_enddate => '2008-12-31',
54 });
55 is( $bpid, undef, 'AddBugetPeriod without start date returns undef' );
56 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
57 my $budgetperiods = GetBudgetPeriods();
58 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
59
60 my $my_budgetperiod = {
61     budget_period_startdate   => '2008-01-01',
62     budget_period_enddate     => '2008-12-31',
63     budget_period_description => 'MAPERI',
64     budget_period_active      => 0,
65     budget_period_id          => '', # Bug 21604
66 };
67 $bpid = AddBudgetPeriod($my_budgetperiod);
68 isnt( $bpid, undef, 'AddBugetPeriod does not returns undef' );
69 my $budgetperiod = GetBudgetPeriod($bpid);
70 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'AddBudgetPeriod stores the start date correctly' );
71 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'AddBudgetPeriod stores the end date correctly' );
72 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'AddBudgetPeriod stores the description correctly' );
73 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'AddBudgetPeriod stores active correctly' );
74 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
75
76
77 $my_budgetperiod = {
78     budget_period_startdate   => '2009-01-01',
79     budget_period_enddate     => '2009-12-31',
80     budget_period_description => 'MODIF_MAPERI',
81     budget_period_active      => 1,
82 };
83 my $mod_status = ModBudgetPeriod($my_budgetperiod);
84 is( $mod_status, undef, 'ModBudgetPeriod without id returns undef' );
85
86 $my_budgetperiod->{budget_period_id} = $bpid;
87 $mod_status = ModBudgetPeriod($my_budgetperiod);
88 is( $mod_status, 1, 'ModBudgetPeriod returnis true' );
89 $budgetperiod = GetBudgetPeriod($bpid);
90 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'ModBudgetPeriod updates the start date correctly' );
91 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'ModBudgetPeriod updates the end date correctly' );
92 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'ModBudgetPeriod updates the description correctly' );
93 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'ModBudgetPeriod upates active correctly' );
94 isnt( GetBudgetPeriod(0), undef, 'GetBugetPeriods functions correctly' );
95
96
97 $budgetperiods = GetBudgetPeriods();
98 is( @$budgetperiods, 1, 'GetBudgetPeriods returns the correct number of budget periods' );
99 is( $budgetperiods->[0]->{budget_period_id}, $my_budgetperiod->{budget_period_id}, 'GetBudgetPeriods returns the id correctly' );
100 is( $budgetperiods->[0]->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'GetBudgetPeriods returns the start date correctly' );
101 is( $budgetperiods->[0]->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'GetBudgetPeriods returns the end date correctly' );
102 is( $budgetperiods->[0]->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'GetBudgetPeriods returns the description correctly' );
103 is( $budgetperiods->[0]->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'GetBudgetPeriods returns active correctly' );
104
105 is( DelBudgetPeriod($bpid), 1, 'DelBudgetPeriod returns true' );
106 $budgetperiods = GetBudgetPeriods();
107 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
108
109
110 #
111 # Budget  :
112 #
113
114 # The budget hierarchy will be:
115 # budget_1
116 #   budget_11
117 #     budget_111
118 #   budget_12
119 # budget_2
120 #   budget_21
121
122 is( AddBudget(), undef, 'AddBuget without argument returns undef' );
123 my $budgets = GetBudgets();
124 is( @$budgets, 0, 'GetBudgets returns the correct number of budgets' );
125
126 $bpid = AddBudgetPeriod($my_budgetperiod); #this is an active budget
127
128 my $my_budget = {
129     budget_code      => 'ABCD',
130     budget_amount    => '123.132000',
131     budget_name      => 'Periodiques',
132     budget_notes     => 'This is a note',
133     budget_period_id => $bpid,
134     budget_encumb    => '', # Bug 21604
135 };
136 my $budget_id = AddBudget($my_budget);
137 isnt( $budget_id, undef, 'AddBudget does not returns undef' );
138 my $budget = GetBudget($budget_id);
139 is( $budget->{budget_code}, $my_budget->{budget_code}, 'AddBudget stores the budget code correctly' );
140 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'AddBudget stores the budget amount correctly' );
141 is( $budget->{budget_name}, $my_budget->{budget_name}, 'AddBudget stores the budget name correctly' );
142 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'AddBudget stores the budget notes correctly' );
143 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'AddBudget stores the budget period id correctly' );
144
145
146 $my_budget = {
147     budget_code      => 'EFG',
148     budget_amount    => '321.231000',
149     budget_name      => 'Modified name',
150     budget_notes     => 'This is a modified note',
151     budget_period_id => $bpid,
152 };
153 $mod_status = ModBudget($my_budget);
154 is( $mod_status, undef, 'ModBudget without id returns undef' );
155
156 $my_budget->{budget_id} = $budget_id;
157 $mod_status = ModBudget($my_budget);
158 is( $mod_status, 1, 'ModBudget returns true' );
159 $budget = GetBudget($budget_id);
160 is( $budget->{budget_code}, $my_budget->{budget_code}, 'ModBudget updates the budget code correctly' );
161 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'ModBudget updates the budget amount correctly' );
162 is( $budget->{budget_name}, $my_budget->{budget_name}, 'ModBudget updates the budget name correctly' );
163 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'ModBudget updates the budget notes correctly' );
164 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'ModBudget updates the budget period id correctly' );
165
166
167 $budgets = GetBudgets();
168 is( @$budgets, 1, 'GetBudgets returns the correct number of budgets' );
169 is( $budgets->[0]->{budget_id}, $my_budget->{budget_id}, 'GetBudgets returns the budget id correctly' );
170 is( $budgets->[0]->{budget_code}, $my_budget->{budget_code}, 'GetBudgets returns the budget code correctly' );
171 is( $budgets->[0]->{budget_amount}, $my_budget->{budget_amount}, 'GetBudgets returns the budget amount correctly' );
172 is( $budgets->[0]->{budget_name}, $my_budget->{budget_name}, 'GetBudgets returns the budget name correctly' );
173 is( $budgets->[0]->{budget_notes}, $my_budget->{budget_notes}, 'GetBudgets returns the budget notes correctly' );
174 is( $budgets->[0]->{budget_period_id}, $my_budget->{budget_period_id}, 'GetBudgets returns the budget period id correctly' );
175
176 $budgets = GetBudgets( {budget_period_id => $bpid} );
177 is( @$budgets, 1, 'GetBudgets With Filter OK' );
178 $budgets = GetBudgets( {budget_period_id => $bpid}, {-asc => "budget_name"} );
179 is( @$budgets, 1, 'GetBudgets With Order OK' );
180 $budgets = GetBudgets( {budget_period_id => GetBudgetPeriod($bpid)->{budget_period_id}}, {-asc => "budget_name"} );
181 is( @$budgets, 1, 'GetBudgets With Order Getting Active budgetPeriod OK');
182
183
184 my $budget_name = GetBudgetName( $budget_id );
185 is($budget_name, $my_budget->{budget_name}, "Test the GetBudgetName routine");
186
187 my $my_inactive_budgetperiod = { #let's add an inactive
188     budget_period_startdate   => '2010-01-01',
189     budget_period_enddate     => '2010-12-31',
190     budget_period_description => 'MODIF_MAPERI',
191     budget_period_active      => 0,
192 };
193 my $bpid_i = AddBudgetPeriod($my_inactive_budgetperiod); #this is an inactive budget
194
195 my $my_budget_inactive = {
196     budget_code      => 'EFG',
197     budget_amount    => '123.132000',
198     budget_name      => 'Periodiques',
199     budget_notes     => 'This is a note',
200     budget_period_id => $bpid_i,
201 };
202 my $budget_id_inactive = AddBudget($my_budget_inactive);
203
204 my $budget_code = $my_budget->{budget_code};
205 my $budget_by_code = GetBudgetByCode( $budget_code );
206 is($budget_by_code->{budget_id}, $budget_id, "GetBudgetByCode, check id"); #this should match the active budget, not the inactive
207 is($budget_by_code->{budget_notes}, $my_budget->{budget_notes}, "GetBudgetByCode, check notes");
208
209 my $second_budget_id = AddBudget({
210     budget_code      => "ZZZZ",
211     budget_amount    => "500.00",
212     budget_name      => "Art",
213     budget_notes     => "This is a note",
214     budget_period_id => $bpid,
215 });
216 isnt( $second_budget_id, undef, 'AddBudget does not returns undef' );
217
218 $budgets = GetBudgets( {budget_period_id => $bpid} );
219 ok( $budgets->[0]->{budget_name} lt $budgets->[1]->{budget_name}, 'default sort order for GetBudgets is by name' );
220
221 is( DelBudget($budget_id), 1, 'DelBudget returns true' );
222 $budgets = GetBudgets();
223 is( @$budgets, 2, 'GetBudgets returns the correct number of budget periods' );
224
225
226 # GetBudgetHierarchySpent and GetBudgetHierarchyOrdered
227 my $budget_period_total = 10_000;
228 my $budget_1_total = 1_000;
229 my $budget_11_total = 100;
230 my $budget_111_total = 50;
231 my $budget_12_total = 100;
232 my $budget_2_total = 2_000;
233
234 my $budget_period_id = AddBudgetPeriod(
235     {
236         budget_period_startdate   => '2013-01-01',
237         budget_period_enddate     => '2014-12-31',
238         budget_period_description => 'Budget Period',
239         budget_period_active      => 1,
240         budget_period_total       => $budget_period_total,
241     }
242 );
243 my $budget_id1 = AddBudget(
244     {
245         budget_code      => 'budget_1',
246         budget_name      => 'budget_1',
247         budget_period_id => $budget_period_id,
248         budget_parent_id => undef,
249         budget_amount    => $budget_1_total,
250     }
251 );
252 my $budget_id2 = AddBudget(
253     {
254         budget_code      => 'budget_2',
255         budget_name      => 'budget_2',
256         budget_period_id => $budget_period_id,
257         budget_parent_id => undef,
258         budget_amount    => $budget_2_total,
259     }
260 );
261 my $budget_id12 = AddBudget(
262     {
263         budget_code      => 'budget_12',
264         budget_name      => 'budget_12',
265         budget_period_id => $budget_period_id,
266         budget_parent_id => $budget_id1,
267         budget_amount    => $budget_12_total,
268     }
269 );
270 my $budget_id11 = AddBudget(
271     {
272         budget_code      => 'budget_11',
273         budget_name      => 'budget_11',
274         budget_period_id => $budget_period_id,
275         budget_parent_id => $budget_id1,
276         budget_amount    => $budget_11_total,
277     }
278 );
279 my $budget_id111 = AddBudget(
280     {
281         budget_code      => 'budget_111',
282         budget_name      => 'budget_111',
283         budget_period_id => $budget_period_id,
284         budget_parent_id => $budget_id11,
285         budget_owner_id  => 1,
286         budget_amount    => $budget_111_total,
287     }
288 );
289 my $budget_id21 = AddBudget(
290     {
291         budget_code      => 'budget_21',
292         budget_name      => 'budget_21',
293         budget_period_id => $budget_period_id,
294         budget_parent_id => $budget_id2,
295     }
296 );
297
298 my $bookseller = Koha::Acquisition::Bookseller->new(
299     {
300         name         => "my vendor",
301         address1     => "bookseller's address",
302         phone        => "0123456",
303         active       => 1,
304         deliverytime => 5,
305     }
306 )->store;
307 my $booksellerid = $bookseller->id;
308
309 my $basketno = C4::Acquisition::NewBasket( $booksellerid, 1 );
310 my ( $biblionumber, $biblioitemnumber ) =
311   C4::Biblio::AddBiblio( MARC::Record->new, '' );
312
313 my @order_infos = (
314     {
315         budget_id => $budget_id1,
316         pending_quantity  => 1,
317         spent_quantity  => 0,
318     },
319     {
320         budget_id => $budget_id2,
321         pending_quantity  => 2,
322         spent_quantity  => 1,
323     },
324     {
325         budget_id => $budget_id11,
326         pending_quantity  => 3,
327         spent_quantity  => 4,
328     },
329     {
330         budget_id => $budget_id12,
331         pending_quantity  => 4,
332         spent_quantity  => 3,
333     },
334     {
335         budget_id => $budget_id111,
336         pending_quantity  => 2,
337         spent_quantity  => 1,
338     },
339
340     # No order for budget_21
341
342 );
343
344 my %budgets;
345 my $invoiceid = AddInvoice(invoicenumber => 'invoice_test_clone', booksellerid => $booksellerid, unknown => "unknown");
346 my $invoice = GetInvoice( $invoiceid );
347 my $item_price = 10;
348 my $item_quantity = 2;
349 my $number_of_orders_to_move = 0;
350 for my $infos (@order_infos) {
351     for ( 1 .. $infos->{pending_quantity} ) {
352         my $order = Koha::Acquisition::Order->new(
353             {
354                 basketno           => $basketno,
355                 biblionumber       => $biblionumber,
356                 budget_id          => $infos->{budget_id},
357                 order_internalnote => "internal note",
358                 order_vendornote   => "vendor note",
359                 quantity           => 2,
360                 cost_tax_included  => $item_price,
361                 rrp_tax_included   => $item_price,
362                 listprice          => $item_price,
363                 ecost_tax_include  => $item_price,
364                 discount           => 0,
365                 uncertainprice     => 0,
366             }
367         )->store;
368         my $ordernumber = $order->ordernumber;
369         push @{ $budgets{$infos->{budget_id}} }, $ordernumber;
370         $number_of_orders_to_move++;
371     }
372     for ( 1 .. $infos->{spent_quantity} ) {
373         my $order = Koha::Acquisition::Order->new(
374             {
375                 basketno           => $basketno,
376                 biblionumber       => $biblionumber,
377                 budget_id          => $infos->{budget_id},
378                 order_internalnote => "internal note",
379                 order_vendornote   => "vendor note",
380                 quantity           => $item_quantity,
381                 cost               => $item_price,
382                 rrp_tax_included   => $item_price,
383                 listprice          => $item_price,
384                 ecost_tax_included => $item_price,
385                 discount           => 0,
386                 uncertainprice     => 0,
387             }
388         )->store;
389         my $ordernumber = $order->ordernumber;
390         ModReceiveOrder({
391               biblionumber     => $biblionumber,
392               order            => $order->unblessed,
393               budget_id        => $infos->{budget_id},
394               quantityreceived => $item_quantity,
395               invoice          => $invoice,
396               received_items   => [],
397         } );
398     }
399 }
400 is( GetBudgetHierarchySpent( $budget_id1 ), 160, "total spent for budget1 is 160" );
401 is( GetBudgetHierarchySpent( $budget_id11 ), 100, "total spent for budget11 is 100" );
402 is( GetBudgetHierarchySpent( $budget_id111 ), 20, "total spent for budget111 is 20" );
403
404 # GetBudgetSpent and GetBudgetOrdered
405 my $budget_period_amount = 100;
406 my $budget_amount = 50;
407
408 $budget = AddBudgetPeriod(
409     {
410         budget_period_startdate   => '2017-08-22',
411         budget_period_enddate     => '2018-08-22',
412         budget_period_description => 'Test budget',
413         budget_period_active      => 1,
414         budget_period_total       => $budget_period_amount,
415     }
416 );
417
418 my $fund = AddBudget(
419     {
420         budget_code       => 'Test fund',
421         budget_name       => 'Test fund',
422         budget_period_id  => $budget,
423         budget_parent_id  => undef,
424         budget_amount     => $budget_amount,
425     }
426 );
427
428 my $vendor = Koha::Acquisition::Bookseller->new(
429     {
430         name         => "test vendor",
431         address1     => "test address",
432         phone        => "0123456",
433         active       => 1,
434         deliverytime => 5,
435     }
436 )->store;
437
438 my $vendorid = $vendor->id;
439
440 my $basketnumber = C4::Acquisition::NewBasket( $vendorid, 1 );
441 my ( $biblio, $biblioitem ) = C4::Biblio::AddBiblio( MARC::Record->new, '' );
442
443 my @orders = (
444     {
445         budget_id  => $fund,
446         pending_quantity => 1,
447         spent_quantity => 0,
448     },
449 );
450
451 my $invoiceident = AddInvoice( invoicenumber => 'invoice_test_clone', booksellerid => $vendorid, shipmentdate => '2017-08-22', shipmentcost => 6, shipmentcost_budgetid => $fund );
452 my $test_invoice = GetInvoice( $invoiceident );
453 my $individual_item_price = 10;
454
455 my $order = Koha::Acquisition::Order->new(
456    {
457       basketno           => $basketnumber,
458       biblionumber       => $biblio,
459       budget_id          => $fund,
460       order_internalnote => "internalnote",
461       order_vendornote   => "vendor note",
462       quantity           => 2,
463       cost_tax_included  => $individual_item_price,
464       rrp_tax_included   => $individual_item_price,
465       listprice          => $individual_item_price,
466       ecost_tax_included => $individual_item_price,
467       discount           => 0,
468       uncertainprice     => 0,
469    }
470 )->store;
471
472 ModReceiveOrder({
473    bibionumber       => $biblio,
474    order             => $order->unblessed,
475    budget_id         => $fund,
476    quantityreceived  => 2,
477    invoice           => $test_invoice,
478    received_items    => [],
479 } );
480
481 is ( GetBudgetSpent( $fund ), 6, "total shipping cost is 6");
482 is ( GetBudgetOrdered( $fund ), '20', "total ordered price is 20");
483
484
485 # CloneBudgetPeriod
486 # Let's make sure our timestamp is old
487 my @orig_funds = Koha::Acquisition::Funds->search({ budget_period_id => $budget_period_id });
488 foreach my $fund (@orig_funds){
489     $fund->timestamp('1999-12-31 23:59:59')->store;
490 }
491
492 my $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
493     {
494         budget_period_id        => $budget_period_id,
495         budget_period_startdate => '2014-01-01',
496         budget_period_enddate   => '2014-12-31',
497         budget_period_description => 'Budget Period Cloned',
498     }
499 );
500
501 my $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
502 is($budget_period_cloned->{budget_period_description}, 'Budget Period Cloned', 'Cloned budget\'s description is updated.');
503
504 my $budget_cloned = C4::Budgets::GetBudgets({ budget_period_id => $budget_period_id_cloned });
505 my $budget_time =  $budget_cloned->[0]->{timestamp};
506
507 isnt($budget_time, '1999-12-31 23:59:59', "New budget has an updated timestamp");
508
509
510
511 my $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
512 my $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
513
514 is(
515     scalar(@$budget_hierarchy_cloned),
516     scalar(@$budget_hierarchy),
517     'CloneBudgetPeriod clones the same number of budgets (funds)'
518 );
519 is_deeply(
520     _get_dependencies($budget_hierarchy),
521     _get_dependencies($budget_hierarchy_cloned),
522     'CloneBudgetPeriod keeps the same dependencies order'
523 );
524
525 # CloneBudgetPeriod with param mark_original_budget_as_inactive
526 my $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
527 is( $budget_period->{budget_period_active}, 1,
528     'CloneBudgetPeriod does not mark as inactive the budgetperiod if not needed'
529 );
530
531 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
532 my $number_of_budgets_not_reset = 0;
533 for my $budget (@$budget_hierarchy_cloned) {
534     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
535 }
536 is( $number_of_budgets_not_reset, 5,
537     'CloneBudgetPeriod does not reset budgets (funds) if not needed' );
538
539 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
540     {
541         budget_period_id                 => $budget_period_id,
542         budget_period_startdate          => '2014-01-01',
543         budget_period_enddate            => '2014-12-31',
544         mark_original_budget_as_inactive => 1,
545     }
546 );
547
548 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
549 is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy should return budgets ordered by name, first child is budget_11' );
550 is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy should return budgets ordered by name, second child is budget_12' );
551 is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy should return budgets ordered by name, first budget is budget_1');
552 is($budget_hierarchy->[0]->{budget_level},'0','budget_level of budget (budget_1)  should be 0');
553 is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','budget_level of first fund(budget_11)  should be 1');
554 is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','budget_level of second fund(budget_12)  should be 1');
555 is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','budget_level of  child fund budget_11 should be 2');
556 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
557 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
558
559 is( scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy),
560 'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)'
561 );
562 is_deeply(
563     _get_dependencies($budget_hierarchy),
564     _get_dependencies($budget_hierarchy_cloned),
565     'CloneBudgetPeriod (with inactive param) keeps the same dependencies order'
566 );
567 $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
568 is( $budget_period->{budget_period_active}, 0,
569     'CloneBudgetPeriod (with inactive param) marks as inactive the budgetperiod'
570 );
571
572 # CloneBudgetPeriod with param reset_all_budgets
573 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
574     {
575         budget_period_id        => $budget_period_id,
576         budget_period_startdate => '2014-01-01',
577         budget_period_enddate   => '2014-12-31',
578         reset_all_budgets         => 1,
579     }
580 );
581
582 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
583 $number_of_budgets_not_reset = 0;
584 for my $budget (@$budget_hierarchy_cloned) {
585     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
586 }
587 is( $number_of_budgets_not_reset, 0,
588     'CloneBudgetPeriod has reset all budgets (funds)' );
589
590 #GetBudgetsByActivity
591 my $result=C4::Budgets::GetBudgetsByActivity(1);
592 isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 1');
593 $result=C4::Budgets::GetBudgetsByActivity(0);
594  isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 0');
595 $result=C4::Budgets::GetBudgetsByActivity();
596  is( $result, 0 , 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' );
597 DelBudget($budget_id);
598 DelBudgetPeriod($bpid);
599
600 # CloneBudgetPeriod with param amount_change_*
601 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
602     {
603         budget_period_id        => $budget_period_id,
604         budget_period_startdate => '2014-01-01',
605         budget_period_enddate   => '2014-12-31',
606         amount_change_percentage => 16,
607         amount_change_round_increment => 5,
608     }
609 );
610
611 $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
612 cmp_ok($budget_period_cloned->{budget_period_total}, '==', 11600, "CloneBudgetPeriod changed correctly budget amount");
613 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
614 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, "CloneBudgetPeriod changed correctly funds amounts");
615 cmp_ok($budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
616 cmp_ok($budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts");
617 cmp_ok($budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
618 cmp_ok($budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, "CloneBudgetPeriod changed correctly funds amounts");
619 cmp_ok($budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts");
620
621 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
622     {
623         budget_period_id        => $budget_period_id,
624         budget_period_startdate => '2014-01-01',
625         budget_period_enddate   => '2014-12-31',
626         amount_change_percentage => 16,
627         amount_change_round_increment => 5,
628         reset_all_budgets => 1,
629     }
630 );
631 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
632 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts");
633
634 # MoveOrders
635 my $number_orders_moved = C4::Budgets::MoveOrders();
636 is( $number_orders_moved, undef, 'MoveOrders return undef if no arg passed' );
637 $number_orders_moved =
638   C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } );
639 is( $number_orders_moved, undef,
640     'MoveOrders return undef if only 1 arg passed' );
641 $number_orders_moved =
642   C4::Budgets::MoveOrders( { to_budget_period_id => $budget_period_id } );
643 is( $number_orders_moved, undef,
644     'MoveOrders return undef if only 1 arg passed' );
645 $number_orders_moved = C4::Budgets::MoveOrders(
646     {
647         from_budget_period_id => $budget_period_id,
648         to_budget_period_id   => $budget_period_id
649     }
650 );
651 is( $number_orders_moved, undef,
652     'MoveOrders return undef if 2 budget period id are the same' );
653
654 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
655     {
656         budget_period_id        => $budget_period_id,
657         budget_period_startdate => '2014-01-01',
658         budget_period_enddate   => '2014-12-31',
659     }
660 );
661
662 my $report = C4::Budgets::MoveOrders(
663     {
664         from_budget_period_id  => $budget_period_id,
665         to_budget_period_id    => $budget_period_id_cloned,
666         move_remaining_unspent => 1,
667     }
668 );
669 is( scalar( @$report ), 6 , "MoveOrders has processed 6 funds" );
670
671 my $number_of_orders_moved = 0;
672 $number_of_orders_moved += scalar( @{ $_->{orders_moved} } ) for @$report;
673 is( $number_of_orders_moved, $number_of_orders_to_move, "MoveOrders has moved $number_of_orders_to_move orders" );
674
675 my @new_budget_ids = map { $_->{budget_id} }
676   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
677 my @old_budget_ids = map { $_->{budget_id} }
678   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
679 for my $budget_id ( keys %budgets ) {
680     for my $ordernumber ( @{ $budgets{$budget_id} } ) {
681         my $budget            = GetBudgetByOrderNumber($ordernumber);
682         my $is_in_new_budgets = grep /^$budget->{budget_id}$/, @new_budget_ids;
683         my $is_in_old_budgets = grep /^$budget->{budget_id}$/, @old_budget_ids;
684         is( $is_in_new_budgets, 1, "MoveOrders changed the budget_id for order $ordernumber" );
685         is( $is_in_old_budgets, 0, "MoveOrders changed the budget_id for order $ordernumber" );
686     }
687 }
688
689
690 # MoveOrders with param move_remaining_unspent
691 my @new_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
692 my @old_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
693
694 for my $new_budget ( @new_budgets ) {
695     my ( $old_budget ) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets;
696     my $new_budget_amount_should_be = $old_budget->{budget_amount} * 2 - $old_budget->{total_spent};
697     is( $new_budget->{budget_amount} + 0, $new_budget_amount_should_be, "MoveOrders updated the budget amount with the previous unspent budget (for budget $new_budget->{budget_code})" );
698 }
699
700 # Test SetOwnerToFundHierarchy
701
702 my $patron_category = $builder->build({ source => 'Category' });
703 my $branchcode = $library->{branchcode};
704 my $john_doe = Koha::Patron->new({
705     cardnumber   => '123456',
706     firstname    => 'John',
707     surname      => 'Doe',
708     categorycode => $patron_category->{categorycode},
709     branchcode   => $branchcode,
710     dateofbirth  => '',
711     dateexpiry   => '9999-12-31',
712     userid       => 'john.doe'
713 })->store->borrowernumber;
714
715 C4::Budgets::SetOwnerToFundHierarchy( $budget_id1, $john_doe );
716 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
717     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" );
718 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
719     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" );
720 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
721     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" );
722 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
723     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" );
724 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
725     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" );
726 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
727     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" );
728
729 my $jane_doe = Koha::Patron->new({
730     cardnumber   => '789012',
731     firstname    => 'Jane',
732     surname      => 'Doe',
733     categorycode => $patron_category->{categorycode},
734     branchcode   => $branchcode,
735     dateofbirth  => '',
736     dateexpiry   => '9999-12-31',
737     userid       => 'jane.doe'
738 })->store->borrowernumber;
739
740 C4::Budgets::SetOwnerToFundHierarchy( $budget_id11, $jane_doe );
741 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
742     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" );
743 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
744     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" );
745 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
746     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" );
747 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
748     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" );
749 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
750     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" );
751 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
752     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" );
753
754 # Test GetBudgetAuthCats
755
756 my $budgetPeriodId = AddBudgetPeriod({
757     budget_period_startdate   => '2008-01-01',
758     budget_period_enddate     => '2008-12-31',
759     budget_period_description => 'just another budget',
760     budget_period_active      => 0,
761 });
762
763 $budgets = GetBudgets();
764 my $i = 0;
765 for my $budget ( @$budgets )
766 {
767     $budget->{sort1_authcat} = "sort1_authcat_$i";
768     $budget->{sort2_authcat} = "sort2_authcat_$i";
769     $budget->{budget_period_id} = $budgetPeriodId;
770     ModBudget( $budget );
771     $i++;
772 }
773
774 my $authCat = GetBudgetAuthCats($budgetPeriodId);
775
776 is( scalar @{$authCat}, $i * 2, "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" );
777
778 $i = 0;
779 for my $budget ( @$budgets )
780 {
781     $budget->{sort1_authcat} = "sort_authcat_$i";
782     $budget->{sort2_authcat} = "sort_authcat_$i";
783     $budget->{budget_period_id} = $budgetPeriodId;
784     ModBudget( $budget );
785     $i++;
786 }
787
788 $authCat = GetBudgetAuthCats($budgetPeriodId);
789 is( scalar @$authCat, scalar @$budgets, "GetBudgetAuthCats returns distinct authCat" );
790
791 $i = 0;
792 for my $budget ( @$budgets )
793 {
794     $budget->{sort1_authcat} = "sort1_authcat_$i";
795     $budget->{sort2_authcat} = "";
796     $budget->{budget_period_id} = $budgetPeriodId;
797     ModBudget( $budget );
798     $i++;
799 }
800
801 $authCat = GetBudgetAuthCats($budgetPeriodId);
802
803 is( scalar @{$authCat}, $i, "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" );
804
805 $i = 0;
806 for my $budget ( @$budgets )
807 {
808     $budget->{sort1_authcat} = "";
809     $budget->{sort2_authcat} = "";
810     $budget->{budget_period_id} = $budgetPeriodId;
811     ModBudget( $budget );
812     $i++;
813 }
814
815 $authCat = GetBudgetAuthCats($budgetPeriodId);
816
817 is( scalar @{$authCat}, 0, "GetBudgetAuthCats returns only non-empty sorting categories (all empty)" );
818
819 # /Test GetBudgetAuthCats
820
821 subtest 'GetBudgetSpent and GetBudgetOrdered' => sub {
822     plan tests => 10;
823
824     my $budget = $builder->build({
825         source => 'Aqbudget',
826         value  => {
827             budget_amount => 1000,
828         }
829     });
830     my $invoice = $builder->build({
831         source => 'Aqinvoice',
832         value  => {
833             closedate => undef,
834         }
835     });
836
837     my $spent = GetBudgetSpent( $budget->{budget_id} );
838     my $ordered = GetBudgetOrdered( $budget->{budget_id} );
839
840     is( $spent, 0, "New budget, no orders/invoices, should be nothing spent");
841     is( $ordered, 0, "New budget, no orders/invoices, should be nothing ordered");
842
843     my $inv_adj_1 = $builder->build({
844         source => 'AqinvoiceAdjustment',
845         value  => {
846             invoiceid     => $invoice->{invoiceid},
847             adjustment    => 3,
848             encumber_open => 0,
849             budget_id     => $budget->{budget_id},
850         }
851     });
852
853     $spent = GetBudgetSpent( $budget->{budget_id} );
854     $ordered = GetBudgetOrdered( $budget->{budget_id} );
855     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
856     is( $ordered, 0, "After adding invoice adjustment on open invoice not encumbered, should be nothing ordered");
857
858     my $inv_adj_2 = $builder->build({
859         source => 'AqinvoiceAdjustment',
860         value  => {
861             invoiceid     => $invoice->{invoiceid},
862             adjustment    => 3,
863             encumber_open => 1,
864             budget_id     => $budget->{budget_id},
865         }
866     });
867
868     $spent = GetBudgetSpent( $budget->{budget_id} );
869     $ordered = GetBudgetOrdered( $budget->{budget_id} );
870     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
871     is( $ordered, 3, "After adding invoice adjustment on open invoice encumbered, should be 3 ordered");
872
873     my $invoice_2 = $builder->build({
874         source => 'Aqinvoice',
875         value  => {
876             closedate => '2017-07-01',
877         }
878     });
879     my $inv_adj_3 = $builder->build({
880         source => 'AqinvoiceAdjustment',
881         value  => {
882             invoiceid     => $invoice_2->{invoiceid},
883             adjustment    => 3,
884             encumber_open => 0,
885             budget_id     => $budget->{budget_id},
886         }
887     });
888     my $inv_adj_4 = $builder->build({
889         source => 'AqinvoiceAdjustment',
890         value  => {
891             invoiceid     => $invoice_2->{invoiceid},
892             adjustment    => 3,
893             encumber_open => 1,
894             budget_id     => $budget->{budget_id},
895         }
896     });
897
898     $spent = GetBudgetSpent( $budget->{budget_id} );
899     $ordered = GetBudgetOrdered( $budget->{budget_id} );
900     is( $spent, 6, "After adding invoice adjustment on closed invoice, should be 6 spent, encumber has no affect once closed");
901     is( $ordered, 3, "After adding invoice adjustment on closed invoice, should still be 3 ordered");
902
903     my $budget_2 = $builder->build({
904         source => 'Aqbudget',
905         value  => {
906             budget_amount => 1000,
907         }
908     });
909     my $inv_adj_5 = $builder->build({
910         source => 'AqinvoiceAdjustment',
911         value  => {
912             invoiceid     => $invoice->{invoiceid},
913             adjustment    => 3,
914             encumber_open => 1,
915             budget_id     => $budget_2->{budget_id},
916         }
917     });
918     my $inv_adj_6 = $builder->build({
919         source => 'AqinvoiceAdjustment',
920         value  => {
921             invoiceid     => $invoice_2->{invoiceid},
922             adjustment    => 3,
923             encumber_open => 1,
924             budget_id     => $budget_2->{budget_id},
925         }
926     });
927
928     $spent = GetBudgetSpent( $budget->{budget_id} );
929     $ordered = GetBudgetOrdered( $budget->{budget_id} );
930     is( $spent, 6, "After adding invoice adjustment on a different budget should be 6 spent/budget unaffected");
931     is( $ordered, 3, "After adding invoice adjustment on a different budget, should still be 3 ordered/budget unaffected");
932
933 };
934
935 sub _get_dependencies {
936     my ($budget_hierarchy) = @_;
937     my $graph;
938     for my $budget (@$budget_hierarchy) {
939         if ( $budget->{child} ) {
940             my @sorted = sort @{ $budget->{child} };
941             for my $child_id (@sorted) {
942                 push @{ $graph->{ $budget->{budget_name} }{children} },
943                   _get_budgetname_by_id( $budget_hierarchy, $child_id );
944             }
945         }
946         push @{ $graph->{ $budget->{budget_name} }{parents} },
947           $budget->{parent_id};
948     }
949     return $graph;
950 }
951
952 sub _get_budgetname_by_id {
953     my ( $budgets, $budget_id ) = @_;
954     my ($budget_name) =
955       map { ( $_->{budget_id} eq $budget_id ) ? $_->{budget_name} : () }
956       @$budgets;
957     return $budget_name;
958 }