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