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