Bug 15774: (follow-up) Address QA issues
[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 => 74;
23 use t::lib::Mocks;
24 use Koha::Database;
25 use Koha::Acquisition::Basket;
26
27 use MARC::File::XML ( BinaryEncoding => 'utf8', RecordFormat => 'MARC21' );
28
29 BEGIN {
30     use_ok('C4::Acquisition');
31     use_ok('C4::Biblio');
32     use_ok('C4::Budgets');
33     use_ok('Koha::Acquisition::Orders');
34     use_ok('Koha::Acquisition::Booksellers');
35     use_ok('t::lib::TestBuilder');
36 }
37
38 # Sub used for testing C4::Acquisition subs returning order(s):
39 #    GetOrdersByStatus, GetOrders, GetDeletedOrders, GetOrder etc.
40 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,$test_nbr_fields) =
41 #  _check_fields_of_order ($exp_fields, $original_order_content, $order_to_check);
42 # params :
43 # $exp_fields             : arrayref whose elements are the keys we expect to find
44 # $original_order_content : hashref whose 2 keys str and num contains hashrefs
45 #                           containing content fields of the order created with Koha::Acquisition::Order
46 # $order_to_check         : hashref whose keys/values are the content of an order
47 #                           returned by the C4::Acquisition sub we are testing
48 # returns :
49 # \@test_missing_fields   : arrayref void if ok ; otherwise contains the list of
50 #                           fields missing in $order_to_check
51 # \@test_extra_fields     : arrayref void if ok ; otherwise contains the list of
52 #                           fields unexpected in $order_to_check
53 # \@test_different_fields : arrayref void if ok ; otherwise contains the list of
54 #                           fields which value is not the same in between $order_to_check and
55 # $test_nbr_fields        : contains the number of fields of $order_to_check
56
57 sub _check_fields_of_order {
58     my ( $exp_fields, $original_order_content, $order_to_check ) = @_;
59     my @test_missing_fields   = ();
60     my @test_extra_fields     = ();
61     my @test_different_fields = ();
62     my $test_nbr_fields       = scalar( keys %$order_to_check );
63     foreach my $field (@$exp_fields) {
64         push @test_missing_fields, $field
65           unless exists( $order_to_check->{$field} );
66     }
67     foreach my $field ( keys %$order_to_check ) {
68         push @test_extra_fields, $field
69           unless grep ( /^$field$/, @$exp_fields );
70     }
71     foreach my $field ( keys %{ $original_order_content->{str} } ) {
72         push @test_different_fields, $field
73           unless ( !exists $order_to_check->{$field} )
74           or ( $original_order_content->{str}->{$field} eq
75             $order_to_check->{$field} );
76     }
77     foreach my $field ( keys %{ $original_order_content->{num} } ) {
78         push @test_different_fields, $field
79           unless ( !exists $order_to_check->{$field} )
80           or ( $original_order_content->{num}->{$field} ==
81             $order_to_check->{$field} );
82     }
83     return (
84         \@test_missing_fields,   \@test_extra_fields,
85         \@test_different_fields, $test_nbr_fields
86     );
87 }
88
89 # Sub used for testing C4::Acquisition subs returning several orders
90 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,\@test_nbr_fields) =
91 #   _check_fields_of_orders ($exp_fields, $original_orders_content, $orders_to_check)
92 sub _check_fields_of_orders {
93     my ( $exp_fields, $original_orders_content, $orders_to_check ) = @_;
94     my @test_missing_fields   = ();
95     my @test_extra_fields     = ();
96     my @test_different_fields = ();
97     my @test_nbr_fields       = ();
98     foreach my $order_to_check (@$orders_to_check) {
99         my $original_order_content =
100           ( grep { $_->{str}->{ordernumber} eq $order_to_check->{ordernumber} }
101               @$original_orders_content )[0];
102         my (
103             $t_missing_fields,   $t_extra_fields,
104             $t_different_fields, $t_nbr_fields
105           )
106           = _check_fields_of_order( $exp_fields, $original_order_content,
107             $order_to_check );
108         push @test_missing_fields,   @$t_missing_fields;
109         push @test_extra_fields,     @$t_extra_fields;
110         push @test_different_fields, @$t_different_fields;
111         push @test_nbr_fields,       $t_nbr_fields;
112     }
113     @test_missing_fields = keys %{ { map { $_ => 1 } @test_missing_fields } };
114     @test_extra_fields   = keys %{ { map { $_ => 1 } @test_extra_fields } };
115     @test_different_fields =
116       keys %{ { map { $_ => 1 } @test_different_fields } };
117     return (
118         \@test_missing_fields,   \@test_extra_fields,
119         \@test_different_fields, \@test_nbr_fields
120     );
121 }
122
123
124 my $schema = Koha::Database->new()->schema();
125 $schema->storage->txn_begin();
126
127 my $dbh = C4::Context->dbh;
128 $dbh->{RaiseError} = 1;
129
130 # Creating some orders
131 my $bookseller = Koha::Acquisition::Bookseller->new(
132     {
133         name         => "my vendor",
134         address1     => "bookseller's address",
135         phone        => "0123456",
136         active       => 1,
137         deliverytime => 5,
138     }
139 )->store;
140 my $booksellerid = $bookseller->id;
141
142 my $booksellerinfo = Koha::Acquisition::Booksellers->find( $booksellerid );
143 is( $booksellerinfo->deliverytime,
144     5, 'set deliverytime when creating vendor (Bug 10556)' );
145
146 my ( $basket, $basketno );
147 ok(
148     $basketno = NewBasket( $booksellerid, 1 ),
149     "NewBasket(  $booksellerid , 1  ) returns $basketno"
150 );
151 ok( $basket = GetBasket($basketno), "GetBasket($basketno) returns $basket" );
152
153 my $bpid=AddBudgetPeriod({
154         budget_period_startdate => '2008-01-01'
155         , budget_period_enddate => '2008-12-31'
156         , budget_period_active  => 1
157         , budget_period_description    => "MAPERI"
158 });
159
160 my $budgetid = C4::Budgets::AddBudget(
161     {
162         budget_code => "budget_code_test_1",
163         budget_name => "budget_name_test_1",
164         budget_period_id => $bpid,
165     }
166 );
167 my $budget = C4::Budgets::GetBudget($budgetid);
168
169 my @ordernumbers;
170 my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' );
171 my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' );
172 my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' );
173 my ( $biblionumber4, $biblioitemnumber4 ) = AddBiblio( MARC::Record->new, '' );
174 my ( $biblionumber5, $biblioitemnumber5 ) = AddBiblio( MARC::Record->new, '' );
175
176
177
178 # Prepare 5 orders, and make distinction beween fields to be tested with eq and with ==
179 # Ex : a price of 50.1 will be stored internally as 5.100000
180
181 my @order_content = (
182     {
183         str => {
184             basketno       => $basketno,
185             biblionumber   => $biblionumber1,
186             budget_id      => $budget->{budget_id},
187             uncertainprice => 0,
188             order_internalnote => "internal note",
189             order_vendornote   => "vendor note",
190             ordernumber => '',
191         },
192         num => {
193             quantity  => 24,
194             listprice => 50.121111,
195             ecost     => 38.15,
196             rrp       => 40.15,
197             discount  => 5.1111,
198         }
199     },
200     {
201         str => {
202             basketno     => $basketno,
203             biblionumber => $biblionumber2,
204             budget_id    => $budget->{budget_id}
205         },
206         num => { quantity => 42 }
207     },
208     {
209         str => {
210             basketno       => $basketno,
211             biblionumber   => $biblionumber2,
212             budget_id      => $budget->{budget_id},
213             uncertainprice => 0,
214             order_internalnote => "internal note",
215             order_vendornote   => "vendor note"
216         },
217         num => {
218             quantity  => 4,
219             ecost     => 42.1,
220             rrp       => 42.1,
221             listprice => 10.1,
222             ecost     => 38.1,
223             rrp       => 11.0,
224             discount  => 5.1,
225         }
226     },
227     {
228         str => {
229             basketno     => $basketno,
230             biblionumber => $biblionumber3,
231             budget_id    => $budget->{budget_id},
232             order_internalnote => "internal note",
233             order_vendornote   => "vendor note"
234         },
235         num => {
236             quantity       => 4,
237             ecost          => 40,
238             rrp            => 42,
239             listprice      => 10,
240             ecost          => 38.15,
241             rrp            => 11.00,
242             discount       => 0,
243             uncertainprice => 0,
244         }
245     },
246     {
247         str => {
248             basketno     => $basketno,
249             biblionumber => $biblionumber4,
250             budget_id    => $budget->{budget_id},
251             order_internalnote => "internal note",
252             order_vendornote   => "vendor note"
253         },
254         num => {
255             quantity       => 1,
256             ecost          => 10,
257             rrp            => 10,
258             listprice      => 10,
259             ecost          => 10,
260             rrp            => 10,
261             discount       => 0,
262             uncertainprice => 0,
263         }
264     },
265     {
266         str => {
267             basketno     => $basketno,
268             biblionumber => $biblionumber5,
269             budget_id    => $budget->{budget_id},
270             order_internalnote => "internal note",
271             order_vendornote   => "vendor note"
272         },
273         num => {
274             quantity       => 1,
275             ecost          => 10,
276             rrp            => 10,
277             listprice      => 10,
278             ecost          => 10,
279             rrp            => 10,
280             discount       => 0,
281             uncertainprice => 0,
282         }
283     }
284 );
285
286 # Create 5 orders in database
287 for ( 0 .. 5 ) {
288     my %ocontent;
289     @ocontent{ keys %{ $order_content[$_]->{num} } } =
290       values %{ $order_content[$_]->{num} };
291     @ocontent{ keys %{ $order_content[$_]->{str} } } =
292       values %{ $order_content[$_]->{str} };
293     $ordernumbers[$_] = Koha::Acquisition::Order->new( \%ocontent )->store->ordernumber;
294     $order_content[$_]->{str}->{ordernumber} = $ordernumbers[$_];
295 }
296
297 DelOrder( $order_content[3]->{str}->{biblionumber}, $ordernumbers[3] );
298
299 my $invoiceid = AddInvoice(
300     invoicenumber => 'invoice',
301     booksellerid  => $booksellerid,
302     unknown       => "unknown"
303 );
304
305 my $invoice = GetInvoice( $invoiceid );
306
307 my ($datereceived, $new_ordernumber) = ModReceiveOrder(
308     {
309         biblionumber      => $biblionumber4,
310         order             => Koha::Acquisition::Orders->find( $ordernumbers[4] )->unblessed,
311         quantityreceived  => 1,
312         invoice           => $invoice,
313         budget_id          => $order_content[4]->{str}->{budget_id},
314     }
315 );
316
317 my $search_orders = SearchOrders({
318     booksellerid => $booksellerid,
319     basketno     => $basketno
320 });
321 isa_ok( $search_orders, 'ARRAY' );
322 ok(
323     (
324         ( scalar @$search_orders == 5 )
325           and !grep ( $_->{ordernumber} eq $ordernumbers[3], @$search_orders )
326     ),
327     "SearchOrders only gets non-cancelled orders"
328 );
329
330 $search_orders = SearchOrders({
331     booksellerid => $booksellerid,
332     basketno     => $basketno,
333     pending      => 1
334 });
335 ok(
336     (
337         ( scalar @$search_orders == 4 ) and !grep ( (
338                      ( $_->{ordernumber} eq $ordernumbers[3] )
339                   or ( $_->{ordernumber} eq $ordernumbers[4] )
340             ),
341             @$search_orders )
342     ),
343     "SearchOrders with pending params gets only pending orders (bug 10723)"
344 );
345
346 $search_orders = SearchOrders({
347     booksellerid => $booksellerid,
348     basketno     => $basketno,
349     pending      => 1,
350     ordered      => 1,
351 });
352 is( scalar (@$search_orders), 0, "SearchOrders with pending and ordered params gets only pending ordered orders (bug 11170)" );
353
354 $search_orders = SearchOrders({
355     ordernumber => $ordernumbers[4]
356 });
357 is( scalar (@$search_orders), 1, "SearchOrders takes into account the ordernumber filter" );
358
359 $search_orders = SearchOrders({
360     biblionumber => $biblionumber4
361 });
362 is( scalar (@$search_orders), 1, "SearchOrders takes into account the biblionumber filter" );
363
364 $search_orders = SearchOrders({
365     biblionumber => $biblionumber4,
366     pending      => 1
367 });
368 is( scalar (@$search_orders), 0, "SearchOrders takes into account the biblionumber and pending filters" );
369
370 #
371 # Test GetBudgetByOrderNumber
372 #
373 ok( GetBudgetByOrderNumber( $ordernumbers[0] )->{'budget_id'} eq $budgetid,
374     "GetBudgetByOrderNumber returns expected budget" );
375
376 my @lateorders = GetLateOrders(0);
377 is( scalar grep ( $_->{basketno} eq $basketno, @lateorders ),
378     0, "GetLateOrders does not get orders from opened baskets" );
379 C4::Acquisition::CloseBasket($basketno);
380 @lateorders = GetLateOrders(0);
381 isnt( scalar grep ( $_->{basketno} eq $basketno, @lateorders ),
382     0, "GetLateOrders gets orders from closed baskets" );
383 ok( !grep ( $_->{ordernumber} eq $ordernumbers[3], @lateorders ),
384     "GetLateOrders does not get cancelled orders" );
385 ok( !grep ( $_->{ordernumber} eq $ordernumbers[4], @lateorders ),
386     "GetLateOrders does not get received orders" );
387
388 $search_orders = SearchOrders({
389     booksellerid => $booksellerid,
390     basketno     => $basketno,
391     pending      => 1,
392     ordered      => 1,
393 });
394 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)" );
395
396 #
397 # Test AddClaim
398 #
399
400 my $order = $lateorders[0];
401 AddClaim( $order->{ordernumber} );
402 my $neworder = GetOrder( $order->{ordernumber} );
403 is(
404     $neworder->{claimed_date},
405     strftime( "%Y-%m-%d", localtime(time) ),
406     "AddClaim : Check claimed_date"
407 );
408
409 my $order2 = Koha::Acquisition::Orders->find( $ordernumbers[1] )->unblessed;
410 $order2->{order_internalnote} = "my notes";
411 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
412     {
413         biblionumber     => $biblionumber2,
414         order            => $order2,
415         quantityreceived => 2,
416         invoice          => $invoice,
417     }
418 )
419 ;
420 $order2 = GetOrder( $ordernumbers[1] );
421 is( $order2->{'quantityreceived'},
422     0, 'Splitting up order did not receive any on original order' );
423 is( $order2->{'quantity'}, 40, '40 items on original order' );
424 is( $order2->{'budget_id'}, $budgetid,
425     'Budget on original order is unchanged' );
426 is( $order2->{order_internalnote}, "my notes",
427     'ModReceiveOrder and GetOrder deal with internal notes' );
428
429 $neworder = GetOrder($new_ordernumber);
430 is( $neworder->{'quantity'}, 2, '2 items on new order' );
431 is( $neworder->{'quantityreceived'},
432     2, 'Splitting up order received items on new order' );
433 is( $neworder->{'budget_id'}, $budgetid, 'Budget on new order is unchanged' );
434
435 is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' );
436 is( $neworder->{parent_ordernumber}, $ordernumbers[1], 'Split: test parent_ordernumber' );
437
438 my $orders = GetHistory( ordernumber => $ordernumbers[1] );
439 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumber returns 1 order' );
440 $orders = GetHistory( ordernumber => $ordernumbers[1], search_children_too => 1 );
441 is( scalar( @$orders ), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' );
442 $orders = GetHistory( ordernumbers => [$ordernumbers[1]] );
443 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumbers returns 1 order' );
444 $orders = GetHistory( ordernumbers => \@ordernumbers );
445 is( scalar( @$orders ), scalar( @ordernumbers ) - 1, 'GetHistory with a list of ordernumbers returns N-1 orders (was has been deleted [3])' );
446
447
448 # Test GetHistory() with and without SearchWithISBNVariations
449 # The ISBN passed as a param is the ISBN-10 version of the 13-digit ISBN in the sample record declared in $marcxml
450
451 my $budgetid2 = C4::Budgets::AddBudget(
452     {
453         budget_code => "budget_code_test_modrecv",
454         budget_name => "budget_name_test_modrecv",
455     }
456 );
457
458 my $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
459 $order3->{order_internalnote} = "my other notes";
460 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
461     {
462         biblionumber     => $biblionumber2,
463         order            => $order3,
464         quantityreceived => 2,
465         invoice          => $invoice,
466         budget_id        => $budgetid2,
467     }
468 );
469
470 $order3 = GetOrder( $ordernumbers[2] );
471 is( $order3->{'quantityreceived'},
472     0, 'Splitting up order did not receive any on original order' );
473 is( $order3->{'quantity'}, 2, '2 items on original order' );
474 is( $order3->{'budget_id'}, $budgetid,
475     'Budget on original order is unchanged' );
476 is( $order3->{order_internalnote}, "my other notes",
477     'ModReceiveOrder and GetOrder deal with notes' );
478
479 $neworder = GetOrder($new_ordernumber);
480 is( $neworder->{'quantity'}, 2, '2 items on new order' );
481 is( $neworder->{'quantityreceived'},
482     2, 'Splitting up order received items on new order' );
483 is( $neworder->{'budget_id'}, $budgetid2, 'Budget on new order is changed' );
484
485 $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
486 $order3->{order_internalnote} = "my third 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'}, 2,          'Order not split up' );
499 is( $order3->{'quantity'},         2,          '2 items on order' );
500 is( $order3->{'budget_id'},        $budgetid2, 'Budget has changed' );
501 is( $order3->{order_internalnote}, "my third notes", 'ModReceiveOrder and GetOrder deal with notes' );
502
503 my $nonexistent_order = GetOrder();
504 is( $nonexistent_order, undef, 'GetOrder returns undef if no ordernumber is given' );
505 $nonexistent_order = GetOrder( 424242424242 );
506 is( $nonexistent_order, undef, 'GetOrder returns undef if a nonexistent ordernumber is given' );
507
508 # Tests for DelOrder
509 my $order1 = GetOrder($ordernumbers[0]);
510 my $error = DelOrder($order1->{biblionumber}, $order1->{ordernumber});
511 ok((not defined $error), "DelOrder does not fail");
512 $order1 = GetOrder($order1->{ordernumber});
513 ok((defined $order1->{datecancellationprinted}), "order is cancelled");
514 ok((not defined $order1->{cancellationreason}), "order has no cancellation reason");
515 ok((defined Koha::Biblios->find( $order1->{biblionumber} )), "biblio still exists");
516
517 $order2 = GetOrder($ordernumbers[1]);
518 $error = DelOrder($order2->{biblionumber}, $order2->{ordernumber}, 1);
519 ok((not defined $error), "DelOrder does not fail");
520 $order2 = GetOrder($order2->{ordernumber});
521 ok((defined $order2->{datecancellationprinted}), "order is cancelled");
522 ok((not defined $order2->{cancellationreason}), "order has no cancellation reason");
523 ok((not defined Koha::Biblios->find( $order2->{biblionumber} )), "biblio does not exist anymore");
524
525 my $order4 = GetOrder($ordernumbers[3]);
526 $error = DelOrder($order4->{biblionumber}, $order4->{ordernumber}, 1, "foobar");
527 ok((not defined $error), "DelOrder does not fail");
528 $order4 = GetOrder($order4->{ordernumber});
529 ok((defined $order4->{datecancellationprinted}), "order is cancelled");
530 ok(($order4->{cancellationreason} eq "foobar"), "order has cancellation reason \"foobar\"");
531 ok((not defined Koha::Biblios->find( $order4->{biblionumber} )), "biblio does not exist anymore");
532
533 my $order5 = GetOrder($ordernumbers[4]);
534 C4::Items::AddItem( { barcode => '0102030405' }, $order5->{biblionumber} );
535 $error = DelOrder($order5->{biblionumber}, $order5->{ordernumber}, 1);
536 $order5 = GetOrder($order5->{ordernumber});
537 ok((defined $order5->{datecancellationprinted}), "order is cancelled");
538 ok((defined Koha::Biblios->find( $order5->{biblionumber} )), "biblio still exists");
539
540 # End of tests for DelOrder
541
542 subtest 'ModOrder' => sub {
543     plan tests => 1;
544     ModOrder( { ordernumber => $order1->{ordernumber}, unitprice => 42 } );
545     my $order = GetOrder( $order1->{ordernumber} );
546     is( int($order->{unitprice}), 42, 'ModOrder should work even if biblionumber if not passed');
547 };
548
549 # Budget reports
550 my $all_count = scalar GetBudgetsReport();
551 ok($all_count >= 1, "GetBudgetReport OK");
552
553 my $active_count = scalar GetBudgetsReport(1);
554 ok($active_count >= 1 , "GetBudgetsReport(1) OK");
555
556 is($all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions.");
557 ok($active_count >= scalar GetBudgetsReport(1), "GetBudgetReport doesn't return inactive budget period acquisitions.");
558
559 # "Flavoured" tests (tests that required a run for each marc flavour)
560 # Tests should be added to the run_flavoured_tests sub below
561 my $biblio_module = new Test::MockModule('C4::Biblio');
562 $biblio_module->mock(
563     'GetMarcSubfieldStructure',
564     sub {
565         my ($self) = shift;
566
567         my ( $title_field,            $title_subfield )            = get_title_field();
568         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
569         my ( $issn_field,             $issn_subfield )             = get_issn_field();
570         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
571         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
572         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
573
574         return {
575             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
576             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
577             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
578             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
579             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
580             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
581         };
582       }
583 );
584
585 sub run_flavoured_tests {
586     my $marcflavour = shift;
587     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
588
589     #
590     # Test SearchWithISBNVariations syspref
591     #
592     my $marc_record = MARC::Record->new;
593     $marc_record->append_fields( create_isbn_field( '9780136019701', $marcflavour ) );
594     my ( $biblionumber6, $biblioitemnumber6 ) = AddBiblio( $marc_record, '' );
595
596     # Create order
597     my $ordernumber = Koha::Acquisition::Order->new( {
598             basketno     => $basketno,
599             biblionumber => $biblionumber6,
600             budget_id    => $budget->{budget_id},
601             order_internalnote => "internal note",
602             order_vendornote   => "vendor note",
603             quantity       => 1,
604             ecost          => 10,
605             rrp            => 10,
606             listprice      => 10,
607             ecost          => 10,
608             rrp            => 10,
609             discount       => 0,
610             uncertainprice => 0,
611     } )->store->ordernumber;
612
613     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
614     $orders = GetHistory( isbn => '0136019706' );
615     is( scalar(@$orders), 0, "GetHistory searches correctly by ISBN" );
616
617     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
618     $orders = GetHistory( isbn => '0136019706' );
619     is( scalar(@$orders), 1, "GetHistory searches correctly by ISBN" );
620
621     my $order = GetOrder($ordernumber);
622     DelOrder($order->{biblionumber}, $order->{ordernumber}, 1);
623 }
624
625 # Do "flavoured" tests
626 subtest 'MARC21' => sub {
627     plan tests => 2;
628     run_flavoured_tests('MARC21');
629 };
630
631 subtest 'UNIMARC' => sub {
632     plan tests => 2;
633     run_flavoured_tests('UNIMARC');
634 };
635
636 subtest 'NORMARC' => sub {
637     plan tests => 2;
638     run_flavoured_tests('NORMARC');
639 };
640
641 ### Functions required for "flavoured" tests
642 sub get_title_field {
643     my $marc_flavour = C4::Context->preference('marcflavour');
644     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
645 }
646
647 sub get_isbn_field {
648     my $marc_flavour = C4::Context->preference('marcflavour');
649     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
650 }
651
652 sub get_issn_field {
653     my $marc_flavour = C4::Context->preference('marcflavour');
654     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
655 }
656
657 sub get_itemnumber_field {
658     my $marc_flavour = C4::Context->preference('marcflavour');
659     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
660 }
661
662 sub create_isbn_field {
663     my ( $isbn, $marcflavour ) = @_;
664
665     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
666     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
667
668     # Add the price subfield
669     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
670     $field->add_subfields( $price_subfield => '$100' );
671
672     return $field;
673 }
674
675 subtest 'ModReceiveOrder replacementprice tests' => sub {
676     plan tests => 2;
677     #Let's build an order, we need a couple things though
678     my $builder = t::lib::TestBuilder->new;
679     my $order_biblio = $builder->build({ source => 'Biblio' });
680     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
681     my $order_invoice = $builder->build({ source => 'Aqinvoice'});
682     my $order_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' }  });
683     my $order_vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $order_currency->{currency}, invoiceprice => $order_currency->{currency} } });
684     my $orderinfo ={
685         basketno => $order_basket->{basketno},
686         booksellerid => $order_vendor->{id},
687         rrp => 19.99,
688         replacementprice => undef,
689         quantity => 1,
690         quantityreceived => 0,
691         datereceived => undef,
692         datecancellationprinted => undef,
693     };
694     my $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
695     (undef, my $received_ordernumber) = ModReceiveOrder({
696             biblionumber => $order_biblio->{biblionumber},
697             order        => $receive_order,
698             invoice      => $order_invoice,
699             quantityreceived => $receive_order->{quantity},
700             budget_id    => $order->{budget_id},
701     });
702     my $received_order = GetOrder($received_ordernumber);
703     is ($received_order->{replacementprice},undef,"No price set if none passed in");
704     $orderinfo->{replacementprice} = 16.12;
705     $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
706     (undef, $received_ordernumber) = ModReceiveOrder({
707             biblionumber => $order_biblio->{biblionumber},
708             order        => $receive_order,
709             invoice      => $order_invoice,
710             quantityreceived => $receive_order->{quantity},
711             budget_id    => $order->{budget_id},
712     });
713     $received_order = GetOrder($received_ordernumber);
714     is ($received_order->{replacementprice},'16.120000',"Replacement price set if none passed in");
715 };
716
717 subtest 'ModReceiveOrder and subscription' => sub {
718     plan tests => 2;
719
720     my $builder     = t::lib::TestBuilder->new;
721     my $first_note  = 'first note';
722     my $second_note = 'second note';
723     my $subscription = $builder->build_object( { class => 'Koha::Subscriptions' } );
724     my $order = $builder->build_object(
725         {
726             class => 'Koha::Acquisition::Orders',
727             value => {
728                 subscriptionid     => $subscription->subscriptionid,
729                 order_internalnote => $first_note,
730                 quantity           => 5,
731                 quantityreceived   => 0,
732                 ecost_tax_excluded => 42,
733                 unitprice_tax_excluded => 42,
734             }
735         }
736     );
737     my $order_info = $order->unblessed;
738     # We do not want the note from the original note to be modified
739     # Keeping it will permit to display it for future receptions
740     $order_info->{order_internalnote} = $second_note;
741     my ( undef, $received_ordernumber ) = ModReceiveOrder(
742         {
743             biblionumber     => $order->biblionumber,
744             order            => $order_info,
745             invoice          => $order->{invoiceid},
746             quantityreceived => 1,
747             budget_id        => $order->budget_id,
748         }
749     );
750     my $received_order = Koha::Acquisition::Orders->find($received_ordernumber);
751     is( $received_order->order_internalnote,
752         $second_note, "No price set if none passed in" );
753
754     $order->get_from_storage;
755     is( $order->get_from_storage->order_internalnote, $first_note );
756 };
757
758 subtest 'GetHistory with additional fields' => sub {
759     plan tests => 3;
760     my $builder = t::lib::TestBuilder->new;
761     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
762     my $orderinfo ={
763         basketno => $order_basket->{basketno},
764         rrp => 19.99,
765         replacementprice => undef,
766         quantity => 1,
767         quantityreceived => 0,
768         datereceived => undef,
769         datecancellationprinted => undef,
770     };
771     my $order =        $builder->build({ source => 'Aqorder', value => $orderinfo });
772     my $history = GetHistory(ordernumber => $order->{ordernumber});
773     is( scalar( @$history ), 1, 'GetHistory returns the one order');
774
775     my $additional_field = $builder->build({source => 'AdditionalField', value => {
776             tablename => 'aqbasket',
777             name => 'snakeoil',
778             authorised_value_category => "",
779         }
780     });
781     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
782     is( scalar ( @$history ), 0, 'GetHistory returns no order for an unused additional field');
783     my $basket = Koha::Acquisition::Baskets->find({ basketno => $order_basket->{basketno} });
784     $basket->set_additional_fields([{
785         id => $additional_field->{id},
786         value => 'delicious',
787     }]);
788
789     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
790     is( scalar( @$history ), 1, 'GetHistory returns the order when additional field is set');
791 };
792
793 $schema->storage->txn_rollback();