Bug 18736: (follow-up) Add missing test cases
[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 use Koha::Number::Price;
17 use Koha::Items;
18
19 use t::lib::TestBuilder;
20 use t::lib::Mocks;
21 use Koha::DateUtils;
22
23 use YAML;
24
25 use t::lib::Mocks;
26 t::lib::Mocks::mock_preference('OrderPriceRounding','');
27
28 my $schema  = Koha::Database->new->schema;
29 $schema->storage->txn_begin;
30 my $builder = t::lib::TestBuilder->new;
31 my $dbh = C4::Context->dbh;
32 $dbh->do(q|DELETE FROM aqbudgetperiods|);
33 $dbh->do(q|DELETE FROM aqbudgets|);
34
35 my $library = $builder->build({
36     source => 'Branch',
37 });
38
39 t::lib::Mocks::mock_userenv(
40     {
41         flags => 1,
42         userid => 'my_userid',
43         branch => $library->{branchcode},
44     }
45 );
46
47 #
48 # Budget Periods :
49 #
50
51 is( AddBudgetPeriod(), undef, 'AddBugetPeriod without argument returns undef' );
52 is( AddBudgetPeriod( { }  ), undef, 'AddBugetPeriod with an empty argument returns undef' );
53 my $bpid = AddBudgetPeriod({
54     budget_period_startdate => '2008-01-01',
55 });
56 is( $bpid, undef, 'AddBugetPeriod without end date returns undef' );
57 $bpid = AddBudgetPeriod({
58     budget_period_enddate => '2008-12-31',
59 });
60 is( $bpid, undef, 'AddBugetPeriod without start date returns undef' );
61 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
62 my $budgetperiods = GetBudgetPeriods();
63 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
64
65 my $my_budgetperiod = {
66     budget_period_startdate   => '2008-01-01',
67     budget_period_enddate     => '2008-12-31',
68     budget_period_description => 'MAPERI',
69     budget_period_active      => 0,
70     budget_period_id          => '', # Bug 21604
71 };
72 $bpid = AddBudgetPeriod($my_budgetperiod);
73 isnt( $bpid, undef, 'AddBugetPeriod does not returns undef' );
74 my $budgetperiod = GetBudgetPeriod($bpid);
75 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'AddBudgetPeriod stores the start date correctly' );
76 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'AddBudgetPeriod stores the end date correctly' );
77 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'AddBudgetPeriod stores the description correctly' );
78 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'AddBudgetPeriod stores active correctly' );
79 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
80
81
82 $my_budgetperiod = {
83     budget_period_startdate   => '2009-01-01',
84     budget_period_enddate     => '2009-12-31',
85     budget_period_description => 'MODIF_MAPERI',
86     budget_period_active      => 1,
87 };
88 my $mod_status = ModBudgetPeriod($my_budgetperiod);
89 is( $mod_status, undef, 'ModBudgetPeriod without id returns undef' );
90
91 $my_budgetperiod->{budget_period_id} = $bpid;
92 $mod_status = ModBudgetPeriod($my_budgetperiod);
93 is( $mod_status, 1, 'ModBudgetPeriod returnis true' );
94 $budgetperiod = GetBudgetPeriod($bpid);
95 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'ModBudgetPeriod updates the start date correctly' );
96 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'ModBudgetPeriod updates the end date correctly' );
97 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'ModBudgetPeriod updates the description correctly' );
98 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'ModBudgetPeriod upates active correctly' );
99 isnt( GetBudgetPeriod(0), undef, 'GetBugetPeriods functions correctly' );
100
101
102 $budgetperiods = GetBudgetPeriods();
103 is( @$budgetperiods, 1, 'GetBudgetPeriods returns the correct number of budget periods' );
104 is( $budgetperiods->[0]->{budget_period_id}, $my_budgetperiod->{budget_period_id}, 'GetBudgetPeriods returns the id correctly' );
105 is( $budgetperiods->[0]->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'GetBudgetPeriods returns the start date correctly' );
106 is( $budgetperiods->[0]->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'GetBudgetPeriods returns the end date correctly' );
107 is( $budgetperiods->[0]->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'GetBudgetPeriods returns the description correctly' );
108 is( $budgetperiods->[0]->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'GetBudgetPeriods returns active correctly' );
109
110 is( DelBudgetPeriod($bpid), 1, 'DelBudgetPeriod returns true' );
111 $budgetperiods = GetBudgetPeriods();
112 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
113
114
115 #
116 # Budget  :
117 #
118
119 # The budget hierarchy will be:
120 # budget_1
121 #   budget_11
122 #     budget_111
123 #   budget_12
124 # budget_2
125 #   budget_21
126
127 is( AddBudget(), undef, 'AddBuget without argument returns undef' );
128 my $budgets = GetBudgets();
129 is( @$budgets, 0, 'GetBudgets returns the correct number of budgets' );
130
131 $bpid = AddBudgetPeriod($my_budgetperiod); #this is an active budget
132
133 my $my_budget = {
134     budget_code      => 'ABCD',
135     budget_amount    => '123.132000',
136     budget_name      => 'Periodiques',
137     budget_notes     => 'This is a note',
138     budget_period_id => $bpid,
139     budget_encumb    => '', # Bug 21604
140 };
141 my $budget_id = AddBudget($my_budget);
142 isnt( $budget_id, undef, 'AddBudget does not returns undef' );
143 my $budget = GetBudget($budget_id);
144 is( $budget->{budget_code}, $my_budget->{budget_code}, 'AddBudget stores the budget code correctly' );
145 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'AddBudget stores the budget amount correctly' );
146 is( $budget->{budget_name}, $my_budget->{budget_name}, 'AddBudget stores the budget name correctly' );
147 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'AddBudget stores the budget notes correctly' );
148 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'AddBudget stores the budget period id correctly' );
149
150
151 $my_budget = {
152     budget_code      => 'EFG',
153     budget_amount    => '321.231000',
154     budget_name      => 'Modified name',
155     budget_notes     => 'This is a modified note',
156     budget_period_id => $bpid,
157 };
158 $mod_status = ModBudget($my_budget);
159 is( $mod_status, undef, 'ModBudget without id returns undef' );
160
161 $my_budget->{budget_id} = $budget_id;
162 $mod_status = ModBudget($my_budget);
163 is( $mod_status, 1, 'ModBudget returns true' );
164 $budget = GetBudget($budget_id);
165 is( $budget->{budget_code}, $my_budget->{budget_code}, 'ModBudget updates the budget code correctly' );
166 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'ModBudget updates the budget amount correctly' );
167 is( $budget->{budget_name}, $my_budget->{budget_name}, 'ModBudget updates the budget name correctly' );
168 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'ModBudget updates the budget notes correctly' );
169 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'ModBudget updates the budget period id correctly' );
170
171
172 $budgets = GetBudgets();
173 is( @$budgets, 1, 'GetBudgets returns the correct number of budgets' );
174 is( $budgets->[0]->{budget_id}, $my_budget->{budget_id}, 'GetBudgets returns the budget id correctly' );
175 is( $budgets->[0]->{budget_code}, $my_budget->{budget_code}, 'GetBudgets returns the budget code correctly' );
176 is( $budgets->[0]->{budget_amount}, $my_budget->{budget_amount}, 'GetBudgets returns the budget amount correctly' );
177 is( $budgets->[0]->{budget_name}, $my_budget->{budget_name}, 'GetBudgets returns the budget name correctly' );
178 is( $budgets->[0]->{budget_notes}, $my_budget->{budget_notes}, 'GetBudgets returns the budget notes correctly' );
179 is( $budgets->[0]->{budget_period_id}, $my_budget->{budget_period_id}, 'GetBudgets returns the budget period id correctly' );
180
181 $budgets = GetBudgets( {budget_period_id => $bpid} );
182 is( @$budgets, 1, 'GetBudgets With Filter OK' );
183 $budgets = GetBudgets( {budget_period_id => $bpid}, {-asc => "budget_name"} );
184 is( @$budgets, 1, 'GetBudgets With Order OK' );
185 $budgets = GetBudgets( {budget_period_id => GetBudgetPeriod($bpid)->{budget_period_id}}, {-asc => "budget_name"} );
186 is( @$budgets, 1, 'GetBudgets With Order Getting Active budgetPeriod OK');
187
188
189 my $budget_name = GetBudgetName( $budget_id );
190 is($budget_name, $my_budget->{budget_name}, "Test the GetBudgetName routine");
191
192 my $my_inactive_budgetperiod = { #let's add an inactive
193     budget_period_startdate   => '2010-01-01',
194     budget_period_enddate     => '2010-12-31',
195     budget_period_description => 'MODIF_MAPERI',
196     budget_period_active      => 0,
197 };
198 my $bpid_i = AddBudgetPeriod($my_inactive_budgetperiod); #this is an inactive budget
199
200 my $my_budget_inactive = {
201     budget_code      => 'EFG',
202     budget_amount    => '123.132000',
203     budget_name      => 'Periodiques',
204     budget_notes     => 'This is a note',
205     budget_period_id => $bpid_i,
206 };
207 my $budget_id_inactive = AddBudget($my_budget_inactive);
208
209 my $budget_code = $my_budget->{budget_code};
210 my $budget_by_code = GetBudgetByCode( $budget_code );
211 is($budget_by_code->{budget_id}, $budget_id, "GetBudgetByCode, check id"); #this should match the active budget, not the inactive
212 is($budget_by_code->{budget_notes}, $my_budget->{budget_notes}, "GetBudgetByCode, check notes");
213
214 my $second_budget_id = AddBudget({
215     budget_code      => "ZZZZ",
216     budget_amount    => "500.00",
217     budget_name      => "Art",
218     budget_notes     => "This is a note",
219     budget_period_id => $bpid,
220 });
221 isnt( $second_budget_id, undef, 'AddBudget does not returns undef' );
222
223 $budgets = GetBudgets( {budget_period_id => $bpid} );
224 ok( $budgets->[0]->{budget_name} lt $budgets->[1]->{budget_name}, 'default sort order for GetBudgets is by name' );
225
226 is( DelBudget($budget_id), 1, 'DelBudget returns true' );
227 $budgets = GetBudgets();
228 is( @$budgets, 2, 'GetBudgets returns the correct number of budget periods' );
229
230
231 # GetBudgetHierarchySpent and GetBudgetHierarchyOrdered
232 my $budget_period_total = 10_000;
233 my $budget_1_total = 1_000;
234 my $budget_11_total = 100;
235 my $budget_111_total = 50;
236 my $budget_12_total = 100;
237 my $budget_2_total = 2_000;
238
239 my $budget_period_id = AddBudgetPeriod(
240     {
241         budget_period_startdate   => '2013-01-01',
242         budget_period_enddate     => '2014-12-31',
243         budget_period_description => 'Budget Period',
244         budget_period_active      => 1,
245         budget_period_total       => $budget_period_total,
246     }
247 );
248 my $budget_id1 = AddBudget(
249     {
250         budget_code      => 'budget_1',
251         budget_name      => 'budget_1',
252         budget_period_id => $budget_period_id,
253         budget_parent_id => undef,
254         budget_amount    => $budget_1_total,
255     }
256 );
257 my $budget_id2 = AddBudget(
258     {
259         budget_code      => 'budget_2',
260         budget_name      => 'budget_2',
261         budget_period_id => $budget_period_id,
262         budget_parent_id => undef,
263         budget_amount    => $budget_2_total,
264     }
265 );
266 my $budget_id12 = AddBudget(
267     {
268         budget_code      => 'budget_12',
269         budget_name      => 'budget_12',
270         budget_period_id => $budget_period_id,
271         budget_parent_id => $budget_id1,
272         budget_amount    => $budget_12_total,
273     }
274 );
275 my $budget_id11 = AddBudget(
276     {
277         budget_code      => 'budget_11',
278         budget_name      => 'budget_11',
279         budget_period_id => $budget_period_id,
280         budget_parent_id => $budget_id1,
281         budget_amount    => $budget_11_total,
282     }
283 );
284 my $budget_id111 = AddBudget(
285     {
286         budget_code      => 'budget_111',
287         budget_name      => 'budget_111',
288         budget_period_id => $budget_period_id,
289         budget_parent_id => $budget_id11,
290         budget_owner_id  => 1,
291         budget_amount    => $budget_111_total,
292     }
293 );
294 my $budget_id21 = AddBudget(
295     {
296         budget_code      => 'budget_21',
297         budget_name      => 'budget_21',
298         budget_period_id => $budget_period_id,
299         budget_parent_id => $budget_id2,
300     }
301 );
302
303 my $bookseller = Koha::Acquisition::Bookseller->new(
304     {
305         name         => "my vendor",
306         address1     => "bookseller's address",
307         phone        => "0123456",
308         active       => 1,
309         deliverytime => 5,
310     }
311 )->store;
312 my $booksellerid = $bookseller->id;
313
314 my $basketno = C4::Acquisition::NewBasket( $booksellerid, 1 );
315 my ( $biblionumber, $biblioitemnumber ) =
316   C4::Biblio::AddBiblio( MARC::Record->new, '' );
317
318 my @order_infos = (
319     {
320         budget_id => $budget_id1,
321         pending_quantity  => 1,
322         spent_quantity  => 0,
323     },
324     {
325         budget_id => $budget_id2,
326         pending_quantity  => 2,
327         spent_quantity  => 1,
328     },
329     {
330         budget_id => $budget_id11,
331         pending_quantity  => 3,
332         spent_quantity  => 4,
333     },
334     {
335         budget_id => $budget_id12,
336         pending_quantity  => 4,
337         spent_quantity  => 3,
338     },
339     {
340         budget_id => $budget_id111,
341         pending_quantity  => 2,
342         spent_quantity  => 1,
343     },
344
345     # No order for budget_21
346
347 );
348
349 my %budgets;
350 my $invoiceid = AddInvoice(invoicenumber => 'invoice_test_clone', booksellerid => $booksellerid, unknown => "unknown");
351 my $invoice = GetInvoice( $invoiceid );
352 my $item_price = 10;
353 my $item_quantity = 2;
354 my $number_of_orders_to_move = 0;
355 for my $infos (@order_infos) {
356     for ( 1 .. $infos->{pending_quantity} ) {
357         my $order = Koha::Acquisition::Order->new(
358             {
359                 basketno           => $basketno,
360                 biblionumber       => $biblionumber,
361                 budget_id          => $infos->{budget_id},
362                 order_internalnote => "internal note",
363                 order_vendornote   => "vendor note",
364                 quantity           => 2,
365                 cost_tax_included  => $item_price,
366                 rrp_tax_included   => $item_price,
367                 listprice          => $item_price,
368                 ecost_tax_include  => $item_price,
369                 discount           => 0,
370                 uncertainprice     => 0,
371             }
372         )->store;
373         my $ordernumber = $order->ordernumber;
374         push @{ $budgets{$infos->{budget_id}} }, $ordernumber;
375         $number_of_orders_to_move++;
376     }
377     for ( 1 .. $infos->{spent_quantity} ) {
378         my $order = Koha::Acquisition::Order->new(
379             {
380                 basketno           => $basketno,
381                 biblionumber       => $biblionumber,
382                 budget_id          => $infos->{budget_id},
383                 order_internalnote => "internal note",
384                 order_vendornote   => "vendor note",
385                 quantity           => $item_quantity,
386                 cost               => $item_price,
387                 rrp_tax_included   => $item_price,
388                 listprice          => $item_price,
389                 ecost_tax_included => $item_price,
390                 discount           => 0,
391                 uncertainprice     => 0,
392             }
393         )->store;
394         my $ordernumber = $order->ordernumber;
395         ModReceiveOrder({
396               biblionumber     => $biblionumber,
397               order            => $order->unblessed,
398               budget_id        => $infos->{budget_id},
399               quantityreceived => $item_quantity,
400               invoice          => $invoice,
401               received_items   => [],
402         } );
403     }
404 }
405 is( GetBudgetHierarchySpent( $budget_id1 ), 160, "total spent for budget1 is 160" );
406 is( GetBudgetHierarchySpent( $budget_id11 ), 100, "total spent for budget11 is 100" );
407 is( GetBudgetHierarchySpent( $budget_id111 ), 20, "total spent for budget111 is 20" );
408
409 # GetBudgetSpent and GetBudgetOrdered
410 my $budget_period_amount = 100;
411 my $budget_amount = 50;
412
413 $budget = AddBudgetPeriod(
414     {
415         budget_period_startdate   => '2017-08-22',
416         budget_period_enddate     => '2018-08-22',
417         budget_period_description => 'Test budget',
418         budget_period_active      => 1,
419         budget_period_total       => $budget_period_amount,
420     }
421 );
422
423 my $fund = AddBudget(
424     {
425         budget_code       => 'Test fund',
426         budget_name       => 'Test fund',
427         budget_period_id  => $budget,
428         budget_parent_id  => undef,
429         budget_amount     => $budget_amount,
430     }
431 );
432
433 my $vendor = Koha::Acquisition::Bookseller->new(
434     {
435         name         => "test vendor",
436         address1     => "test address",
437         phone        => "0123456",
438         active       => 1,
439         deliverytime => 5,
440     }
441 )->store;
442
443 my $vendorid = $vendor->id;
444
445 my $basketnumber = C4::Acquisition::NewBasket( $vendorid, 1 );
446 my ( $biblio, $biblioitem ) = C4::Biblio::AddBiblio( MARC::Record->new, '' );
447
448 my @orders = (
449     {
450         budget_id  => $fund,
451         pending_quantity => 1,
452         spent_quantity => 0,
453     },
454 );
455
456 my $invoiceident = AddInvoice( invoicenumber => 'invoice_test_clone', booksellerid => $vendorid, shipmentdate => '2017-08-22', shipmentcost => 6, shipmentcost_budgetid => $fund );
457 my $test_invoice = GetInvoice( $invoiceident );
458 my $individual_item_price = 10;
459
460 my $order = Koha::Acquisition::Order->new(
461    {
462       basketno           => $basketnumber,
463       biblionumber       => $biblio,
464       budget_id          => $fund,
465       order_internalnote => "internalnote",
466       order_vendornote   => "vendor note",
467       quantity           => 2,
468       cost_tax_included  => $individual_item_price,
469       rrp_tax_included   => $individual_item_price,
470       listprice          => $individual_item_price,
471       ecost_tax_included => $individual_item_price,
472       discount           => 0,
473       uncertainprice     => 0,
474    }
475 )->store;
476
477 ModReceiveOrder({
478    bibionumber       => $biblio,
479    order             => $order->unblessed,
480    budget_id         => $fund,
481    quantityreceived  => 2,
482    invoice           => $test_invoice,
483    received_items    => [],
484 } );
485 t::lib::Mocks::mock_preference('OrderPriceRounding','');
486
487 is ( GetBudgetSpent( $fund ), 6, "total shipping cost is 6");
488 is ( GetBudgetOrdered( $fund ), '20', "total ordered price is 20");
489
490
491 # CloneBudgetPeriod
492 # Let's make sure our timestamp is old
493 my @orig_funds = Koha::Acquisition::Funds->search({ budget_period_id => $budget_period_id });
494 foreach my $fund (@orig_funds){
495     $fund->timestamp('1999-12-31 23:59:59')->store;
496 }
497
498 my $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
499     {
500         budget_period_id        => $budget_period_id,
501         budget_period_startdate => '2014-01-01',
502         budget_period_enddate   => '2014-12-31',
503         budget_period_description => 'Budget Period Cloned',
504     }
505 );
506
507 my $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
508 is($budget_period_cloned->{budget_period_description}, 'Budget Period Cloned', 'Cloned budget\'s description is updated.');
509
510 my $budget_cloned = C4::Budgets::GetBudgets({ budget_period_id => $budget_period_id_cloned });
511 my $budget_time =  $budget_cloned->[0]->{timestamp};
512
513 isnt($budget_time, '1999-12-31 23:59:59', "New budget has an updated timestamp");
514
515
516
517 my $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
518 my $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
519
520 is(
521     scalar(@$budget_hierarchy_cloned),
522     scalar(@$budget_hierarchy),
523     'CloneBudgetPeriod clones the same number of budgets (funds)'
524 );
525 is_deeply(
526     _get_dependencies($budget_hierarchy),
527     _get_dependencies($budget_hierarchy_cloned),
528     'CloneBudgetPeriod keeps the same dependencies order'
529 );
530
531 # CloneBudgetPeriod with param mark_original_budget_as_inactive
532 my $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
533 is( $budget_period->{budget_period_active}, 1,
534     'CloneBudgetPeriod does not mark as inactive the budgetperiod if not needed'
535 );
536
537 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
538 my $number_of_budgets_not_reset = 0;
539 for my $budget (@$budget_hierarchy_cloned) {
540     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
541 }
542 is( $number_of_budgets_not_reset, 5,
543     'CloneBudgetPeriod does not reset budgets (funds) if not needed' );
544
545 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
546     {
547         budget_period_id                 => $budget_period_id,
548         budget_period_startdate          => '2014-01-01',
549         budget_period_enddate            => '2014-12-31',
550         mark_original_budget_as_inactive => 1,
551     }
552 );
553
554 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
555 is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy should return budgets ordered by name, first child is budget_11' );
556 is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy should return budgets ordered by name, second child is budget_12' );
557 is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy should return budgets ordered by name, first budget is budget_1');
558 is($budget_hierarchy->[0]->{budget_level},'0','budget_level of budget (budget_1)  should be 0');
559 is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','budget_level of first fund(budget_11)  should be 1');
560 is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','budget_level of second fund(budget_12)  should be 1');
561 is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','budget_level of  child fund budget_11 should be 2');
562 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
563 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
564
565 is( scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy),
566 'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)'
567 );
568 is_deeply(
569     _get_dependencies($budget_hierarchy),
570     _get_dependencies($budget_hierarchy_cloned),
571     'CloneBudgetPeriod (with inactive param) keeps the same dependencies order'
572 );
573 $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
574 is( $budget_period->{budget_period_active}, 0,
575     'CloneBudgetPeriod (with inactive param) marks as inactive the budgetperiod'
576 );
577
578 # CloneBudgetPeriod with param reset_all_budgets
579 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
580     {
581         budget_period_id        => $budget_period_id,
582         budget_period_startdate => '2014-01-01',
583         budget_period_enddate   => '2014-12-31',
584         reset_all_budgets         => 1,
585     }
586 );
587
588 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
589 $number_of_budgets_not_reset = 0;
590 for my $budget (@$budget_hierarchy_cloned) {
591     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
592 }
593 is( $number_of_budgets_not_reset, 0,
594     'CloneBudgetPeriod has reset all budgets (funds)' );
595
596 #GetBudgetsByActivity
597 my $result=C4::Budgets::GetBudgetsByActivity(1);
598 isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 1');
599 $result=C4::Budgets::GetBudgetsByActivity(0);
600  isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 0');
601 $result=C4::Budgets::GetBudgetsByActivity();
602  is( $result, 0 , 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' );
603 DelBudget($budget_id);
604 DelBudgetPeriod($bpid);
605
606 # CloneBudgetPeriod with param amount_change_*
607 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
608     {
609         budget_period_id        => $budget_period_id,
610         budget_period_startdate => '2014-01-01',
611         budget_period_enddate   => '2014-12-31',
612         amount_change_percentage => 16,
613         amount_change_round_increment => 5,
614     }
615 );
616
617 $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
618 cmp_ok($budget_period_cloned->{budget_period_total}, '==', 11600, "CloneBudgetPeriod changed correctly budget amount");
619 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
620 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, "CloneBudgetPeriod changed correctly funds amounts");
621 cmp_ok($budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
622 cmp_ok($budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts");
623 cmp_ok($budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
624 cmp_ok($budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, "CloneBudgetPeriod changed correctly funds amounts");
625 cmp_ok($budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts");
626
627 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
628     {
629         budget_period_id        => $budget_period_id,
630         budget_period_startdate => '2014-01-01',
631         budget_period_enddate   => '2014-12-31',
632         amount_change_percentage => 16,
633         amount_change_round_increment => 5,
634         reset_all_budgets => 1,
635     }
636 );
637 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
638 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts");
639
640 # MoveOrders
641 my $number_orders_moved = C4::Budgets::MoveOrders();
642 is( $number_orders_moved, undef, 'MoveOrders return undef if no arg passed' );
643 $number_orders_moved =
644   C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } );
645 is( $number_orders_moved, undef,
646     'MoveOrders return undef if only 1 arg passed' );
647 $number_orders_moved =
648   C4::Budgets::MoveOrders( { to_budget_period_id => $budget_period_id } );
649 is( $number_orders_moved, undef,
650     'MoveOrders return undef if only 1 arg passed' );
651 $number_orders_moved = C4::Budgets::MoveOrders(
652     {
653         from_budget_period_id => $budget_period_id,
654         to_budget_period_id   => $budget_period_id
655     }
656 );
657 is( $number_orders_moved, undef,
658     'MoveOrders return undef if 2 budget period id are the same' );
659
660 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
661     {
662         budget_period_id        => $budget_period_id,
663         budget_period_startdate => '2014-01-01',
664         budget_period_enddate   => '2014-12-31',
665     }
666 );
667
668 my $report = C4::Budgets::MoveOrders(
669     {
670         from_budget_period_id  => $budget_period_id,
671         to_budget_period_id    => $budget_period_id_cloned,
672         move_remaining_unspent => 1,
673     }
674 );
675 is( scalar( @$report ), 6 , "MoveOrders has processed 6 funds" );
676
677 my $number_of_orders_moved = 0;
678 $number_of_orders_moved += scalar( @{ $_->{orders_moved} } ) for @$report;
679 is( $number_of_orders_moved, $number_of_orders_to_move, "MoveOrders has moved $number_of_orders_to_move orders" );
680
681 my @new_budget_ids = map { $_->{budget_id} }
682   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
683 my @old_budget_ids = map { $_->{budget_id} }
684   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
685 for my $budget_id ( keys %budgets ) {
686     for my $ordernumber ( @{ $budgets{$budget_id} } ) {
687         my $budget            = GetBudgetByOrderNumber($ordernumber);
688         my $is_in_new_budgets = grep /^$budget->{budget_id}$/, @new_budget_ids;
689         my $is_in_old_budgets = grep /^$budget->{budget_id}$/, @old_budget_ids;
690         is( $is_in_new_budgets, 1, "MoveOrders changed the budget_id for order $ordernumber" );
691         is( $is_in_old_budgets, 0, "MoveOrders changed the budget_id for order $ordernumber" );
692     }
693 }
694
695
696 # MoveOrders with param move_remaining_unspent
697 my @new_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
698 my @old_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
699
700 for my $new_budget ( @new_budgets ) {
701     my ( $old_budget ) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets;
702     my $new_budget_amount_should_be = $old_budget->{budget_amount} * 2 - $old_budget->{total_spent};
703     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})" );
704 }
705
706 # Test SetOwnerToFundHierarchy
707
708 my $patron_category = $builder->build({ source => 'Category' });
709 my $branchcode = $library->{branchcode};
710 my $john_doe = Koha::Patron->new({
711     cardnumber   => '123456',
712     firstname    => 'John',
713     surname      => 'Doe',
714     categorycode => $patron_category->{categorycode},
715     branchcode   => $branchcode,
716     dateofbirth  => '',
717     dateexpiry   => '9999-12-31',
718     userid       => 'john.doe'
719 })->store->borrowernumber;
720
721 C4::Budgets::SetOwnerToFundHierarchy( $budget_id1, $john_doe );
722 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
723     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" );
724 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
725     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" );
726 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
727     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" );
728 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
729     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" );
730 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
731     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" );
732 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
733     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" );
734
735 my $jane_doe = Koha::Patron->new({
736     cardnumber   => '789012',
737     firstname    => 'Jane',
738     surname      => 'Doe',
739     categorycode => $patron_category->{categorycode},
740     branchcode   => $branchcode,
741     dateofbirth  => '',
742     dateexpiry   => '9999-12-31',
743     userid       => 'jane.doe'
744 })->store->borrowernumber;
745
746 C4::Budgets::SetOwnerToFundHierarchy( $budget_id11, $jane_doe );
747 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
748     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" );
749 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
750     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" );
751 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
752     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" );
753 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
754     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" );
755 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
756     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" );
757 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
758     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" );
759
760 # Test GetBudgetAuthCats
761
762 my $budgetPeriodId = AddBudgetPeriod({
763     budget_period_startdate   => '2008-01-01',
764     budget_period_enddate     => '2008-12-31',
765     budget_period_description => 'just another budget',
766     budget_period_active      => 0,
767 });
768
769 $budgets = GetBudgets();
770 my $i = 0;
771 for my $budget ( @$budgets )
772 {
773     $budget->{sort1_authcat} = "sort1_authcat_$i";
774     $budget->{sort2_authcat} = "sort2_authcat_$i";
775     $budget->{budget_period_id} = $budgetPeriodId;
776     ModBudget( $budget );
777     $i++;
778 }
779
780 my $authCat = GetBudgetAuthCats($budgetPeriodId);
781
782 is( scalar @{$authCat}, $i * 2, "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" );
783
784 $i = 0;
785 for my $budget ( @$budgets )
786 {
787     $budget->{sort1_authcat} = "sort_authcat_$i";
788     $budget->{sort2_authcat} = "sort_authcat_$i";
789     $budget->{budget_period_id} = $budgetPeriodId;
790     ModBudget( $budget );
791     $i++;
792 }
793
794 $authCat = GetBudgetAuthCats($budgetPeriodId);
795 is( scalar @$authCat, scalar @$budgets, "GetBudgetAuthCats returns distinct authCat" );
796
797 $i = 0;
798 for my $budget ( @$budgets )
799 {
800     $budget->{sort1_authcat} = "sort1_authcat_$i";
801     $budget->{sort2_authcat} = "";
802     $budget->{budget_period_id} = $budgetPeriodId;
803     ModBudget( $budget );
804     $i++;
805 }
806
807 $authCat = GetBudgetAuthCats($budgetPeriodId);
808
809 is( scalar @{$authCat}, $i, "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" );
810
811 $i = 0;
812 for my $budget ( @$budgets )
813 {
814     $budget->{sort1_authcat} = "";
815     $budget->{sort2_authcat} = "";
816     $budget->{budget_period_id} = $budgetPeriodId;
817     ModBudget( $budget );
818     $i++;
819 }
820
821 $authCat = GetBudgetAuthCats($budgetPeriodId);
822
823 is( scalar @{$authCat}, 0, "GetBudgetAuthCats returns only non-empty sorting categories (all empty)" );
824
825 # /Test GetBudgetAuthCats
826
827 subtest 'GetBudgetSpent and GetBudgetOrdered' => sub {
828     plan tests => 20;
829
830     my $budget_period = $builder->build({
831         source => 'Aqbudgetperiod',
832         value  => {
833             budget_period_active => 1,
834             budget_total => 10000,
835         }
836     });
837     my $budget = $builder->build({
838         source => 'Aqbudget',
839         value  => {
840             budget_amount => 1000,
841             budget_encumb => undef,
842             budget_expend => undef,
843             budget_period_id => $budget_period->{budget_period_id},
844             budget_parent_id => undef,
845         }
846     });
847     my $invoice = $builder->build({
848         source => 'Aqinvoice',
849         value  => {
850             closedate => undef,
851         }
852     });
853
854     my $spent     = GetBudgetSpent( $budget->{budget_id} );
855     my $ordered   = GetBudgetOrdered( $budget->{budget_id} );
856     my $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
857
858     is( $spent, 0, "New budget, no orders/invoices, should be nothing spent");
859     is( $ordered, 0, "New budget, no orders/invoices, should be nothing ordered");
860     is( @$hierarchy[0]->{total_spent},0,"New budgets, no orders/invoices, budget hierarchy shows 0 spent");
861     is( @$hierarchy[0]->{total_ordered},0,"New budgets, no orders/invoices, budget hierarchy shows 0 ordered");
862
863     my $inv_adj_1 = $builder->build({
864         source => 'AqinvoiceAdjustment',
865         value  => {
866             invoiceid     => $invoice->{invoiceid},
867             adjustment    => 3,
868             encumber_open => 0,
869             budget_id     => $budget->{budget_id},
870         }
871     });
872
873     $spent = GetBudgetSpent( $budget->{budget_id} );
874     $ordered = GetBudgetOrdered( $budget->{budget_id} );
875     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
876     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
877     is( $ordered, 0, "After adding invoice adjustment on open invoice not encumbered, should be nothing ordered");
878     is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 spent");
879     is( @$hierarchy[0]->{total_ordered},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 ordered");
880
881     my $inv_adj_2 = $builder->build({
882         source => 'AqinvoiceAdjustment',
883         value  => {
884             invoiceid     => $invoice->{invoiceid},
885             adjustment    => 3,
886             encumber_open => 1,
887             budget_id     => $budget->{budget_id},
888         }
889     });
890
891     $spent = GetBudgetSpent( $budget->{budget_id} );
892     $ordered = GetBudgetOrdered( $budget->{budget_id} );
893     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
894     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
895     is( $ordered, 3, "After adding invoice adjustment on open invoice encumbered, should be 3 ordered");
896     is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 0 spent");
897     is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 3 ordered");
898
899     my $invoice_2 = $builder->build({
900         source => 'Aqinvoice',
901         value  => {
902             closedate => '2017-07-01',
903         }
904     });
905     my $inv_adj_3 = $builder->build({
906         source => 'AqinvoiceAdjustment',
907         value  => {
908             invoiceid     => $invoice_2->{invoiceid},
909             adjustment    => 3,
910             encumber_open => 0,
911             budget_id     => $budget->{budget_id},
912         }
913     });
914     my $inv_adj_4 = $builder->build({
915         source => 'AqinvoiceAdjustment',
916         value  => {
917             invoiceid     => $invoice_2->{invoiceid},
918             adjustment    => 3,
919             encumber_open => 1,
920             budget_id     => $budget->{budget_id},
921         }
922     });
923
924     $spent = GetBudgetSpent( $budget->{budget_id} );
925     $ordered = GetBudgetOrdered( $budget->{budget_id} );
926     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
927     is( $spent, 6, "After adding invoice adjustment on closed invoice, should be 6 spent, encumber has no affect once closed");
928     is( $ordered, 3, "After adding invoice adjustment on closed invoice, should still be 3 ordered");
929     is( @$hierarchy[0]->{total_spent},6,"After adding invoice adjustment on closed invoice, budget hierarchy shows 6 spent");
930     is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on closed invoice, budget hierarchy still shows 3 ordered");
931
932     my $budget0 = $builder->build({
933         source => 'Aqbudget',
934         value  => {
935             budget_amount => 1000,
936             budget_encumb => undef,
937             budget_expend => undef,
938             budget_period_id => $budget_period->{budget_period_id},
939             budget_parent_id => $budget->{budget_id},
940         }
941     });
942     my $inv_adj_5 = $builder->build({
943         source => 'AqinvoiceAdjustment',
944         value  => {
945             invoiceid     => $invoice->{invoiceid},
946             adjustment    => 3,
947             encumber_open => 1,
948             budget_id     => $budget0->{budget_id},
949         }
950     });
951     my $inv_adj_6 = $builder->build({
952         source => 'AqinvoiceAdjustment',
953         value  => {
954             invoiceid     => $invoice_2->{invoiceid},
955             adjustment    => 3,
956             encumber_open => 1,
957             budget_id     => $budget0->{budget_id},
958         }
959     });
960
961     $spent = GetBudgetSpent( $budget->{budget_id} );
962     $ordered = GetBudgetOrdered( $budget->{budget_id} );
963     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
964     is( $spent, 6, "After adding invoice adjustment on a child budget should be 6 spent/budget unaffected");
965     is( $ordered, 3, "After adding invoice adjustment on a child budget, should still be 3 ordered/budget unaffected");
966     is( @$hierarchy[0]->{total_spent},9,"After adding invoice adjustment on child budget, budget hierarchy shows 9 spent");
967     is( @$hierarchy[0]->{total_ordered},6,"After adding invoice adjustment on child budget, budget hierarchy shows 6 ordered");
968 };
969
970 subtest 'GetBudgetSpent GetBudgetOrdered GetBudgetsPlanCell tests' => sub {
971
972     plan tests => 16;
973
974 #Let's build an order, we need a couple things though
975     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
976
977     my $spent_biblio   = $builder->build({ source => 'Biblio' });
978     my $item_1         = $builder->build({ source => 'Item', value => { biblionumber => $spent_biblio->{biblionumber} } });
979     my $biblioitem_1   = $builder->build({ source => 'Biblioitem', value => { biblionumber => $spent_biblio->{biblionumber}, itemnumber => $item_1->{itemnumber} } });
980     my $spent_basket   = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
981     my $spent_invoice  = $builder->build({ source => 'Aqinvoice'});
982     my $spent_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' }  });
983     my $spent_vendor   = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $spent_currency->{currency}, invoiceprice => $spent_currency->{currency} } });
984     my $budget_authcat = $builder->build({ source => 'AuthorisedValueCategory', value => {} });
985     my $spent_sort1    = $builder->build({ source => 'AuthorisedValue', value => {
986             category => $budget_authcat->{category_name},
987             authorised_value => 'PICKLE',
988         }
989     });
990     my $spent_budget = $builder->build({ source => 'Aqbudget', value => {
991             sort1_authcat => $budget_authcat->{category_name},
992         }
993     });
994     my $spent_orderinfo = {
995         basketno                => $spent_basket->{basketno},
996         booksellerid            => $spent_vendor->{id},
997         rrp                     => 16.99,
998         discount                => .42,
999         ecost                   => 16.91,
1000         biblionumber            => $spent_biblio->{biblionumber},
1001         currency                => $spent_currency->{currency},
1002         tax_rate_on_ordering    => 0,
1003         tax_value_on_ordering   => 0,
1004         tax_rate_on_receiving   => 0,
1005         tax_value_on_receiving  => 0,
1006         quantity                => 8,
1007         quantityreceived        => 0,
1008         datecancellationprinted => undef,
1009         datereceived            => undef,
1010         budget_id               => $spent_budget->{budget_id},
1011         sort1                   => $spent_sort1->{authorised_value},
1012     };
1013
1014 #Okay we have basically what the user would enter, now we do some maths
1015
1016     $spent_orderinfo = C4::Acquisition::populate_order_with_prices({
1017             order        => $spent_orderinfo,
1018             booksellerid => $spent_orderinfo->{booksellerid},
1019             ordering     => 1,
1020     });
1021
1022 #And let's place the order
1023
1024     my $spent_order = $builder->build({ source => 'Aqorder', value => $spent_orderinfo });
1025     t::lib::Mocks::mock_preference('OrderPriceRounding','');
1026     my $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} );
1027
1028     is($spent_orderinfo->{ecost_tax_excluded}, 9.854200,'We store extra precision in price calculation');
1029     is( Koha::Number::Price->new($spent_orderinfo->{ecost_tax_excluded})->format(), 9.85,'But the price as formatted is two digits');
1030     is($spent_ordered,'78.8336',"We expect the ordered amount to be equal to the estimated price times quantity with full precision");
1031
1032     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1033     $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} );
1034     is($spent_ordered,'78.8',"We expect the ordered amount to be equal to the estimated price rounded times quantity");
1035
1036 #Let's test some budget planning
1037 #Regression tests for bug 18736
1038     #We need an item to test by BRANCHES
1039     my $order_item_1 = $builder->build({ source => 'AqordersItem', value => { ordernumber => $spent_order->{ordernumber}, itemnumber => $item_1->{itemnumber}  } });
1040     my $spent_fund = Koha::Acquisition::Funds->find( $spent_order->{budget_id} );
1041     my $cell = {
1042         authcat => 'MONTHS',
1043         cell_authvalue => $spent_order->{entrydate}, #normally this is just the year/month but full won't hurt us here
1044         budget_id => $spent_order->{budget_id},
1045         budget_period_id => $spent_fund->budget_period_id,
1046         sort1_authcat => $spent_order->{sort1_authcat},
1047         sort2_authcat => $spent_order->{sort1_authcat},
1048     };
1049     my $test_values = {
1050         'MONTHS' => {
1051             authvalue => $spent_order->{entrydate},
1052             expected_rounded => 9.85,
1053             expected_exact   => 9.8542,
1054         },
1055         'BRANCHES' => {
1056             authvalue => $item_1->{homebranch},
1057             expected_rounded => 9.85,
1058             expected_exact   => 9.8542,
1059         },
1060         'ITEMTYPES' => {
1061             authvalue => $biblioitem_1->{itemtype},
1062             expected_rounded => 78.80,
1063             expected_exact   => 78.8336,
1064         },
1065         'ELSE' => {
1066             authvalue => $spent_sort1->{authorised_value},
1067             expected_rounded => 78.8,
1068             expected_exact   => 78.8336,
1069         },
1070     };
1071
1072     for my $authcat ( keys %$test_values ) {
1073         my $test_val         = $test_values->{$authcat};
1074         my $authvalue        = $test_val->{authvalue};
1075         my $expected_rounded = $test_val->{expected_rounded};
1076         my $expected_exact   = $test_val->{expected_exact};
1077         $cell->{authcat} = $authcat;
1078         $cell->{authvalue} = $authvalue;
1079         t::lib::Mocks::mock_preference('OrderPriceRounding','');
1080         my ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now
1081         is ( $actual+0, $expected_exact, "We expect this to be an exact order cost ($authcat)"); #really we should expect cost*quantity but we don't
1082         t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1083         ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now
1084         is ( $actual+0, $expected_rounded, "We expect this to be a rounded order cost ($authcat)"); #really we should expect cost*quantity but we don't
1085     }
1086
1087 #Okay, now we can receive the order, giving the price as the user would
1088
1089     $spent_orderinfo->{unitprice} = 9.85; #we are paying what we expected
1090
1091 #Do our maths
1092
1093     $spent_orderinfo = C4::Acquisition::populate_order_with_prices({
1094             order        => $spent_orderinfo,
1095             booksellerid => $spent_orderinfo->{booksellerid},
1096             receiving    => 1,
1097     });
1098     my $received_order = $builder->build({ source => 'Aqorder', value => $spent_orderinfo });
1099
1100 #And receive
1101
1102     ModReceiveOrder({
1103             biblionumber => $spent_order->{biblionumber},
1104             order => $received_order,
1105             invoice => $spent_invoice,
1106             quantityreceived => $spent_order->{quantity},
1107             budget_id => $spent_order->{budget_id},
1108             received_items => [],
1109     });
1110
1111     t::lib::Mocks::mock_preference('OrderPriceRounding','');
1112     my $spent_spent = GetBudgetSpent( $spent_order->{budget_id} );
1113     is($spent_orderinfo->{unitprice_tax_excluded}, 9.854200,'We store extra precision in price calculation');
1114     is( Koha::Number::Price->new($spent_orderinfo->{unitprice_tax_excluded})->format(), 9.85,'But the price as formatted is two digits');
1115     is($spent_spent,'78.8336',"We expect the spent amount to be equal to the estimated price times quantity with full precision");
1116
1117     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1118     $spent_spent = GetBudgetSpent( $spent_order->{budget_id} );
1119     is($spent_spent,'78.8',"We expect the spent amount to be equal to the estimated price rounded times quantity");
1120
1121 };
1122
1123 sub _get_dependencies {
1124     my ($budget_hierarchy) = @_;
1125     my $graph;
1126     for my $budget (@$budget_hierarchy) {
1127         if ( $budget->{child} ) {
1128             my @sorted = sort @{ $budget->{child} };
1129             for my $child_id (@sorted) {
1130                 push @{ $graph->{ $budget->{budget_name} }{children} },
1131                   _get_budgetname_by_id( $budget_hierarchy, $child_id );
1132             }
1133         }
1134         push @{ $graph->{ $budget->{budget_name} }{parents} },
1135           $budget->{parent_id};
1136     }
1137     return $graph;
1138 }
1139
1140 sub _get_budgetname_by_id {
1141     my ( $budgets, $budget_id ) = @_;
1142     my ($budget_name) =
1143       map { ( $_->{budget_id} eq $budget_id ) ? $_->{budget_name} : () }
1144       @$budgets;
1145     return $budget_name;
1146 }