Bug 22042: [22.05.x] Block all return actions when BlockReturnOfWithdrawn items is...
[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 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
589 #Test skiptotals
590 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id, undef, undef, 1);
591 is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy skiptotals should return budgets ordered by name, first child is budget_11' );
592 is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy skiptotals should return budgets ordered by name, second child is budget_12' );
593 is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy skiptotals should return budgets ordered by name, first budget is budget_1');
594 is($budget_hierarchy->[0]->{budget_level},'0','skiptotals: budget_level of budget (budget_1)  should be 0');
595 is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','skiptotals: budget_level of first fund(budget_11)  should be 1');
596 is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','skiptotals: budget_level of second fund(budget_12)  should be 1');
597 is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','skiptotals: budget_level of  child fund budget_11 should be 2');
598
599 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
600 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
601 is( scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy),
602 'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)'
603 );
604 is_deeply(
605     _get_dependencies($budget_hierarchy),
606     _get_dependencies($budget_hierarchy_cloned),
607     'CloneBudgetPeriod (with inactive param) keeps the same dependencies order'
608 );
609 $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
610 is( $budget_period->{budget_period_active}, 0,
611     'CloneBudgetPeriod (with inactive param) marks as inactive the budgetperiod'
612 );
613
614 # CloneBudgetPeriod with param reset_all_budgets
615 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
616     {
617         budget_period_id        => $budget_period_id,
618         budget_period_startdate => '2014-01-01',
619         budget_period_enddate   => '2014-12-31',
620         reset_all_budgets         => 1,
621     }
622 );
623
624 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
625 $number_of_budgets_not_reset = 0;
626 for my $budget (@$budget_hierarchy_cloned) {
627     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
628 }
629 is( $number_of_budgets_not_reset, 0,
630     'CloneBudgetPeriod has reset all budgets (funds)' );
631
632 #GetBudgetsByActivity
633 my $result=C4::Budgets::GetBudgetsByActivity(1);
634 isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 1');
635 $result=C4::Budgets::GetBudgetsByActivity(0);
636  isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 0');
637 $result=C4::Budgets::GetBudgetsByActivity();
638  is( $result, 0 , 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' );
639 DelBudget($budget_id);
640 DelBudgetPeriod($bpid);
641
642 # CloneBudgetPeriod with param amount_change_*
643 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
644     {
645         budget_period_id        => $budget_period_id,
646         budget_period_startdate => '2014-01-01',
647         budget_period_enddate   => '2014-12-31',
648         amount_change_percentage => 16,
649         amount_change_round_increment => 5,
650     }
651 );
652
653 $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
654 cmp_ok($budget_period_cloned->{budget_period_total}, '==', 11600, "CloneBudgetPeriod changed correctly budget amount");
655 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
656 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, "CloneBudgetPeriod changed correctly funds amounts");
657 cmp_ok($budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
658 cmp_ok($budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts");
659 cmp_ok($budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
660 cmp_ok($budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, "CloneBudgetPeriod changed correctly funds amounts");
661 cmp_ok($budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts");
662
663 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
664     {
665         budget_period_id        => $budget_period_id,
666         budget_period_startdate => '2014-01-01',
667         budget_period_enddate   => '2014-12-31',
668         amount_change_percentage => 16,
669         amount_change_round_increment => 5,
670         reset_all_budgets => 1,
671     }
672 );
673 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
674 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts");
675
676 # MoveOrders
677 my $number_orders_moved = C4::Budgets::MoveOrders();
678 is( $number_orders_moved, undef, 'MoveOrders return undef if no arg passed' );
679 $number_orders_moved =
680   C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } );
681 is( $number_orders_moved, undef,
682     'MoveOrders return undef if only 1 arg passed' );
683 $number_orders_moved =
684   C4::Budgets::MoveOrders( { to_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 = C4::Budgets::MoveOrders(
688     {
689         from_budget_period_id => $budget_period_id,
690         to_budget_period_id   => $budget_period_id
691     }
692 );
693 is( $number_orders_moved, undef,
694     'MoveOrders return undef if 2 budget period id are the same' );
695
696 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
697     {
698         budget_period_id        => $budget_period_id,
699         budget_period_startdate => '2014-01-01',
700         budget_period_enddate   => '2014-12-31',
701     }
702 );
703
704 my $report = C4::Budgets::MoveOrders(
705     {
706         from_budget_period_id  => $budget_period_id,
707         to_budget_period_id    => $budget_period_id_cloned,
708         move_remaining_unspent => 1,
709     }
710 );
711 is( scalar( @$report ), 6 , "MoveOrders has processed 6 funds" );
712
713 my $number_of_orders_moved = 0;
714 $number_of_orders_moved += scalar( @{ $_->{orders_moved} } ) for @$report;
715 is( $number_of_orders_moved, $number_of_orders_to_move, "MoveOrders has moved $number_of_orders_to_move orders" );
716
717 my @new_budget_ids = map { $_->{budget_id} }
718   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
719 my @old_budget_ids = map { $_->{budget_id} }
720   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
721 for my $budget_id ( keys %budgets ) {
722     for my $ordernumber ( @{ $budgets{$budget_id} } ) {
723         my $budget            = GetBudgetByOrderNumber($ordernumber);
724         my $is_in_new_budgets = grep /^$budget->{budget_id}$/, @new_budget_ids;
725         my $is_in_old_budgets = grep /^$budget->{budget_id}$/, @old_budget_ids;
726         is( $is_in_new_budgets, 1, "MoveOrders changed the budget_id for order $ordernumber" );
727         is( $is_in_old_budgets, 0, "MoveOrders changed the budget_id for order $ordernumber" );
728     }
729 }
730
731
732 # MoveOrders with param move_remaining_unspent
733 my @new_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
734 my @old_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
735
736 for my $new_budget ( @new_budgets ) {
737     my ( $old_budget ) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets;
738     my $new_budget_amount_should_be = $old_budget->{budget_amount} * 2 - $old_budget->{total_spent};
739     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})" );
740 }
741
742 # Test SetOwnerToFundHierarchy
743
744 my $patron_category = $builder->build({ source => 'Category' });
745 my $branchcode = $library->{branchcode};
746 my $john_doe = Koha::Patron->new({
747     cardnumber   => '123456',
748     firstname    => 'John',
749     surname      => 'Doe',
750     categorycode => $patron_category->{categorycode},
751     branchcode   => $branchcode,
752     dateofbirth  => '',
753     dateexpiry   => '9999-12-31',
754     userid       => 'john.doe'
755 })->store->borrowernumber;
756
757 C4::Budgets::SetOwnerToFundHierarchy( $budget_id1, $john_doe );
758 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
759     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" );
760 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
761     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" );
762 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
763     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" );
764 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
765     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" );
766 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
767     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" );
768 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
769     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" );
770
771 my $jane_doe = Koha::Patron->new({
772     cardnumber   => '789012',
773     firstname    => 'Jane',
774     surname      => 'Doe',
775     categorycode => $patron_category->{categorycode},
776     branchcode   => $branchcode,
777     dateofbirth  => '',
778     dateexpiry   => '9999-12-31',
779     userid       => 'jane.doe'
780 })->store->borrowernumber;
781
782 C4::Budgets::SetOwnerToFundHierarchy( $budget_id11, $jane_doe );
783 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
784     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" );
785 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
786     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" );
787 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
788     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" );
789 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
790     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" );
791 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
792     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" );
793 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
794     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" );
795
796 # Test GetBudgetAuthCats
797
798 my $budgetPeriodId = AddBudgetPeriod({
799     budget_period_startdate   => '2008-01-01',
800     budget_period_enddate     => '2008-12-31',
801     budget_period_description => 'just another budget',
802     budget_period_active      => 0,
803 });
804
805 $budgets = GetBudgets();
806 my $i = 0;
807 for my $budget ( @$budgets )
808 {
809     $budget->{sort1_authcat} = "sort1_authcat_$i";
810     $budget->{sort2_authcat} = "sort2_authcat_$i";
811     $budget->{budget_period_id} = $budgetPeriodId;
812     ModBudget( $budget );
813     $i++;
814 }
815
816 my $authCat = GetBudgetAuthCats($budgetPeriodId);
817
818 is( scalar @{$authCat}, $i * 2, "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" );
819
820 $i = 0;
821 for my $budget ( @$budgets )
822 {
823     $budget->{sort1_authcat} = "sort_authcat_$i";
824     $budget->{sort2_authcat} = "sort_authcat_$i";
825     $budget->{budget_period_id} = $budgetPeriodId;
826     ModBudget( $budget );
827     $i++;
828 }
829
830 $authCat = GetBudgetAuthCats($budgetPeriodId);
831 is( scalar @$authCat, scalar @$budgets, "GetBudgetAuthCats returns distinct authCat" );
832
833 $i = 0;
834 for my $budget ( @$budgets )
835 {
836     $budget->{sort1_authcat} = "sort1_authcat_$i";
837     $budget->{sort2_authcat} = "";
838     $budget->{budget_period_id} = $budgetPeriodId;
839     ModBudget( $budget );
840     $i++;
841 }
842
843 $authCat = GetBudgetAuthCats($budgetPeriodId);
844
845 is( scalar @{$authCat}, $i, "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" );
846
847 $i = 0;
848 for my $budget ( @$budgets )
849 {
850     $budget->{sort1_authcat} = "";
851     $budget->{sort2_authcat} = "";
852     $budget->{budget_period_id} = $budgetPeriodId;
853     ModBudget( $budget );
854     $i++;
855 }
856
857 $authCat = GetBudgetAuthCats($budgetPeriodId);
858
859 is( scalar @{$authCat}, 0, "GetBudgetAuthCats returns only non-empty sorting categories (all empty)" );
860
861 # /Test GetBudgetAuthCats
862
863 subtest 'GetBudgetSpent and GetBudgetOrdered and GetBudgetHierarchy shipping and adjustments' => sub {
864     plan tests => 26;
865
866     my $budget_period = $builder->build({
867         source => 'Aqbudgetperiod',
868         value  => {
869             budget_period_active => 1,
870             budget_total => 10000,
871         }
872     });
873     my $budget = $builder->build({
874         source => 'Aqbudget',
875         value  => {
876             budget_amount => 1000,
877             budget_encumb => undef,
878             budget_expend => undef,
879             budget_period_id => $budget_period->{budget_period_id},
880             budget_parent_id => undef,
881         }
882     });
883     my $invoice = $builder->build({
884         source => 'Aqinvoice',
885         value  => {
886             closedate => undef,
887         }
888     });
889
890     my $spent     = GetBudgetSpent( $budget->{budget_id} );
891     my $ordered   = GetBudgetOrdered( $budget->{budget_id} );
892     my $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
893
894     is( $spent, 0, "New budget, no orders/invoices, should be nothing spent");
895     is( $ordered, 0, "New budget, no orders/invoices, should be nothing ordered");
896     is( @$hierarchy[0]->{total_spent},0,"New budgets, no orders/invoices, budget hierarchy shows 0 spent");
897     is( @$hierarchy[0]->{total_ordered},0,"New budgets, no orders/invoices, budget hierarchy shows 0 ordered");
898
899     my $inv_adj_1 = $builder->build({
900         source => 'AqinvoiceAdjustment',
901         value  => {
902             invoiceid     => $invoice->{invoiceid},
903             adjustment    => 3,
904             encumber_open => 0,
905             budget_id     => $budget->{budget_id},
906         }
907     });
908
909     $spent = GetBudgetSpent( $budget->{budget_id} );
910     $ordered = GetBudgetOrdered( $budget->{budget_id} );
911     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
912     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
913     is( $ordered, 0, "After adding invoice adjustment on open invoice not encumbered, should be nothing ordered");
914     is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 spent");
915     is( @$hierarchy[0]->{total_ordered},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 ordered");
916
917     my $inv_adj_2 = $builder->build({
918         source => 'AqinvoiceAdjustment',
919         value  => {
920             invoiceid     => $invoice->{invoiceid},
921             adjustment    => 3,
922             encumber_open => 1,
923             budget_id     => $budget->{budget_id},
924         }
925     });
926
927     $spent = GetBudgetSpent( $budget->{budget_id} );
928     $ordered = GetBudgetOrdered( $budget->{budget_id} );
929     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
930     is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent");
931     is( $ordered, 3, "After adding invoice adjustment on open invoice encumbered, should be 3 ordered");
932     is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 0 spent");
933     is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 3 ordered");
934
935     my $invoice_2 = $builder->build({
936         source => 'Aqinvoice',
937         value  => {
938             closedate => '2017-07-01',
939         }
940     });
941     my $inv_adj_3 = $builder->build({
942         source => 'AqinvoiceAdjustment',
943         value  => {
944             invoiceid     => $invoice_2->{invoiceid},
945             adjustment    => 3,
946             encumber_open => 0,
947             budget_id     => $budget->{budget_id},
948         }
949     });
950     my $inv_adj_4 = $builder->build({
951         source => 'AqinvoiceAdjustment',
952         value  => {
953             invoiceid     => $invoice_2->{invoiceid},
954             adjustment    => 3,
955             encumber_open => 1,
956             budget_id     => $budget->{budget_id},
957         }
958     });
959
960     $spent = GetBudgetSpent( $budget->{budget_id} );
961     $ordered = GetBudgetOrdered( $budget->{budget_id} );
962     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
963     is( $spent, 6, "After adding invoice adjustment on closed invoice, should be 6 spent, encumber has no affect once closed");
964     is( $ordered, 3, "After adding invoice adjustment on closed invoice, should still be 3 ordered");
965     is( @$hierarchy[0]->{total_spent},6,"After adding invoice adjustment on closed invoice, budget hierarchy shows 6 spent");
966     is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on closed invoice, budget hierarchy still shows 3 ordered");
967
968     my $budget0 = $builder->build({
969         source => 'Aqbudget',
970         value  => {
971             budget_amount => 1000,
972             budget_encumb => undef,
973             budget_expend => undef,
974             budget_period_id => $budget_period->{budget_period_id},
975             budget_parent_id => $budget->{budget_id},
976         }
977     });
978     my $inv_adj_5 = $builder->build({
979         source => 'AqinvoiceAdjustment',
980         value  => {
981             invoiceid     => $invoice->{invoiceid},
982             adjustment    => 3,
983             encumber_open => 1,
984             budget_id     => $budget0->{budget_id},
985         }
986     });
987     my $inv_adj_6 = $builder->build({
988         source => 'AqinvoiceAdjustment',
989         value  => {
990             invoiceid     => $invoice_2->{invoiceid},
991             adjustment    => 3,
992             encumber_open => 1,
993             budget_id     => $budget0->{budget_id},
994         }
995     });
996
997     $spent = GetBudgetSpent( $budget->{budget_id} );
998     $ordered = GetBudgetOrdered( $budget->{budget_id} );
999     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
1000     is( $spent, 6, "After adding invoice adjustment on a child budget should be 6 spent/budget unaffected");
1001     is( $ordered, 3, "After adding invoice adjustment on a child budget, should still be 3 ordered/budget unaffected");
1002     is( @$hierarchy[0]->{total_spent},9,"After adding invoice adjustment on child budget, budget hierarchy shows 9 spent");
1003     is( @$hierarchy[0]->{total_ordered},6,"After adding invoice adjustment on child budget, budget hierarchy shows 6 ordered");
1004
1005     my $invoice_3 = $builder->build({
1006         source => 'Aqinvoice',
1007         value  => {
1008             closedate => '2017-07-01',
1009             shipmentcost_budgetid => $budget0->{budget_id},
1010             shipmentcost           => 1.25
1011         }
1012     });
1013     my $invoice_4 = $builder->build({
1014         source => 'Aqinvoice',
1015         value  => {
1016             closedate => undef,
1017             shipmentcost_budgetid => $budget0->{budget_id},
1018             shipmentcost           => 1.75
1019         }
1020     });
1021
1022     $spent = GetBudgetSpent( $budget->{budget_id} );
1023     $ordered = GetBudgetOrdered( $budget->{budget_id} );
1024     is( $spent, 6, "After adding invoice shipment cost on open and closed invoice on child, neither are counted as spent from parent");
1025     is( $ordered, 3, "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from parent");
1026     $spent = GetBudgetSpent( $budget0->{budget_id} );
1027     $ordered = GetBudgetOrdered( $budget0->{budget_id} );
1028     is( $spent, 6, "After adding invoice shipment cost on open and closed invoice on child, both are counted as spent from child");
1029     is( $ordered, 3, "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from child");
1030     $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} );
1031     is( @$hierarchy[0]->{total_spent},12,"After adding shipmentcost on child, budget hierarchy shows 12 spent total");
1032     is( @$hierarchy[0]->{total_ordered},6,"After adding shipmentcost on child, budget hierarchy still shows 6 ordered total");
1033
1034
1035 };
1036
1037 subtest 'GetBudgetSpent GetBudgetOrdered GetBudgetsPlanCell tests' => sub {
1038
1039     plan tests => 24;
1040
1041 #Let's build an order, we need a couple things though
1042     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1043
1044     my $item_1         = $builder->build_sample_item;
1045     my $spent_basket   = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
1046     my $spent_invoice  = $builder->build({ source => 'Aqinvoice'});
1047     my $spent_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' }  });
1048     my $spent_vendor   = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $spent_currency->{currency}, invoiceprice => $spent_currency->{currency} } });
1049     my $budget_authcat = $builder->build({ source => 'AuthorisedValueCategory', value => {} });
1050     my $spent_sort1    = $builder->build({ source => 'AuthorisedValue', value => {
1051             category => $budget_authcat->{category_name},
1052             authorised_value => 'PICKLE',
1053         }
1054     });
1055     my $spent_budget_period = $builder->build({ source => 'Aqbudgetperiod', value => {
1056         }
1057     });
1058     my $spent_budget = $builder->build({ source => 'Aqbudget', value => {
1059             sort1_authcat => $budget_authcat->{category_name},
1060             budget_period_id => $spent_budget_period->{budget_period_id},
1061             budget_parent_id => undef,
1062         }
1063     });
1064     my $spent_orderinfo = {
1065         basketno                => $spent_basket->{basketno},
1066         booksellerid            => $spent_vendor->{id},
1067         rrp                     => 16.99,
1068         discount                => .42,
1069         ecost                   => 16.91,
1070         biblionumber            => $item_1->biblionumber,
1071         currency                => $spent_currency->{currency},
1072         tax_rate_on_ordering    => 0,
1073         tax_value_on_ordering   => 0,
1074         tax_rate_on_receiving   => 0,
1075         tax_value_on_receiving  => 0,
1076         quantity                => 8,
1077         quantityreceived        => 0,
1078         datecancellationprinted => undef,
1079         datereceived            => undef,
1080         budget_id               => $spent_budget->{budget_id},
1081         sort1                   => $spent_sort1->{authorised_value},
1082     };
1083
1084 #Okay we have basically what the user would enter, now we do some maths
1085
1086     $spent_orderinfo = C4::Acquisition::populate_order_with_prices({
1087             order        => $spent_orderinfo,
1088             booksellerid => $spent_orderinfo->{booksellerid},
1089             ordering     => 1,
1090     });
1091
1092 #And let's place the order
1093
1094     my $spent_order = $builder->build({ source => 'Aqorder', value => $spent_orderinfo });
1095     t::lib::Mocks::mock_preference('OrderPriceRounding','');
1096     my $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} );
1097
1098     is($spent_orderinfo->{ecost_tax_excluded}, 9.854200,'We store extra precision in price calculation');
1099     is( Koha::Number::Price->new($spent_orderinfo->{ecost_tax_excluded})->format(), 9.85,'But the price as formatted is two digits');
1100     is($spent_ordered,'78.8336',"We expect the ordered amount to be equal to the estimated price times quantity with full precision");
1101
1102     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1103     $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} );
1104     is($spent_ordered,'78.8',"We expect the ordered amount to be equal to the estimated price rounded times quantity");
1105
1106     #Test GetBudgetHierarchy for rounding
1107     t::lib::Mocks::mock_preference('OrderPriceRounding','');
1108     my $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id});
1109     is ( @$gbh[0]->{budget_spent}+0, 0, "We expect this to be an exact order cost * quantity");
1110     is ( @$gbh[0]->{budget_ordered}+0, 78.8336, "We expect this to be an exact order cost * quantity");
1111     t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1112     $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id});
1113     is ( @$gbh[0]->{budget_spent}+0, 0, "We expect this to be an rounded order cost * quantity");
1114     is ( @$gbh[0]->{budget_ordered}+0, 78.8, "We expect this to be an exact order cost * quantity");
1115
1116 #Let's test some budget planning
1117 #Regression tests for bug 18736
1118     #We need an item to test by BRANCHES
1119     my $order_item_1 = $builder->build({ source => 'AqordersItem', value => { ordernumber => $spent_order->{ordernumber}, itemnumber => $item_1->itemnumber  } });
1120     my $spent_fund = Koha::Acquisition::Funds->find( $spent_order->{budget_id} );
1121     my $cell = {
1122         authcat => 'MONTHS',
1123         cell_authvalue => $spent_order->{entrydate}, #normally this is just the year/month but full won't hurt us here
1124         budget_id => $spent_order->{budget_id},
1125         budget_period_id => $spent_fund->budget_period_id,
1126         sort1_authcat => $spent_order->{sort1_authcat},
1127         sort2_authcat => $spent_order->{sort1_authcat},
1128     };
1129     my $test_values = {
1130         'MONTHS' => {
1131             authvalue => $spent_order->{entrydate},
1132             expected_rounded => 9.85,
1133             expected_exact   => 9.8542,
1134         },
1135         'BRANCHES' => {
1136             authvalue => $item_1->homebranch,
1137             expected_rounded => 9.85,
1138             expected_exact   => 9.8542,
1139         },
1140         'ITEMTYPES' => {
1141             authvalue => $item_1->biblioitem->itemtype,
1142             expected_rounded => 78.80,
1143             expected_exact   => 78.8336,
1144         },
1145         'ELSE' => {
1146             authvalue => $spent_sort1->{authorised_value},
1147             expected_rounded => 78.8,
1148             expected_exact   => 78.8336,
1149         },
1150     };
1151
1152     for my $authcat ( keys %$test_values ) {
1153         my $test_val         = $test_values->{$authcat};
1154         my $authvalue        = $test_val->{authvalue};
1155         my $expected_rounded = $test_val->{expected_rounded};
1156         my $expected_exact   = $test_val->{expected_exact};
1157         $cell->{authcat} = $authcat;
1158         $cell->{authvalue} = $authvalue;
1159         t::lib::Mocks::mock_preference('OrderPriceRounding','');
1160         my ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now
1161         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
1162         t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent');
1163         ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now
1164         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
1165     }
1166
1167 #Okay, now we can receive the order, giving the price as the user would
1168
1169     $spent_orderinfo->{unitprice} = 9.85; #we are paying what we expected
1170
1171 #Do our maths
1172
1173     $spent_orderinfo = C4::Acquisition::populate_order_with_prices({
1174             order        => $spent_orderinfo,
1175             booksellerid => $spent_orderinfo->{booksellerid},
1176             receiving    => 1,
1177     });
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 }