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