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