Bug 17798: Confirm hold when printing slip from another patron's account
[koha.git] / t / db_dependent / Acquisition.t
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use POSIX qw(strftime);
21
22 use Test::More tests => 72;
23 use t::lib::Mocks;
24 use Koha::Database;
25 use Koha::DateUtils qw(dt_from_string output_pref);
26 use Koha::Acquisition::Basket;
27
28 use MARC::File::XML ( BinaryEncoding => 'utf8', RecordFormat => 'MARC21' );
29
30 BEGIN {
31     use_ok('C4::Acquisition', qw( NewBasket GetBasket AddInvoice GetInvoice GetInvoices ModReceiveOrder SearchOrders GetOrder GetHistory ModOrder get_rounding_sql get_rounded_price ReopenBasket ModBasket ModBasketHeader ModBasketUsers ));
32     use_ok('C4::Biblio', qw( AddBiblio GetMarcSubfieldStructure ));
33     use_ok('C4::Budgets', qw( AddBudgetPeriod AddBudget GetBudget GetBudgetByOrderNumber GetBudgetsReport GetBudgets GetBudgetReport ));
34     use_ok('Koha::Acquisition::Orders');
35     use_ok('Koha::Acquisition::Booksellers');
36     use_ok('t::lib::TestBuilder');
37 }
38
39 # Sub used for testing C4::Acquisition subs returning order(s):
40 #    GetOrdersByStatus, GetOrders, GetDeletedOrders, GetOrder etc.
41 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,$test_nbr_fields) =
42 #  _check_fields_of_order ($exp_fields, $original_order_content, $order_to_check);
43 # params :
44 # $exp_fields             : arrayref whose elements are the keys we expect to find
45 # $original_order_content : hashref whose 2 keys str and num contains hashrefs
46 #                           containing content fields of the order created with Koha::Acquisition::Order
47 # $order_to_check         : hashref whose keys/values are the content of an order
48 #                           returned by the C4::Acquisition sub we are testing
49 # returns :
50 # \@test_missing_fields   : arrayref void if ok ; otherwise contains the list of
51 #                           fields missing in $order_to_check
52 # \@test_extra_fields     : arrayref void if ok ; otherwise contains the list of
53 #                           fields unexpected in $order_to_check
54 # \@test_different_fields : arrayref void if ok ; otherwise contains the list of
55 #                           fields which value is not the same in between $order_to_check and
56 # $test_nbr_fields        : contains the number of fields of $order_to_check
57
58 sub _check_fields_of_order {
59     my ( $exp_fields, $original_order_content, $order_to_check ) = @_;
60     my @test_missing_fields   = ();
61     my @test_extra_fields     = ();
62     my @test_different_fields = ();
63     my $test_nbr_fields       = scalar( keys %$order_to_check );
64     foreach my $field (@$exp_fields) {
65         push @test_missing_fields, $field
66           unless exists( $order_to_check->{$field} );
67     }
68     foreach my $field ( keys %$order_to_check ) {
69         push @test_extra_fields, $field
70           unless grep ( /^$field$/, @$exp_fields );
71     }
72     foreach my $field ( keys %{ $original_order_content->{str} } ) {
73         push @test_different_fields, $field
74           unless ( !exists $order_to_check->{$field} )
75           or ( $original_order_content->{str}->{$field} eq
76             $order_to_check->{$field} );
77     }
78     foreach my $field ( keys %{ $original_order_content->{num} } ) {
79         push @test_different_fields, $field
80           unless ( !exists $order_to_check->{$field} )
81           or ( $original_order_content->{num}->{$field} ==
82             $order_to_check->{$field} );
83     }
84     return (
85         \@test_missing_fields,   \@test_extra_fields,
86         \@test_different_fields, $test_nbr_fields
87     );
88 }
89
90 # Sub used for testing C4::Acquisition subs returning several orders
91 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,\@test_nbr_fields) =
92 #   _check_fields_of_orders ($exp_fields, $original_orders_content, $orders_to_check)
93 sub _check_fields_of_orders {
94     my ( $exp_fields, $original_orders_content, $orders_to_check ) = @_;
95     my @test_missing_fields   = ();
96     my @test_extra_fields     = ();
97     my @test_different_fields = ();
98     my @test_nbr_fields       = ();
99     foreach my $order_to_check (@$orders_to_check) {
100         my $original_order_content =
101           ( grep { $_->{str}->{ordernumber} eq $order_to_check->{ordernumber} }
102               @$original_orders_content )[0];
103         my (
104             $t_missing_fields,   $t_extra_fields,
105             $t_different_fields, $t_nbr_fields
106           )
107           = _check_fields_of_order( $exp_fields, $original_order_content,
108             $order_to_check );
109         push @test_missing_fields,   @$t_missing_fields;
110         push @test_extra_fields,     @$t_extra_fields;
111         push @test_different_fields, @$t_different_fields;
112         push @test_nbr_fields,       $t_nbr_fields;
113     }
114     @test_missing_fields = keys %{ { map { $_ => 1 } @test_missing_fields } };
115     @test_extra_fields   = keys %{ { map { $_ => 1 } @test_extra_fields } };
116     @test_different_fields =
117       keys %{ { map { $_ => 1 } @test_different_fields } };
118     return (
119         \@test_missing_fields,   \@test_extra_fields,
120         \@test_different_fields, \@test_nbr_fields
121     );
122 }
123
124
125 my $schema = Koha::Database->new()->schema();
126 $schema->storage->txn_begin();
127
128 # Creating some orders
129 my $bookseller = Koha::Acquisition::Bookseller->new(
130     {
131         name         => "my vendor",
132         address1     => "bookseller's address",
133         phone        => "0123456",
134         active       => 1,
135         deliverytime => 5,
136     }
137 )->store;
138 my $booksellerid = $bookseller->id;
139
140 my $booksellerinfo = Koha::Acquisition::Booksellers->find( $booksellerid );
141 is( $booksellerinfo->deliverytime,
142     5, 'set deliverytime when creating vendor (Bug 10556)' );
143
144 my ( $basket, $basketno );
145 ok(
146     $basketno = NewBasket( $booksellerid, 1 ),
147     "NewBasket(  $booksellerid , 1  ) returns $basketno"
148 );
149 ok( $basket = GetBasket($basketno), "GetBasket($basketno) returns $basket" );
150
151 my $bpid=AddBudgetPeriod({
152         budget_period_startdate => '2008-01-01'
153         , budget_period_enddate => '2008-12-31'
154         , budget_period_active  => 1
155         , budget_period_description    => "MAPERI"
156 });
157
158 my $budgetid = C4::Budgets::AddBudget(
159     {
160         budget_code => "budget_code_test_1",
161         budget_name => "budget_name_test_1",
162         budget_period_id => $bpid,
163     }
164 );
165 my $budget = C4::Budgets::GetBudget($budgetid);
166
167 my @ordernumbers;
168 my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' );
169 my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' );
170 my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' );
171 my ( $biblionumber4, $biblioitemnumber4 ) = AddBiblio( MARC::Record->new, '' );
172 my ( $biblionumber5, $biblioitemnumber5 ) = AddBiblio( MARC::Record->new, '' );
173
174
175
176 # Prepare 6 orders, and make distinction beween fields to be tested with eq and with ==
177 # Ex : a price of 50.1 will be stored internally as 5.100000
178
179 my @order_content = (
180     {
181         str => {
182             basketno       => $basketno,
183             biblionumber   => $biblionumber1,
184             budget_id      => $budget->{budget_id},
185             uncertainprice => 0,
186             order_internalnote => "internal note foo",
187             order_vendornote   => "vendor note bar",
188             ordernumber => '',
189         },
190         num => {
191             quantity  => 24,
192             listprice => 50.121111,
193             ecost     => 38.15,
194             rrp       => 40.15,
195             discount  => 5.1111,
196         }
197     },
198     {
199         str => {
200             basketno     => $basketno,
201             biblionumber => $biblionumber2,
202             budget_id    => $budget->{budget_id}
203         },
204         num => { quantity => 42 }
205     },
206     {
207         str => {
208             basketno       => $basketno,
209             biblionumber   => $biblionumber2,
210             budget_id      => $budget->{budget_id},
211             uncertainprice => 0,
212             order_internalnote => "internal note foo",
213             order_vendornote   => "vendor note bar"
214         },
215         num => {
216             quantity  => 4,
217             ecost     => 42.1,
218             rrp       => 42.1,
219             listprice => 10.1,
220             ecost     => 38.1,
221             rrp       => 11.0,
222             discount  => 5.1,
223         }
224     },
225     {
226         str => {
227             basketno     => $basketno,
228             biblionumber => $biblionumber3,
229             budget_id    => $budget->{budget_id},
230             order_internalnote => "internal note",
231             order_vendornote   => "vendor note"
232         },
233         num => {
234             quantity       => 4,
235             ecost          => 40,
236             rrp            => 42,
237             listprice      => 10,
238             ecost          => 38.15,
239             rrp            => 11.00,
240             discount       => 0,
241             uncertainprice => 0,
242         }
243     },
244     {
245         str => {
246             basketno     => $basketno,
247             biblionumber => $biblionumber4,
248             budget_id    => $budget->{budget_id},
249             order_internalnote => "internal note bar",
250             order_vendornote   => "vendor note foo"
251         },
252         num => {
253             quantity       => 1,
254             ecost          => 10,
255             rrp            => 10,
256             listprice      => 10,
257             ecost          => 10,
258             rrp            => 10,
259             discount       => 0,
260             uncertainprice => 0,
261         }
262     },
263     {
264         str => {
265             basketno     => $basketno,
266             biblionumber => $biblionumber5,
267             budget_id    => $budget->{budget_id},
268             order_internalnote => "internal note",
269             order_vendornote   => "vendor note"
270         },
271         num => {
272             quantity       => 1,
273             ecost          => 10,
274             rrp            => 10,
275             listprice      => 10,
276             ecost          => 10,
277             rrp            => 10,
278             discount       => 0,
279             uncertainprice => 0,
280         }
281     }
282 );
283
284 # Create 6 orders in database
285 for ( 0 .. 5 ) {
286     my %ocontent;
287     @ocontent{ keys %{ $order_content[$_]->{num} } } =
288       values %{ $order_content[$_]->{num} };
289     @ocontent{ keys %{ $order_content[$_]->{str} } } =
290       values %{ $order_content[$_]->{str} };
291     $ordernumbers[$_] = Koha::Acquisition::Order->new( \%ocontent )->store->ordernumber;
292     $order_content[$_]->{str}->{ordernumber} = $ordernumbers[$_];
293 }
294
295 Koha::Acquisition::Orders->find($ordernumbers[3])->cancel;
296
297 my $invoiceid = AddInvoice(
298     invoicenumber => 'invoice',
299     booksellerid  => $booksellerid,
300     unknown       => "unknown"
301 );
302
303 my $invoice = GetInvoice( $invoiceid );
304
305 my $reception_date = output_pref(
306     {
307             dt => dt_from_string->add( days => 1 ),
308             dateformat => 'iso',
309             dateonly => 1,
310     }
311 );
312 my ($datereceived, $new_ordernumber) = ModReceiveOrder(
313     {
314         biblionumber      => $biblionumber4,
315         order             => Koha::Acquisition::Orders->find( $ordernumbers[4] )->unblessed,
316         quantityreceived  => 1,
317         invoice           => $invoice,
318         budget_id         => $order_content[4]->{str}->{budget_id},
319         datereceived      => $reception_date,
320     }
321 );
322
323 is(
324     output_pref(
325         {
326             dt         => dt_from_string($datereceived),
327             dateformat => 'iso',
328             dateonly   => 1
329         }
330     ),
331     $reception_date,
332     'ModReceiveOrder sets the passed date'
333 );
334
335 my $search_orders = SearchOrders({
336     booksellerid => $booksellerid,
337     basketno     => $basketno
338 });
339 isa_ok( $search_orders, 'ARRAY' );
340 ok(
341     (
342         ( scalar @$search_orders == 5 )
343           and !grep ( $_->{ordernumber} eq $ordernumbers[3], @$search_orders )
344     ),
345     "SearchOrders only gets non-cancelled orders"
346 );
347
348 $search_orders = SearchOrders({
349     booksellerid => $booksellerid,
350     basketno     => $basketno,
351     pending      => 1
352 });
353 ok(
354     (
355         ( scalar @$search_orders == 4 ) and !grep ( (
356                      ( $_->{ordernumber} eq $ordernumbers[3] )
357                   or ( $_->{ordernumber} eq $ordernumbers[4] )
358             ),
359             @$search_orders )
360     ),
361     "SearchOrders with pending params gets only pending orders (bug 10723)"
362 );
363
364 $search_orders = SearchOrders({
365     booksellerid => $booksellerid,
366     basketno     => $basketno,
367     pending      => 1,
368     ordered      => 1,
369 });
370 is( scalar (@$search_orders), 0, "SearchOrders with pending and ordered params gets only pending ordered orders (bug 11170)" );
371
372 $search_orders = SearchOrders({
373     ordernumber => $ordernumbers[4]
374 });
375 is( scalar (@$search_orders), 1, "SearchOrders takes into account the ordernumber filter" );
376
377 $search_orders = SearchOrders({
378     biblionumber => $biblionumber4
379 });
380 is( scalar (@$search_orders), 1, "SearchOrders takes into account the biblionumber filter" );
381
382 $search_orders = SearchOrders({
383     biblionumber => $biblionumber4,
384     pending      => 1
385 });
386 is( scalar (@$search_orders), 0, "SearchOrders takes into account the biblionumber and pending filters" );
387
388 #
389 # Test GetBudgetByOrderNumber
390 #
391 ok( GetBudgetByOrderNumber( $ordernumbers[0] )->{'budget_id'} eq $budgetid,
392     "GetBudgetByOrderNumber returns expected budget" );
393
394 my $lateorders = Koha::Acquisition::Orders->filter_by_lates({ delay => 0 });
395 is( $lateorders->search({ 'me.basketno' => $basketno })->count,
396     0, "GetLateOrders does not get orders from opened baskets" );
397 Koha::Acquisition::Baskets->find($basketno)->close;
398 $lateorders = Koha::Acquisition::Orders->filter_by_lates({ delay => 0 });
399 isnt( $lateorders->search({ 'me.basketno' => $basketno })->count,
400     0, "GetLateOrders gets orders from closed baskets" );
401 is( $lateorders->search({ ordernumber => $ordernumbers[3] })->count, 0,
402     "GetLateOrders does not get cancelled orders" );
403 is( $lateorders->search({ ordernumber => $ordernumbers[4] })->count, 0,
404     "GetLateOrders does not get received orders" );
405
406 $search_orders = SearchOrders({
407     booksellerid => $booksellerid,
408     basketno     => $basketno,
409     pending      => 1,
410     ordered      => 1,
411 });
412 is( scalar (@$search_orders), 4, "SearchOrders with pending and ordered params gets only pending ordered orders. After closing the basket, orders are marked as 'ordered' (bug 11170)" );
413
414 #
415 # Test AddClaim
416 #
417
418 my $order = $lateorders->next;
419 $order->claim();
420 is(
421     output_pref({ str => $order->claimed_date, dateformat => 'iso', dateonly => 1 }),
422     strftime( "%Y-%m-%d", localtime(time) ),
423     "Koha::Acquisition::Order->claim: Check claimed_date"
424 );
425
426 my $order2 = Koha::Acquisition::Orders->find( $ordernumbers[1] )->unblessed;
427 $order2->{order_internalnote} = "my notes";
428 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
429     {
430         biblionumber     => $biblionumber2,
431         order            => $order2,
432         quantityreceived => 2,
433         invoice          => $invoice,
434     }
435 );
436 $order2 = GetOrder( $ordernumbers[1] );
437 is( $order2->{'quantityreceived'},
438     0, 'Splitting up order did not receive any on original order' );
439 is( $order2->{'quantity'}, 40, '40 items on original order' );
440 is( $order2->{'budget_id'}, $budgetid,
441     'Budget on original order is unchanged' );
442 is( $order2->{order_internalnote}, "my notes",
443     'ModReceiveOrder and GetOrder deal with internal notes' );
444 my $order1 = GetOrder( $ordernumbers[0] );
445 is(
446     $order1->{order_internalnote},
447     "internal note foo",
448     "ModReceiveOrder only changes the supplied orders internal notes"
449 );
450
451 my $neworder = GetOrder($new_ordernumber);
452 is( $neworder->{'quantity'}, 2, '2 items on new order' );
453 is( $neworder->{'quantityreceived'},
454     2, 'Splitting up order received items on new order' );
455 is( $neworder->{'budget_id'}, $budgetid, 'Budget on new order is unchanged' );
456
457 is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' );
458 is( $neworder->{parent_ordernumber}, $ordernumbers[1], 'Split: test parent_ordernumber' );
459
460 my $orders = GetHistory( ordernumber => $ordernumbers[1] );
461 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumber returns 1 order' );
462 $orders = GetHistory( ordernumber => $ordernumbers[1], search_children_too => 1 );
463 is( scalar( @$orders ), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' );
464 $orders = GetHistory( ordernumbers => [$ordernumbers[1]] );
465 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumbers returns 1 order' );
466 $orders = GetHistory( ordernumbers => \@ordernumbers );
467 is( scalar( @$orders ), scalar( @ordernumbers ) - 1, 'GetHistory with a list of ordernumbers returns N-1 orders (was has been deleted [3])' );
468
469 $orders = GetHistory( internalnote => 'internal note foo' );
470 is( scalar( @$orders ), 2, 'GetHistory returns correctly a search for internalnote' );
471 $orders = GetHistory( vendornote => 'vendor note bar' );
472 is( scalar( @$orders ), 2, 'GetHistory returns correctly a search for vendornote' );
473 $orders = GetHistory( internalnote => 'internal note bar' );
474 is( scalar( @$orders ), 1, 'GetHistory returns correctly a search for internalnote' );
475 $orders = GetHistory( vendornote => 'vendor note foo' );
476 is( scalar( @$orders ), 1, 'GetHistory returns correctly a search for vendornote' );
477
478 my $budgetid2 = C4::Budgets::AddBudget(
479     {
480         budget_code => "budget_code_test_modrecv",
481         budget_name => "budget_name_test_modrecv",
482     }
483 );
484
485 my $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
486 $order3->{order_internalnote} = "my other notes";
487 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
488     {
489         biblionumber     => $biblionumber2,
490         order            => $order3,
491         quantityreceived => 2,
492         invoice          => $invoice,
493         budget_id        => $budgetid2,
494     }
495 );
496
497 $order3 = GetOrder( $ordernumbers[2] );
498 is( $order3->{'quantityreceived'},
499     0, 'Splitting up order did not receive any on original order' );
500 is( $order3->{'quantity'}, 2, '2 items on original order' );
501 is( $order3->{'budget_id'}, $budgetid,
502     'Budget on original order is unchanged' );
503 is( $order3->{order_internalnote}, "my other notes",
504     'ModReceiveOrder and GetOrder deal with notes' );
505
506 $neworder = GetOrder($new_ordernumber);
507 is( $neworder->{'quantity'}, 2, '2 items on new order' );
508 is( $neworder->{'quantityreceived'},
509     2, 'Splitting up order received items on new order' );
510 is( $neworder->{'budget_id'}, $budgetid2, 'Budget on new order is changed' );
511
512 $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
513 $order3->{order_internalnote} = "my third notes";
514 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
515     {
516         biblionumber     => $biblionumber2,
517         order            => $order3,
518         quantityreceived => 2,
519         invoice          => $invoice,
520         budget_id        => $budgetid2,
521     }
522 );
523
524 $order3 = GetOrder( $ordernumbers[2] );
525 is( $order3->{'quantityreceived'}, 2,          'Order not split up' );
526 is( $order3->{'quantity'},         2,          '2 items on order' );
527 is( $order3->{'budget_id'},        $budgetid2, 'Budget has changed' );
528 is( $order3->{order_internalnote}, "my third notes", 'ModReceiveOrder and GetOrder deal with notes' );
529
530 my $nonexistent_order = GetOrder();
531 is( $nonexistent_order, undef, 'GetOrder returns undef if no ordernumber is given' );
532 $nonexistent_order = GetOrder( 424242424242 );
533 is( $nonexistent_order, undef, 'GetOrder returns undef if a nonexistent ordernumber is given' );
534
535 subtest 'ModOrder' => sub {
536     plan tests => 1;
537     ModOrder( { ordernumber => $order1->{ordernumber}, unitprice => 42 } );
538     my $order = GetOrder( $order1->{ordernumber} );
539     is( int($order->{unitprice}), 42, 'ModOrder should work even if biblionumber if not passed');
540 };
541
542 # Budget reports
543 my $all_count = scalar GetBudgetsReport();
544 ok($all_count >= 1, "GetBudgetReport OK");
545
546 my $active_count = scalar GetBudgetsReport(1);
547 ok($active_count >= 1 , "GetBudgetsReport(1) OK");
548
549 is($all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions.");
550 ok($active_count >= scalar GetBudgetsReport(1), "GetBudgetReport doesn't return inactive budget period acquisitions.");
551
552 # "Flavoured" tests (tests that required a run for each marc flavour)
553 # Tests should be added to the run_flavoured_tests sub below
554 my $biblio_module = Test::MockModule->new('C4::Biblio');
555 $biblio_module->mock(
556     'GetMarcSubfieldStructure',
557     sub {
558         my ($self) = shift;
559
560         my ( $title_field,            $title_subfield )            = get_title_field();
561         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
562         my ( $issn_field,             $issn_subfield )             = get_issn_field();
563         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
564         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
565         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
566
567         return {
568             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
569             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
570             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
571             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
572             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
573             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
574         };
575       }
576 );
577
578 sub run_flavoured_tests {
579     my $marcflavour = shift;
580     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
581
582     #
583     # Test SearchWithISBNVariations syspref
584     #
585     my $marc_record = MARC::Record->new;
586     $marc_record->append_fields( create_isbn_field( '9780136019701', $marcflavour ) );
587     my ( $biblionumber6, $biblioitemnumber6 ) = AddBiblio( $marc_record, '' );
588
589     # Create order
590     my $ordernumber = Koha::Acquisition::Order->new( {
591             basketno     => $basketno,
592             biblionumber => $biblionumber6,
593             budget_id    => $budget->{budget_id},
594             order_internalnote => "internal note",
595             order_vendornote   => "vendor note",
596             quantity       => 1,
597             ecost          => 10,
598             rrp            => 10,
599             listprice      => 10,
600             ecost          => 10,
601             rrp            => 10,
602             discount       => 0,
603             uncertainprice => 0,
604     } )->store->ordernumber;
605
606     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
607     $orders = GetHistory( isbn => '0136019706' );
608     is( scalar(@$orders), 0, "GetHistory searches correctly by ISBN" );
609
610     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
611     $orders = GetHistory( isbn => '0136019706' );
612     is( scalar(@$orders), 1, "GetHistory searches correctly by ISBN" );
613
614     Koha::Acquisition::Orders->find($ordernumber)->cancel;
615
616     my $marc_record_issn = MARC::Record->new;
617     $marc_record_issn->append_fields( create_issn_field( '2434561X', $marcflavour ) );
618     my ( $biblionumber6_issn, undef ) = AddBiblio( $marc_record_issn, '' );
619
620     my $orders_issn = GetHistory( issn => '2434561X' );
621     is( scalar(@$orders_issn), 0, "Precheck that ISSN shouldn't be in database" );
622
623     # Create order
624     my $ordernumber_issn = Koha::Acquisition::Order->new( {
625             basketno     => $basketno,
626             biblionumber => $biblionumber6_issn,
627             budget_id    => $budget->{budget_id},
628             order_internalnote => "internal note",
629             order_vendornote   => "vendor note",
630             quantity       => 1,
631             ecost          => 10,
632             rrp            => 10,
633             listprice      => 10,
634             ecost          => 10,
635             rrp            => 10,
636             discount       => 0,
637             uncertainprice => 0,
638     } )->store->ordernumber;
639
640     t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0);
641     $orders_issn = GetHistory( issn => '2434-561X' );
642     is( scalar(@$orders_issn), 0, "GetHistory searches correctly by ISSN" );
643
644     t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1);
645     $orders_issn = GetHistory( issn => '2434-561X' );
646     is( scalar(@$orders_issn), 1, "GetHistory searches correctly by ISSN" );
647
648     Koha::Acquisition::Orders->find($ordernumber_issn)->cancel;
649 }
650
651 # Test GetHistory() with and without SearchWithISBNVariations or SearchWithISSNVariations
652 # The ISBN passed as a param is the ISBN-10 version of the 13-digit ISBN in the sample record declared in $marcxml
653
654 # Do "flavoured" tests
655 subtest 'MARC21' => sub {
656     plan tests => 5;
657     run_flavoured_tests('MARC21');
658 };
659
660 subtest 'UNIMARC' => sub {
661     plan tests => 5;
662     run_flavoured_tests('UNIMARC');
663 };
664
665 ### Functions required for "flavoured" tests
666 sub get_title_field {
667     my $marc_flavour = C4::Context->preference('marcflavour');
668     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
669 }
670
671 sub get_isbn_field {
672     my $marc_flavour = C4::Context->preference('marcflavour');
673     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
674 }
675
676 sub get_issn_field {
677     my $marc_flavour = C4::Context->preference('marcflavour');
678     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
679 }
680
681 sub get_itemnumber_field {
682     my $marc_flavour = C4::Context->preference('marcflavour');
683     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
684 }
685
686 sub create_isbn_field {
687     my ( $isbn, $marcflavour ) = @_;
688
689     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
690     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
691
692     # Add the price subfield
693     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
694     $field->add_subfields( $price_subfield => '$100' );
695
696     return $field;
697 }
698
699 sub create_issn_field {
700     my ( $issn, $marcflavour ) = @_;
701
702     my ( $issn_field, $issn_subfield ) = get_issn_field();
703     my $field = MARC::Field->new( $issn_field, '', '', $issn_subfield => $issn );
704
705     return $field;
706 }
707
708 subtest 'ModReceiveOrder replacementprice tests' => sub {
709     plan tests => 2;
710     #Let's build an order, we need a couple things though
711     my $builder = t::lib::TestBuilder->new;
712     my $order_biblio = $builder->build_sample_biblio;
713     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
714     my $order_invoice = $builder->build({ source => 'Aqinvoice'});
715     my $order_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' }  });
716     my $order_vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $order_currency->{currency}, invoiceprice => $order_currency->{currency} } });
717     my $orderinfo ={
718         basketno => $order_basket->{basketno},
719         rrp => 19.99,
720         replacementprice => undef,
721         quantity => 1,
722         quantityreceived => 0,
723         datereceived => undef,
724         datecancellationprinted => undef,
725     };
726     my $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
727     (undef, my $received_ordernumber) = ModReceiveOrder({
728             biblionumber => $order_biblio->biblionumber,
729             order        => $receive_order,
730             invoice      => $order_invoice,
731             quantityreceived => $receive_order->{quantity},
732             budget_id    => $order->{budget_id},
733     });
734     my $received_order = GetOrder($received_ordernumber);
735     is ($received_order->{replacementprice},undef,"No price set if none passed in");
736     $orderinfo->{replacementprice} = 16.12;
737     $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
738     (undef, $received_ordernumber) = ModReceiveOrder({
739             biblionumber => $order_biblio->biblionumber,
740             order        => $receive_order,
741             invoice      => $order_invoice,
742             quantityreceived => $receive_order->{quantity},
743             budget_id    => $order->{budget_id},
744     });
745     $received_order = GetOrder($received_ordernumber);
746     is ($received_order->{replacementprice},'16.120000',"Replacement price set if none passed in");
747 };
748
749 subtest 'ModReceiveOrder and subscription' => sub {
750     plan tests => 2;
751
752     my $builder     = t::lib::TestBuilder->new;
753     my $first_note  = 'first note';
754     my $second_note = 'second note';
755     my $subscription = $builder->build_object( { class => 'Koha::Subscriptions' } );
756     my $order = $builder->build_object(
757         {
758             class => 'Koha::Acquisition::Orders',
759             value => {
760                 subscriptionid     => $subscription->subscriptionid,
761                 order_internalnote => $first_note,
762                 quantity           => 5,
763                 quantityreceived   => 0,
764                 ecost_tax_excluded => 42,
765                 unitprice_tax_excluded => 42,
766             }
767         }
768     );
769     my $order_info = $order->unblessed;
770     # We do not want the note from the original note to be modified
771     # Keeping it will permit to display it for future receptions
772     $order_info->{order_internalnote} = $second_note;
773     my ( undef, $received_ordernumber ) = ModReceiveOrder(
774         {
775             biblionumber     => $order->biblionumber,
776             order            => $order_info,
777             invoice          => $order->{invoiceid},
778             quantityreceived => 1,
779             budget_id        => $order->budget_id,
780         }
781     );
782     my $received_order = Koha::Acquisition::Orders->find($received_ordernumber);
783     is( $received_order->order_internalnote,
784         $second_note, "No price set if none passed in" );
785
786     is( $order->get_from_storage->order_internalnote, $first_note );
787 };
788
789 subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub {
790     plan tests => 2;
791
792     my $builder = t::lib::TestBuilder->new;
793     subtest 'partial order' => sub {
794         plan tests => 2;
795
796         subtest 'no invoice_unitprice' => sub {
797             plan tests => 4;
798             my $order = $builder->build_object(
799                 {
800                     class => 'Koha::Acquisition::Orders',
801                     value => {
802                         quantity               => 5,
803                         quantityreceived       => 0,
804                         ecost_tax_excluded     => 42,
805                         unitprice_tax_excluded => 42,
806                         unitprice              => 42,
807                     }
808                 }
809             );
810             my $order_info = {
811                 %{ $order->unblessed },
812                 invoice_unitprice => undef,
813                 invoice_currency  => undef,
814             };
815             my ( undef, $received_ordernumber ) = ModReceiveOrder(
816                 {
817                     biblionumber     => $order->biblionumber,
818                     order            => $order_info,
819                     quantityreceived => 1,                   # We receive only 1
820                     budget_id        => $order->budget_id,
821                 }
822             );
823             my $active_currency = Koha::Acquisition::Currencies->get_active;
824             my $received_order =
825               Koha::Acquisition::Orders->find($received_ordernumber);
826             is( $received_order->invoice_unitprice,
827                 $order->unitprice, 'no price should be stored if none passed' );
828             is( $received_order->invoice_currency,
829                 $active_currency->currency, 'no currency should be stored if none passed' );
830             $order = $order->get_from_storage;
831             is( $order->invoice_unitprice, $order->unitprice,
832                 'no price should be stored if none passed' );
833             is( $order->invoice_currency, $active_currency->currency,
834                 'no currency should be stored if none passed' );
835         };
836         subtest 'with invoice_unitprice' => sub {
837             plan tests => 4;
838             my $order = $builder->build_object(
839                 {
840                     class => 'Koha::Acquisition::Orders',
841                     value => {
842                         quantity               => 5,
843                         quantityreceived       => 0,
844                         ecost_tax_excluded     => 42,
845                         unitprice_tax_excluded => 42,
846                         unitprice              => 42,
847                     }
848                 }
849             );
850             my $order_info = {
851                 %{ $order->unblessed },
852                 invoice_unitprice => 37,
853                 invoice_currency  => 'GBP',
854             };
855             my ( undef, $received_ordernumber ) = ModReceiveOrder(
856                 {
857                     biblionumber     => $order->biblionumber,
858                     order            => $order_info,
859                     quantityreceived => 1,
860                     budget_id        => $order->budget_id,
861                 }
862             );
863             my $received_order =
864               Koha::Acquisition::Orders->find($received_ordernumber);
865             is( $received_order->invoice_unitprice + 0,
866                 37, 'price should be stored in new order' );
867             is( $received_order->invoice_currency,
868                 'GBP', 'currency should be stored in new order' );
869             $order = $order->get_from_storage;
870             is( $order->invoice_unitprice + 0,
871                 37, 'price should be stored in existing order' );
872             is( $order->invoice_currency, 'GBP',
873                 'currency should be stored in existing order' );
874
875         };
876     };
877
878     subtest 'full received order' => sub {
879         plan tests => 2;
880
881         subtest 'no invoice_unitprice' => sub {
882             plan tests => 4;
883             my $builder = t::lib::TestBuilder->new;
884             my $order   = $builder->build_object(
885                 {
886                     class => 'Koha::Acquisition::Orders',
887                     value => {
888                         quantity               => 5,
889                         quantityreceived       => 0,
890                         ecost_tax_excluded     => 42,
891                         unitprice_tax_excluded => 42,
892                         unitprice              => 42,
893                     }
894                 }
895             );
896             my $order_info = {
897                 %{ $order->unblessed },
898                 invoice_unitprice => undef,
899                 invoice_currency  => undef,
900             };
901             my ( undef, $received_ordernumber ) = ModReceiveOrder(
902                 {
903                     biblionumber => $order->biblionumber,
904                     order        => $order_info,
905                     quantityreceived => 5,                # We receive them all!
906                     budget_id        => $order->budget_id,
907                 }
908             );
909             my $active_currency = Koha::Acquisition::Currencies->get_active;
910             my $received_order =
911               Koha::Acquisition::Orders->find($received_ordernumber);
912             is( $received_order->invoice_unitprice,
913                 $order->unitprice, 'no price should be stored if none passed' );
914             is( $received_order->invoice_currency,
915                 $active_currency->currency, 'no currency should be stored if none passed' );
916             $order = $order->get_from_storage;
917             is( $order->invoice_unitprice, $order->unitprice,
918                 'no price should be stored if none passed' );
919             is( $order->invoice_currency, $active_currency->currency,
920                 'no currency should be stored if none passed' );
921
922         };
923
924         subtest 'with invoice_unitprice' => sub {
925             plan tests => 4;
926             my $order = $builder->build_object(
927                 {
928                     class => 'Koha::Acquisition::Orders',
929                     value => {
930                         quantity               => 5,
931                         quantityreceived       => 0,
932                         ecost_tax_excluded     => 42,
933                         unitprice_tax_excluded => 42,
934                         unitprice              => 42,
935                     }
936                 }
937             );
938             my $order_info = {
939                 %{ $order->unblessed },
940                 invoice_unitprice => 37,
941                 invoice_currency  => 'GBP',
942             };
943             my ( undef, $received_ordernumber ) = ModReceiveOrder(
944                 {
945                     biblionumber     => $order->biblionumber,
946                     order            => $order_info,
947                     quantityreceived => 1,
948                     budget_id        => $order->budget_id,
949                 }
950             );
951             my $received_order =
952               Koha::Acquisition::Orders->find($received_ordernumber);
953             is( $received_order->invoice_unitprice + 0,
954                 37, 'price should be stored in new order' );
955             is( $received_order->invoice_currency,
956                 'GBP', 'currency should be stored in new order' );
957             $order = $order->get_from_storage;
958             is( $order->invoice_unitprice + 0,
959                 37, 'price should be stored in existing order' );
960             is( $order->invoice_currency, 'GBP',
961                 'currency should be stored in existing order' );
962
963         };
964     };
965
966 };
967
968 subtest 'GetHistory with additional fields' => sub {
969     plan tests => 3;
970     my $builder = t::lib::TestBuilder->new;
971     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
972     my $orderinfo ={
973         basketno => $order_basket->{basketno},
974         rrp => 19.99,
975         replacementprice => undef,
976         quantity => 1,
977         quantityreceived => 0,
978         datereceived => undef,
979         datecancellationprinted => undef,
980     };
981     my $order =        $builder->build({ source => 'Aqorder', value => $orderinfo });
982     my $history = GetHistory(ordernumber => $order->{ordernumber});
983     is( scalar( @$history ), 1, 'GetHistory returns the one order');
984
985     my $additional_field = $builder->build({source => 'AdditionalField', value => {
986             tablename => 'aqbasket',
987             name => 'snakeoil',
988             authorised_value_category => "",
989         }
990     });
991     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
992     is( scalar ( @$history ), 0, 'GetHistory returns no order for an unused additional field');
993     my $basket = Koha::Acquisition::Baskets->find({ basketno => $order_basket->{basketno} });
994     $basket->set_additional_fields([{
995         id => $additional_field->{id},
996         value => 'delicious',
997     }]);
998
999     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
1000     is( scalar( @$history ), 1, 'GetHistory returns the order when additional field is set');
1001 };
1002
1003 subtest 'Tests for get_rounding_sql' => sub {
1004
1005     plan tests => 2;
1006
1007     my $value = '3.141592';
1008
1009     t::lib::Mocks::mock_preference( 'OrderPriceRounding', q{} );
1010     my $no_rounding_result = C4::Acquisition::get_rounding_sql($value);
1011     t::lib::Mocks::mock_preference( 'OrderPriceRounding', q{nearest_cent} );
1012     my $rounding_result = C4::Acquisition::get_rounding_sql($value);
1013
1014     ok( $no_rounding_result eq $value, "Value ($value) not to be rounded" );
1015     ok( $rounding_result =~ /CAST/,    "Value ($value) will be rounded" );
1016
1017 };
1018
1019 subtest 'Test for get_rounded_price' => sub {
1020
1021     plan tests => 6;
1022
1023     my $exact_price      = 3.14;
1024     my $up_price         = 3.145592;
1025     my $down_price       = 3.141592;
1026     my $round_up_price   = sprintf( '%0.2f', $up_price );
1027     my $round_down_price = sprintf( '%0.2f', $down_price );
1028
1029     t::lib::Mocks::mock_preference( 'OrderPriceRounding', q{} );
1030     my $not_rounded_result1 = C4::Acquisition::get_rounded_price($exact_price);
1031     my $not_rounded_result2 = C4::Acquisition::get_rounded_price($up_price);
1032     my $not_rounded_result3 = C4::Acquisition::get_rounded_price($down_price);
1033     t::lib::Mocks::mock_preference( 'OrderPriceRounding', q{nearest_cent} );
1034     my $rounded_result1 = C4::Acquisition::get_rounded_price($exact_price);
1035     my $rounded_result2 = C4::Acquisition::get_rounded_price($up_price);
1036     my $rounded_result3 = C4::Acquisition::get_rounded_price($down_price);
1037
1038     is( $not_rounded_result1, $exact_price,      "Price ($exact_price) was correctly not rounded ($not_rounded_result1)" );
1039     is( $not_rounded_result2, $up_price,         "Price ($up_price) was correctly not rounded ($not_rounded_result2)" );
1040     is( $not_rounded_result3, $down_price,       "Price ($down_price) was correctly not rounded ($not_rounded_result3)" );
1041     is( $rounded_result1,     $exact_price,      "Price ($exact_price) was correctly rounded ($rounded_result1)" );
1042     is( $rounded_result2,     $round_up_price,   "Price ($up_price) was correctly rounded ($rounded_result2)" );
1043     is( $rounded_result3,     $round_down_price, "Price ($down_price) was correctly rounded ($rounded_result3)" );
1044
1045 };
1046
1047 subtest 'GetHistory - managing library' => sub {
1048
1049     plan tests => 1;
1050
1051     my $orders = GetHistory(managing_library => 'CPL');
1052
1053     my $builder = t::lib::TestBuilder->new;
1054
1055     my $order_basket1 = $builder->build({ source => 'Aqbasket', value => { branch => 'CPL' } });
1056     my $orderinfo1 ={
1057         basketno => $order_basket1->{basketno},
1058         rrp => 19.99,
1059         replacementprice => undef,
1060         quantity => 1,
1061         quantityreceived => 0,
1062         datereceived => undef,
1063         datecancellationprinted => undef,
1064     };
1065     my $order1 = $builder->build({ source => 'Aqorder', value => $orderinfo1 });
1066
1067     my $order_basket2 = $builder->build({ source => 'Aqbasket', value => { branch => 'LIB' } });
1068     my $orderinfo2 ={
1069         basketno => $order_basket2->{basketno},
1070         rrp => 19.99,
1071         replacementprice => undef,
1072         quantity => 1,
1073         quantityreceived => 0,
1074         datereceived => undef,
1075         datecancellationprinted => undef,
1076     };
1077     my $order2 = $builder->build({ source => 'Aqorder', value => $orderinfo2 });
1078
1079     my $history = GetHistory(managing_library => 'CPL');
1080     is( scalar( @$history), scalar ( @$orders ) +1, "GetHistory returns number of orders");
1081
1082 };
1083
1084 subtest 'GetHistory - is_standing' => sub {
1085
1086     plan tests => 1;
1087
1088     my $orders = GetHistory( is_standing => '1' );
1089
1090     my $builder = t::lib::TestBuilder->new;
1091
1092     my $order_basket1 = $builder->build( { source => 'Aqbasket', value => { is_standing => 0 } } );
1093     my $orderinfo1 = {
1094         basketno                => $order_basket1->{basketno},
1095         rrp                     => 19.99,
1096         replacementprice        => undef,
1097         quantity                => 1,
1098         quantityreceived        => 0,
1099         datereceived            => undef,
1100         datecancellationprinted => undef,
1101     };
1102     my $order1 = $builder->build( { source => 'Aqorder', value => $orderinfo1 } );
1103
1104     my $order_basket2 = $builder->build( { source => 'Aqbasket', value => { is_standing => 1 } } );
1105     my $orderinfo2 = {
1106         basketno                => $order_basket2->{basketno},
1107         rrp                     => 19.99,
1108         replacementprice        => undef,
1109         quantity                => 1,
1110         quantityreceived        => 0,
1111         datereceived            => undef,
1112         datecancellationprinted => undef,
1113     };
1114     my $order2 = $builder->build( { source => 'Aqorder', value => $orderinfo2 } );
1115
1116     my $history = GetHistory( is_standing => 1 );
1117     is(
1118         scalar(@$history),
1119         scalar(@$orders) + 1,
1120         "GetHistory returns number of standing orders"
1121     );
1122
1123 };
1124
1125 subtest 'Acquisition logging' => sub {
1126
1127     plan tests => 5;
1128
1129     t::lib::Mocks::mock_preference('AcquisitionLog', 1);
1130
1131     Koha::ActionLogs->delete;
1132     my $basketno = NewBasket( $booksellerid, 1 );
1133     my @create_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'ADD_BASKET', object => $basketno })->as_list;
1134     is (scalar @create_logs, 1, 'Basket creation is logged');
1135
1136     Koha::ActionLogs->delete;
1137     C4::Acquisition::ReopenBasket($basketno);
1138     my @reopen_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'REOPEN_BASKET', object => $basketno })->as_list;
1139     is (scalar @reopen_logs, 1, 'Basket reopen is logged');
1140
1141     Koha::ActionLogs->delete;
1142     C4::Acquisition::ModBasket({
1143         basketno => $basketno,
1144         booksellerid => $booksellerid
1145     });
1146     my @mod_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET', object => $basketno })->as_list;
1147     is (scalar @mod_logs, 1, 'Basket modify is logged');
1148
1149     Koha::ActionLogs->delete;
1150     C4::Acquisition::ModBasketHeader($basketno,"Test","","","",$booksellerid);
1151     my @mod_header_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET_HEADER', object => $basketno })->as_list;
1152     is (scalar @mod_header_logs, 1, 'Basket header modify is logged');
1153
1154     Koha::ActionLogs->delete;
1155     C4::Acquisition::ModBasketUsers($basketno,(1));
1156     my @mod_users_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET_USERS', object => $basketno })->as_list;
1157     is (scalar @mod_users_logs, 1, 'Basket users modify is logged');
1158
1159     t::lib::Mocks::mock_preference('AcquisitionLog', 0);
1160 };
1161
1162 $schema->storage->txn_rollback();
1163
1164 subtest 'GetInvoices() tests with additional fields' => sub {
1165
1166     plan tests => 7;
1167
1168     $schema->storage->txn_begin;
1169
1170     my $builder = t::lib::TestBuilder->new;
1171
1172     my $invoice_1 = $builder->build_object(
1173         {
1174              class => 'Koha::Acquisition::Invoices',
1175              value => {
1176                 invoicenumber => 'whataretheodds1'
1177              }
1178         }
1179     );
1180     my $invoice_2 = $builder->build_object(
1181         {
1182              class => 'Koha::Acquisition::Invoices',
1183              value => {
1184                 invoicenumber => 'whataretheodds2'
1185              }
1186         }
1187     );
1188
1189
1190     my $invoices = [ GetInvoices( invoicenumber => 'whataretheodds' ) ];
1191     is( scalar @{$invoices}, 2, 'Two invoices retrieved' );
1192     is( $invoices->[0]->{invoiceid}, $invoice_1->id );
1193     is( $invoices->[1]->{invoiceid}, $invoice_2->id );
1194
1195     my $additional_field_1 = $builder->build_object(
1196         {   class => 'Koha::AdditionalFields',
1197             value => {
1198                 tablename                 => 'aqinvoices',
1199                 authorised_value_category => "",
1200             }
1201         }
1202     );
1203
1204     my $additional_field_2 = $builder->build_object(
1205         {   class => 'Koha::AdditionalFields',
1206             value => {
1207                 tablename                 => 'aqinvoices',
1208                 authorised_value_category => "",
1209             }
1210         }
1211     );
1212
1213     $invoice_1->set_additional_fields([ { id => $additional_field_1->id, value => 'Ya-Hey' } ]);
1214     $invoice_2->set_additional_fields([ { id => $additional_field_2->id, value => "Hey ho let's go" } ]);
1215
1216     $invoices = [ GetInvoices(
1217         invoicenumber => 'whataretheodds',
1218         additional_fields => [{ id => $additional_field_1->id, value => 'Ya-Hey' }]
1219     )];
1220     is( scalar @{$invoices}, 1, 'One invoice retrieved' );
1221     is( $invoices->[0]->{invoiceid}, $invoice_1->id, 'Ya-Hey' );
1222
1223     $invoices = [ GetInvoices(
1224         invoicenumber => 'whataretheodds',
1225         additional_fields => [{ id => $additional_field_2->id, value => "Hey ho let's go" }]
1226     )];
1227     is( scalar @{$invoices}, 1, 'One invoice retrieved' );
1228     is( $invoices->[0]->{invoiceid}, $invoice_2->id, "Hey ho let's go" );
1229
1230     $schema->storage->txn_rollback;
1231 };