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