Bug 21604: Add two trivial test cases
[koha.git] / t / db_dependent / Budgets.t
1 #!/usr/bin/perl
2 use Modern::Perl;
3 use Test::More tests => 145;
4
5 BEGIN {
6     use_ok('C4::Budgets')
7 }
8 use C4::Context;
9 use C4::Biblio;
10 use C4::Acquisition;
11 use C4::Members qw( AddMember );
12
13 use Koha::Acquisition::Booksellers;
14 use Koha::Acquisition::Orders;
15 use Koha::Acquisition::Funds;
16 use Koha::Patrons;
17
18 use t::lib::TestBuilder;
19 use Koha::DateUtils;
20
21 use YAML;
22
23 my $schema  = Koha::Database->new->schema;
24 $schema->storage->txn_begin;
25 my $builder = t::lib::TestBuilder->new;
26 my $dbh = C4::Context->dbh;
27 $dbh->do(q|DELETE FROM aqbudgetperiods|);
28 $dbh->do(q|DELETE FROM aqbudgets|);
29
30 my $library = $builder->build({
31     source => 'Branch',
32 });
33
34 # Mock userenv
35 local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ };
36 my $userenv;
37 *C4::Context::userenv = \&Mock_userenv;
38 $userenv = { flags => 1, id => 'my_userid', branch => $library->{branchcode} };
39
40 #
41 # Budget Periods :
42 #
43
44 is( AddBudgetPeriod(), undef, 'AddBugetPeriod without argument returns undef' );
45 is( AddBudgetPeriod( { }  ), undef, 'AddBugetPeriod with an empty argument returns undef' );
46 my $bpid = AddBudgetPeriod({
47     budget_period_startdate => '2008-01-01',
48 });
49 is( $bpid, undef, 'AddBugetPeriod without end date returns undef' );
50 $bpid = AddBudgetPeriod({
51     budget_period_enddate => '2008-12-31',
52 });
53 is( $bpid, undef, 'AddBugetPeriod without start date returns undef' );
54 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
55 my $budgetperiods = GetBudgetPeriods();
56 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
57
58 my $my_budgetperiod = {
59     budget_period_startdate   => '2008-01-01',
60     budget_period_enddate     => '2008-12-31',
61     budget_period_description => 'MAPERI',
62     budget_period_active      => 0,
63     budget_period_id          => '', # Bug 21604
64 };
65 $bpid = AddBudgetPeriod($my_budgetperiod);
66 isnt( $bpid, undef, 'AddBugetPeriod does not returns undef' );
67 my $budgetperiod = GetBudgetPeriod($bpid);
68 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'AddBudgetPeriod stores the start date correctly' );
69 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'AddBudgetPeriod stores the end date correctly' );
70 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'AddBudgetPeriod stores the description correctly' );
71 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'AddBudgetPeriod stores active correctly' );
72 is( GetBudgetPeriod(0), undef ,'GetBudgetPeriod(0) returned undef : noactive BudgetPeriod' );
73
74
75 $my_budgetperiod = {
76     budget_period_startdate   => '2009-01-01',
77     budget_period_enddate     => '2009-12-31',
78     budget_period_description => 'MODIF_MAPERI',
79     budget_period_active      => 1,
80 };
81 my $mod_status = ModBudgetPeriod($my_budgetperiod);
82 is( $mod_status, undef, 'ModBudgetPeriod without id returns undef' );
83
84 $my_budgetperiod->{budget_period_id} = $bpid;
85 $mod_status = ModBudgetPeriod($my_budgetperiod);
86 is( $mod_status, 1, 'ModBudgetPeriod returnis true' );
87 $budgetperiod = GetBudgetPeriod($bpid);
88 is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'ModBudgetPeriod updates the start date correctly' );
89 is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'ModBudgetPeriod updates the end date correctly' );
90 is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'ModBudgetPeriod updates the description correctly' );
91 is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'ModBudgetPeriod upates active correctly' );
92 isnt( GetBudgetPeriod(0), undef, 'GetBugetPeriods functions correctly' );
93
94
95 $budgetperiods = GetBudgetPeriods();
96 is( @$budgetperiods, 1, 'GetBudgetPeriods returns the correct number of budget periods' );
97 is( $budgetperiods->[0]->{budget_period_id}, $my_budgetperiod->{budget_period_id}, 'GetBudgetPeriods returns the id correctly' );
98 is( $budgetperiods->[0]->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'GetBudgetPeriods returns the start date correctly' );
99 is( $budgetperiods->[0]->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'GetBudgetPeriods returns the end date correctly' );
100 is( $budgetperiods->[0]->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'GetBudgetPeriods returns the description correctly' );
101 is( $budgetperiods->[0]->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'GetBudgetPeriods returns active correctly' );
102
103 is( DelBudgetPeriod($bpid), 1, 'DelBudgetPeriod returns true' );
104 $budgetperiods = GetBudgetPeriods();
105 is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' );
106
107
108 #
109 # Budget  :
110 #
111
112 # The budget hierarchy will be:
113 # budget_1
114 #   budget_11
115 #     budget_111
116 #   budget_12
117 # budget_2
118 #   budget_21
119
120 is( AddBudget(), undef, 'AddBuget without argument returns undef' );
121 my $budgets = GetBudgets();
122 is( @$budgets, 0, 'GetBudgets returns the correct number of budgets' );
123
124 $bpid = AddBudgetPeriod($my_budgetperiod); #this is an active budget
125
126 my $my_budget = {
127     budget_code      => 'ABCD',
128     budget_amount    => '123.132000',
129     budget_name      => 'Periodiques',
130     budget_notes     => 'This is a note',
131     budget_period_id => $bpid,
132     budget_encumb    => '', # Bug 21604
133 };
134 my $budget_id = AddBudget($my_budget);
135 isnt( $budget_id, undef, 'AddBudget does not returns undef' );
136 my $budget = GetBudget($budget_id);
137 is( $budget->{budget_code}, $my_budget->{budget_code}, 'AddBudget stores the budget code correctly' );
138 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'AddBudget stores the budget amount correctly' );
139 is( $budget->{budget_name}, $my_budget->{budget_name}, 'AddBudget stores the budget name correctly' );
140 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'AddBudget stores the budget notes correctly' );
141 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'AddBudget stores the budget period id correctly' );
142
143
144 $my_budget = {
145     budget_code      => 'EFG',
146     budget_amount    => '321.231000',
147     budget_name      => 'Modified name',
148     budget_notes     => 'This is a modified note',
149     budget_period_id => $bpid,
150 };
151 $mod_status = ModBudget($my_budget);
152 is( $mod_status, undef, 'ModBudget without id returns undef' );
153
154 $my_budget->{budget_id} = $budget_id;
155 $mod_status = ModBudget($my_budget);
156 is( $mod_status, 1, 'ModBudget returns true' );
157 $budget = GetBudget($budget_id);
158 is( $budget->{budget_code}, $my_budget->{budget_code}, 'ModBudget updates the budget code correctly' );
159 is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'ModBudget updates the budget amount correctly' );
160 is( $budget->{budget_name}, $my_budget->{budget_name}, 'ModBudget updates the budget name correctly' );
161 is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'ModBudget updates the budget notes correctly' );
162 is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'ModBudget updates the budget period id correctly' );
163
164
165 $budgets = GetBudgets();
166 is( @$budgets, 1, 'GetBudgets returns the correct number of budgets' );
167 is( $budgets->[0]->{budget_id}, $my_budget->{budget_id}, 'GetBudgets returns the budget id correctly' );
168 is( $budgets->[0]->{budget_code}, $my_budget->{budget_code}, 'GetBudgets returns the budget code correctly' );
169 is( $budgets->[0]->{budget_amount}, $my_budget->{budget_amount}, 'GetBudgets returns the budget amount correctly' );
170 is( $budgets->[0]->{budget_name}, $my_budget->{budget_name}, 'GetBudgets returns the budget name correctly' );
171 is( $budgets->[0]->{budget_notes}, $my_budget->{budget_notes}, 'GetBudgets returns the budget notes correctly' );
172 is( $budgets->[0]->{budget_period_id}, $my_budget->{budget_period_id}, 'GetBudgets returns the budget period id correctly' );
173
174 $budgets = GetBudgets( {budget_period_id => $bpid} );
175 is( @$budgets, 1, 'GetBudgets With Filter OK' );
176 $budgets = GetBudgets( {budget_period_id => $bpid}, {-asc => "budget_name"} );
177 is( @$budgets, 1, 'GetBudgets With Order OK' );
178 $budgets = GetBudgets( {budget_period_id => GetBudgetPeriod($bpid)->{budget_period_id}}, {-asc => "budget_name"} );
179 is( @$budgets, 1, 'GetBudgets With Order Getting Active budgetPeriod OK');
180
181
182 my $budget_name = GetBudgetName( $budget_id );
183 is($budget_name, $my_budget->{budget_name}, "Test the GetBudgetName routine");
184
185 my $my_inactive_budgetperiod = { #let's add an inactive
186     budget_period_startdate   => '2010-01-01',
187     budget_period_enddate     => '2010-12-31',
188     budget_period_description => 'MODIF_MAPERI',
189     budget_period_active      => 0,
190 };
191 my $bpid_i = AddBudgetPeriod($my_inactive_budgetperiod); #this is an inactive budget
192
193 my $my_budget_inactive = {
194     budget_code      => 'EFG',
195     budget_amount    => '123.132000',
196     budget_name      => 'Periodiques',
197     budget_notes     => 'This is a note',
198     budget_period_id => $bpid_i,
199 };
200 my $budget_id_inactive = AddBudget($my_budget_inactive);
201
202 my $budget_code = $my_budget->{budget_code};
203 my $budget_by_code = GetBudgetByCode( $budget_code );
204 is($budget_by_code->{budget_id}, $budget_id, "GetBudgetByCode, check id"); #this should match the active budget, not the inactive
205 is($budget_by_code->{budget_notes}, $my_budget->{budget_notes}, "GetBudgetByCode, check notes");
206
207 my $second_budget_id = AddBudget({
208     budget_code      => "ZZZZ",
209     budget_amount    => "500.00",
210     budget_name      => "Art",
211     budget_notes     => "This is a note",
212     budget_period_id => $bpid,
213 });
214 isnt( $second_budget_id, undef, 'AddBudget does not returns undef' );
215
216 $budgets = GetBudgets( {budget_period_id => $bpid} );
217 ok( $budgets->[0]->{budget_name} lt $budgets->[1]->{budget_name}, 'default sort order for GetBudgets is by name' );
218
219 is( DelBudget($budget_id), 1, 'DelBudget returns true' );
220 $budgets = GetBudgets();
221 is( @$budgets, 2, 'GetBudgets returns the correct number of budget periods' );
222
223
224 # GetBudgetHierarchySpent and GetBudgetHierarchyOrdered
225 my $budget_period_total = 10_000;
226 my $budget_1_total = 1_000;
227 my $budget_11_total = 100;
228 my $budget_111_total = 50;
229 my $budget_12_total = 100;
230 my $budget_2_total = 2_000;
231
232 my $budget_period_id = AddBudgetPeriod(
233     {
234         budget_period_startdate   => '2013-01-01',
235         budget_period_enddate     => '2014-12-31',
236         budget_period_description => 'Budget Period',
237         budget_period_active      => 1,
238         budget_period_total       => $budget_period_total,
239     }
240 );
241 my $budget_id1 = AddBudget(
242     {
243         budget_code      => 'budget_1',
244         budget_name      => 'budget_1',
245         budget_period_id => $budget_period_id,
246         budget_parent_id => undef,
247         budget_amount    => $budget_1_total,
248     }
249 );
250 my $budget_id2 = AddBudget(
251     {
252         budget_code      => 'budget_2',
253         budget_name      => 'budget_2',
254         budget_period_id => $budget_period_id,
255         budget_parent_id => undef,
256         budget_amount    => $budget_2_total,
257     }
258 );
259 my $budget_id12 = AddBudget(
260     {
261         budget_code      => 'budget_12',
262         budget_name      => 'budget_12',
263         budget_period_id => $budget_period_id,
264         budget_parent_id => $budget_id1,
265         budget_amount    => $budget_12_total,
266     }
267 );
268 my $budget_id11 = AddBudget(
269     {
270         budget_code      => 'budget_11',
271         budget_name      => 'budget_11',
272         budget_period_id => $budget_period_id,
273         budget_parent_id => $budget_id1,
274         budget_amount    => $budget_11_total,
275     }
276 );
277 my $budget_id111 = AddBudget(
278     {
279         budget_code      => 'budget_111',
280         budget_name      => 'budget_111',
281         budget_period_id => $budget_period_id,
282         budget_parent_id => $budget_id11,
283         budget_owner_id  => 1,
284         budget_amount    => $budget_111_total,
285     }
286 );
287 my $budget_id21 = AddBudget(
288     {
289         budget_code      => 'budget_21',
290         budget_name      => 'budget_21',
291         budget_period_id => $budget_period_id,
292         budget_parent_id => $budget_id2,
293     }
294 );
295
296 my $bookseller = Koha::Acquisition::Bookseller->new(
297     {
298         name         => "my vendor",
299         address1     => "bookseller's address",
300         phone        => "0123456",
301         active       => 1,
302         deliverytime => 5,
303     }
304 )->store;
305 my $booksellerid = $bookseller->id;
306
307 my $basketno = C4::Acquisition::NewBasket( $booksellerid, 1 );
308 my ( $biblionumber, $biblioitemnumber ) =
309   C4::Biblio::AddBiblio( MARC::Record->new, '' );
310
311 my @order_infos = (
312     {
313         budget_id => $budget_id1,
314         pending_quantity  => 1,
315         spent_quantity  => 0,
316     },
317     {
318         budget_id => $budget_id2,
319         pending_quantity  => 2,
320         spent_quantity  => 1,
321     },
322     {
323         budget_id => $budget_id11,
324         pending_quantity  => 3,
325         spent_quantity  => 4,
326     },
327     {
328         budget_id => $budget_id12,
329         pending_quantity  => 4,
330         spent_quantity  => 3,
331     },
332     {
333         budget_id => $budget_id111,
334         pending_quantity  => 2,
335         spent_quantity  => 1,
336     },
337
338     # No order for budget_21
339
340 );
341
342 my %budgets;
343 my $invoiceid = AddInvoice(invoicenumber => 'invoice_test_clone', booksellerid => $booksellerid, unknown => "unknown");
344 my $invoice = GetInvoice( $invoiceid );
345 my $item_price = 10;
346 my $item_quantity = 2;
347 my $number_of_orders_to_move = 0;
348 for my $infos (@order_infos) {
349     for ( 1 .. $infos->{pending_quantity} ) {
350         my $order = Koha::Acquisition::Order->new(
351             {
352                 basketno           => $basketno,
353                 biblionumber       => $biblionumber,
354                 budget_id          => $infos->{budget_id},
355                 order_internalnote => "internal note",
356                 order_vendornote   => "vendor note",
357                 quantity           => 2,
358                 cost_tax_included  => $item_price,
359                 rrp_tax_included   => $item_price,
360                 listprice          => $item_price,
361                 ecost_tax_include  => $item_price,
362                 discount           => 0,
363                 uncertainprice     => 0,
364             }
365         )->store;
366         my $ordernumber = $order->ordernumber;
367         push @{ $budgets{$infos->{budget_id}} }, $ordernumber;
368         $number_of_orders_to_move++;
369     }
370     for ( 1 .. $infos->{spent_quantity} ) {
371         my $order = Koha::Acquisition::Order->new(
372             {
373                 basketno           => $basketno,
374                 biblionumber       => $biblionumber,
375                 budget_id          => $infos->{budget_id},
376                 order_internalnote => "internal note",
377                 order_vendornote   => "vendor note",
378                 quantity           => $item_quantity,
379                 cost               => $item_price,
380                 rrp_tax_included   => $item_price,
381                 listprice          => $item_price,
382                 ecost_tax_included => $item_price,
383                 discount           => 0,
384                 uncertainprice     => 0,
385             }
386         )->store;
387         my $ordernumber = $order->ordernumber;
388         ModReceiveOrder({
389               biblionumber     => $biblionumber,
390               order            => $order->unblessed,
391               budget_id        => $infos->{budget_id},
392               quantityreceived => $item_quantity,
393               invoice          => $invoice,
394               received_items   => [],
395         } );
396     }
397 }
398 is( GetBudgetHierarchySpent( $budget_id1 ), 160, "total spent for budget1 is 160" );
399 is( GetBudgetHierarchySpent( $budget_id11 ), 100, "total spent for budget11 is 100" );
400 is( GetBudgetHierarchySpent( $budget_id111 ), 20, "total spent for budget111 is 20" );
401
402 # GetBudgetSpent and GetBudgetOrdered
403 my $budget_period_amount = 100;
404 my $budget_amount = 50;
405
406 $budget = AddBudgetPeriod(
407     {
408         budget_period_startdate   => '2017-08-22',
409         budget_period_enddate     => '2018-08-22',
410         budget_period_description => 'Test budget',
411         budget_period_active      => 1,
412         budget_period_total       => $budget_period_amount,
413     }
414 );
415
416 my $fund = AddBudget(
417     {
418         budget_code       => 'Test fund',
419         budget_name       => 'Test fund',
420         budget_period_id  => $budget,
421         budget_parent_id  => undef,
422         budget_amount     => $budget_amount,
423     }
424 );
425
426 my $vendor = Koha::Acquisition::Bookseller->new(
427     {
428         name         => "test vendor",
429         address1     => "test address",
430         phone        => "0123456",
431         active       => 1,
432         deliverytime => 5,
433     }
434 )->store;
435
436 my $vendorid = $vendor->id;
437
438 my $basketnumber = C4::Acquisition::NewBasket( $vendorid, 1 );
439 my ( $biblio, $biblioitem ) = C4::Biblio::AddBiblio( MARC::Record->new, '' );
440
441 my @orders = (
442     {
443         budget_id  => $fund,
444         pending_quantity => 1,
445         spent_quantity => 0,
446     },
447 );
448
449 my $invoiceident = AddInvoice( invoicenumber => 'invoice_test_clone', booksellerid => $vendorid, shipmentdate => '2017-08-22', shipmentcost => 6, shipmentcost_budgetid => $fund );
450 my $test_invoice = GetInvoice( $invoiceident );
451 my $individual_item_price = 10;
452
453 my $order = Koha::Acquisition::Order->new(
454    {
455       basketno           => $basketnumber,
456       biblionumber       => $biblio,
457       budget_id          => $fund,
458       order_internalnote => "internalnote",
459       order_vendornote   => "vendor note",
460       quantity           => 2,
461       cost_tax_included  => $individual_item_price,
462       rrp_tax_included   => $individual_item_price,
463       listprice          => $individual_item_price,
464       ecost_tax_included => $individual_item_price,
465       discount           => 0,
466       uncertainprice     => 0,
467    }
468 )->store;
469
470 ModReceiveOrder({
471    bibionumber       => $biblio,
472    order             => $order->unblessed,
473    budget_id         => $fund,
474    quantityreceived  => 2,
475    invoice           => $test_invoice,
476    received_items    => [],
477 } );
478
479 is ( GetBudgetSpent( $fund ), 6, "total shipping cost is 6");
480 is ( GetBudgetOrdered( $fund ), '20.000000', "total ordered price is 20");
481
482
483 # CloneBudgetPeriod
484 # Let's make sure our timestamp is old
485 my @orig_funds = Koha::Acquisition::Funds->search({ budget_period_id => $budget_period_id });
486 foreach my $fund (@orig_funds){
487     $fund->timestamp('1999-12-31 23:59:59')->store;
488 }
489
490 my $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
491     {
492         budget_period_id        => $budget_period_id,
493         budget_period_startdate => '2014-01-01',
494         budget_period_enddate   => '2014-12-31',
495         budget_period_description => 'Budget Period Cloned',
496     }
497 );
498
499 my $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
500 is($budget_period_cloned->{budget_period_description}, 'Budget Period Cloned', 'Cloned budget\'s description is updated.');
501
502 my $budget_cloned = C4::Budgets::GetBudgets({ budget_period_id => $budget_period_id_cloned });
503 my $budget_time =  $budget_cloned->[0]->{timestamp};
504
505 isnt($budget_time, '1999-12-31 23:59:59', "New budget has an updated timestamp");
506
507
508
509 my $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
510 my $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
511
512 is(
513     scalar(@$budget_hierarchy_cloned),
514     scalar(@$budget_hierarchy),
515     'CloneBudgetPeriod clones the same number of budgets (funds)'
516 );
517 is_deeply(
518     _get_dependencies($budget_hierarchy),
519     _get_dependencies($budget_hierarchy_cloned),
520     'CloneBudgetPeriod keeps the same dependencies order'
521 );
522
523 # CloneBudgetPeriod with param mark_original_budget_as_inactive
524 my $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
525 is( $budget_period->{budget_period_active}, 1,
526     'CloneBudgetPeriod does not mark as inactive the budgetperiod if not needed'
527 );
528
529 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
530 my $number_of_budgets_not_reset = 0;
531 for my $budget (@$budget_hierarchy_cloned) {
532     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
533 }
534 is( $number_of_budgets_not_reset, 5,
535     'CloneBudgetPeriod does not reset budgets (funds) if not needed' );
536
537 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
538     {
539         budget_period_id                 => $budget_period_id,
540         budget_period_startdate          => '2014-01-01',
541         budget_period_enddate            => '2014-12-31',
542         mark_original_budget_as_inactive => 1,
543     }
544 );
545
546 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
547 is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy should return budgets ordered by name, first child is budget_11' );
548 is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy should return budgets ordered by name, second child is budget_12' );
549 is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy should return budgets ordered by name, first budget is budget_1');
550 is($budget_hierarchy->[0]->{budget_level},'0','budget_level of budget (budget_1)  should be 0');
551 is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','budget_level of first fund(budget_11)  should be 1');
552 is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','budget_level of second fund(budget_12)  should be 1');
553 is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','budget_level of  child fund budget_11 should be 2');
554 $budget_hierarchy        = GetBudgetHierarchy($budget_period_id);
555 $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned);
556
557 is( scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy),
558 'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)'
559 );
560 is_deeply(
561     _get_dependencies($budget_hierarchy),
562     _get_dependencies($budget_hierarchy_cloned),
563     'CloneBudgetPeriod (with inactive param) keeps the same dependencies order'
564 );
565 $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id);
566 is( $budget_period->{budget_period_active}, 0,
567     'CloneBudgetPeriod (with inactive param) marks as inactive the budgetperiod'
568 );
569
570 # CloneBudgetPeriod with param reset_all_budgets
571 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
572     {
573         budget_period_id        => $budget_period_id,
574         budget_period_startdate => '2014-01-01',
575         budget_period_enddate   => '2014-12-31',
576         reset_all_budgets         => 1,
577     }
578 );
579
580 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
581 $number_of_budgets_not_reset = 0;
582 for my $budget (@$budget_hierarchy_cloned) {
583     $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0;
584 }
585 is( $number_of_budgets_not_reset, 0,
586     'CloneBudgetPeriod has reset all budgets (funds)' );
587
588 #GetBudgetsByActivity
589 my $result=C4::Budgets::GetBudgetsByActivity(1);
590 isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 1');
591 $result=C4::Budgets::GetBudgetsByActivity(0);
592  isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 0');
593 $result=C4::Budgets::GetBudgetsByActivity();
594  is( $result, 0 , 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' );
595 DelBudget($budget_id);
596 DelBudgetPeriod($bpid);
597
598 # CloneBudgetPeriod with param amount_change_*
599 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
600     {
601         budget_period_id        => $budget_period_id,
602         budget_period_startdate => '2014-01-01',
603         budget_period_enddate   => '2014-12-31',
604         amount_change_percentage => 16,
605         amount_change_round_increment => 5,
606     }
607 );
608
609 $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned);
610 cmp_ok($budget_period_cloned->{budget_period_total}, '==', 11600, "CloneBudgetPeriod changed correctly budget amount");
611 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
612 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, "CloneBudgetPeriod changed correctly funds amounts");
613 cmp_ok($budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
614 cmp_ok($budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts");
615 cmp_ok($budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts");
616 cmp_ok($budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, "CloneBudgetPeriod changed correctly funds amounts");
617 cmp_ok($budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts");
618
619 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
620     {
621         budget_period_id        => $budget_period_id,
622         budget_period_startdate => '2014-01-01',
623         budget_period_enddate   => '2014-12-31',
624         amount_change_percentage => 16,
625         amount_change_round_increment => 5,
626         reset_all_budgets => 1,
627     }
628 );
629 $budget_hierarchy_cloned     = GetBudgetHierarchy($budget_period_id_cloned);
630 cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts");
631
632 # MoveOrders
633 my $number_orders_moved = C4::Budgets::MoveOrders();
634 is( $number_orders_moved, undef, 'MoveOrders return undef if no arg passed' );
635 $number_orders_moved =
636   C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } );
637 is( $number_orders_moved, undef,
638     'MoveOrders return undef if only 1 arg passed' );
639 $number_orders_moved =
640   C4::Budgets::MoveOrders( { to_budget_period_id => $budget_period_id } );
641 is( $number_orders_moved, undef,
642     'MoveOrders return undef if only 1 arg passed' );
643 $number_orders_moved = C4::Budgets::MoveOrders(
644     {
645         from_budget_period_id => $budget_period_id,
646         to_budget_period_id   => $budget_period_id
647     }
648 );
649 is( $number_orders_moved, undef,
650     'MoveOrders return undef if 2 budget period id are the same' );
651
652 $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod(
653     {
654         budget_period_id        => $budget_period_id,
655         budget_period_startdate => '2014-01-01',
656         budget_period_enddate   => '2014-12-31',
657     }
658 );
659
660 my $report = C4::Budgets::MoveOrders(
661     {
662         from_budget_period_id  => $budget_period_id,
663         to_budget_period_id    => $budget_period_id_cloned,
664         move_remaining_unspent => 1,
665     }
666 );
667 is( scalar( @$report ), 6 , "MoveOrders has processed 6 funds" );
668
669 my $number_of_orders_moved = 0;
670 $number_of_orders_moved += scalar( @{ $_->{orders_moved} } ) for @$report;
671 is( $number_of_orders_moved, $number_of_orders_to_move, "MoveOrders has moved $number_of_orders_to_move orders" );
672
673 my @new_budget_ids = map { $_->{budget_id} }
674   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
675 my @old_budget_ids = map { $_->{budget_id} }
676   @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
677 for my $budget_id ( keys %budgets ) {
678     for my $ordernumber ( @{ $budgets{$budget_id} } ) {
679         my $budget            = GetBudgetByOrderNumber($ordernumber);
680         my $is_in_new_budgets = grep /^$budget->{budget_id}$/, @new_budget_ids;
681         my $is_in_old_budgets = grep /^$budget->{budget_id}$/, @old_budget_ids;
682         is( $is_in_new_budgets, 1, "MoveOrders changed the budget_id for order $ordernumber" );
683         is( $is_in_old_budgets, 0, "MoveOrders changed the budget_id for order $ordernumber" );
684     }
685 }
686
687
688 # MoveOrders with param move_remaining_unspent
689 my @new_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) };
690 my @old_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) };
691
692 for my $new_budget ( @new_budgets ) {
693     my ( $old_budget ) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets;
694     my $new_budget_amount_should_be = $old_budget->{budget_amount} * 2 - $old_budget->{total_spent};
695     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})" );
696 }
697
698 # Test SetOwnerToFundHierarchy
699
700 my $patron_category = $builder->build({ source => 'Category' });
701 my $branchcode = $library->{branchcode};
702 my $john_doe = C4::Members::AddMember(
703     cardnumber   => '123456',
704     firstname    => 'John',
705     surname      => 'Doe',
706     categorycode => $patron_category->{categorycode},
707     branchcode   => $branchcode,
708     dateofbirth  => '',
709     dateexpiry   => '9999-12-31',
710     userid       => 'john.doe'
711 );
712
713 C4::Budgets::SetOwnerToFundHierarchy( $budget_id1, $john_doe );
714 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
715     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" );
716 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
717     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" );
718 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
719     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" );
720 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
721     $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" );
722 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
723     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" );
724 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
725     undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" );
726
727 my $jane_doe = C4::Members::AddMember(
728     cardnumber   => '789012',
729     firstname    => 'Jane',
730     surname      => 'Doe',
731     categorycode => $patron_category->{categorycode},
732     branchcode   => $branchcode,
733     dateofbirth  => '',
734     dateexpiry   => '9999-12-31',
735     userid       => 'jane.doe'
736 );
737
738 C4::Budgets::SetOwnerToFundHierarchy( $budget_id11, $jane_doe );
739 is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id},
740     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" );
741 is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id},
742     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" );
743 is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id},
744     $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" );
745 is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id},
746     $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" );
747 is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id},
748     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" );
749 is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id},
750     undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" );
751
752 # Test GetBudgetAuthCats
753
754 my $budgetPeriodId = AddBudgetPeriod({
755     budget_period_startdate   => '2008-01-01',
756     budget_period_enddate     => '2008-12-31',
757     budget_period_description => 'just another budget',
758     budget_period_active      => 0,
759 });
760
761 $budgets = GetBudgets();
762 my $i = 0;
763 for my $budget ( @$budgets )
764 {
765     $budget->{sort1_authcat} = "sort1_authcat_$i";
766     $budget->{sort2_authcat} = "sort2_authcat_$i";
767     $budget->{budget_period_id} = $budgetPeriodId;
768     ModBudget( $budget );
769     $i++;
770 }
771
772 my $authCat = GetBudgetAuthCats($budgetPeriodId);
773
774 is( scalar @{$authCat}, $i * 2, "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" );
775
776 $i = 0;
777 for my $budget ( @$budgets )
778 {
779     $budget->{sort1_authcat} = "sort_authcat_$i";
780     $budget->{sort2_authcat} = "sort_authcat_$i";
781     $budget->{budget_period_id} = $budgetPeriodId;
782     ModBudget( $budget );
783     $i++;
784 }
785
786 $authCat = GetBudgetAuthCats($budgetPeriodId);
787 is( scalar @$authCat, scalar @$budgets, "GetBudgetAuthCats returns distinct authCat" );
788
789 $i = 0;
790 for my $budget ( @$budgets )
791 {
792     $budget->{sort1_authcat} = "sort1_authcat_$i";
793     $budget->{sort2_authcat} = "";
794     $budget->{budget_period_id} = $budgetPeriodId;
795     ModBudget( $budget );
796     $i++;
797 }
798
799 $authCat = GetBudgetAuthCats($budgetPeriodId);
800
801 is( scalar @{$authCat}, $i, "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" );
802
803 $i = 0;
804 for my $budget ( @$budgets )
805 {
806     $budget->{sort1_authcat} = "";
807     $budget->{sort2_authcat} = "";
808     $budget->{budget_period_id} = $budgetPeriodId;
809     ModBudget( $budget );
810     $i++;
811 }
812
813 $authCat = GetBudgetAuthCats($budgetPeriodId);
814
815 is( scalar @{$authCat}, 0, "GetBudgetAuthCats returns only non-empty sorting categories (all empty)" );
816
817 # /Test GetBudgetAuthCats
818
819 sub _get_dependencies {
820     my ($budget_hierarchy) = @_;
821     my $graph;
822     for my $budget (@$budget_hierarchy) {
823         if ( $budget->{child} ) {
824             my @sorted = sort @{ $budget->{child} };
825             for my $child_id (@sorted) {
826                 push @{ $graph->{ $budget->{budget_name} }{children} },
827                   _get_budgetname_by_id( $budget_hierarchy, $child_id );
828             }
829         }
830         push @{ $graph->{ $budget->{budget_name} }{parents} },
831           $budget->{parent_id};
832     }
833     return $graph;
834 }
835
836 sub _get_budgetname_by_id {
837     my ( $budgets, $budget_id ) = @_;
838     my ($budget_name) =
839       map { ( $_->{budget_id} eq $budget_id ) ? $_->{budget_name} : () }
840       @$budgets;
841     return $budget_name;
842 }
843
844 # C4::Context->userenv
845 sub Mock_userenv {
846     return $userenv;
847 }