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