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