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