Bug 22565: (QA follow-up) Fix test Acquisition.t
[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 => 75;
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 $order2 = GetOrder( $ordernumbers[1] );
420 is( $order2->{'quantityreceived'},
421     0, 'Splitting up order did not receive any on original order' );
422 is( $order2->{'quantity'}, 40, '40 items on original order' );
423 is( $order2->{'budget_id'}, $budgetid,
424     'Budget on original order is unchanged' );
425 is( $order2->{order_internalnote}, "my notes",
426     'ModReceiveOrder and GetOrder deal with internal notes' );
427 my $order1 = GetOrder( $ordernumbers[0] );
428 is(
429     $order1->{order_internalnote},
430     "internal note",
431     "ModReceiveOrder only changes the supplied orders internal notes"
432 );
433
434 $neworder = GetOrder($new_ordernumber);
435 is( $neworder->{'quantity'}, 2, '2 items on new order' );
436 is( $neworder->{'quantityreceived'},
437     2, 'Splitting up order received items on new order' );
438 is( $neworder->{'budget_id'}, $budgetid, 'Budget on new order is unchanged' );
439
440 is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' );
441 is( $neworder->{parent_ordernumber}, $ordernumbers[1], 'Split: test parent_ordernumber' );
442
443 my $orders = GetHistory( ordernumber => $ordernumbers[1] );
444 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumber returns 1 order' );
445 $orders = GetHistory( ordernumber => $ordernumbers[1], search_children_too => 1 );
446 is( scalar( @$orders ), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' );
447 $orders = GetHistory( ordernumbers => [$ordernumbers[1]] );
448 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumbers returns 1 order' );
449 $orders = GetHistory( ordernumbers => \@ordernumbers );
450 is( scalar( @$orders ), scalar( @ordernumbers ) - 1, 'GetHistory with a list of ordernumbers returns N-1 orders (was has been deleted [3])' );
451
452
453 # Test GetHistory() with and without SearchWithISBNVariations
454 # The ISBN passed as a param is the ISBN-10 version of the 13-digit ISBN in the sample record declared in $marcxml
455
456 my $budgetid2 = C4::Budgets::AddBudget(
457     {
458         budget_code => "budget_code_test_modrecv",
459         budget_name => "budget_name_test_modrecv",
460     }
461 );
462
463 my $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
464 $order3->{order_internalnote} = "my other notes";
465 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
466     {
467         biblionumber     => $biblionumber2,
468         order            => $order3,
469         quantityreceived => 2,
470         invoice          => $invoice,
471         budget_id        => $budgetid2,
472     }
473 );
474
475 $order3 = GetOrder( $ordernumbers[2] );
476 is( $order3->{'quantityreceived'},
477     0, 'Splitting up order did not receive any on original order' );
478 is( $order3->{'quantity'}, 2, '2 items on original order' );
479 is( $order3->{'budget_id'}, $budgetid,
480     'Budget on original order is unchanged' );
481 is( $order3->{order_internalnote}, "my other notes",
482     'ModReceiveOrder and GetOrder deal with notes' );
483
484 $neworder = GetOrder($new_ordernumber);
485 is( $neworder->{'quantity'}, 2, '2 items on new order' );
486 is( $neworder->{'quantityreceived'},
487     2, 'Splitting up order received items on new order' );
488 is( $neworder->{'budget_id'}, $budgetid2, 'Budget on new order is changed' );
489
490 $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
491 $order3->{order_internalnote} = "my third notes";
492 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
493     {
494         biblionumber     => $biblionumber2,
495         order            => $order3,
496         quantityreceived => 2,
497         invoice          => $invoice,
498         budget_id        => $budgetid2,
499     }
500 );
501
502 $order3 = GetOrder( $ordernumbers[2] );
503 is( $order3->{'quantityreceived'}, 2,          'Order not split up' );
504 is( $order3->{'quantity'},         2,          '2 items on order' );
505 is( $order3->{'budget_id'},        $budgetid2, 'Budget has changed' );
506 is( $order3->{order_internalnote}, "my third notes", 'ModReceiveOrder and GetOrder deal with notes' );
507
508 my $nonexistent_order = GetOrder();
509 is( $nonexistent_order, undef, 'GetOrder returns undef if no ordernumber is given' );
510 $nonexistent_order = GetOrder( 424242424242 );
511 is( $nonexistent_order, undef, 'GetOrder returns undef if a nonexistent ordernumber is given' );
512
513 # Tests for DelOrder
514 $order1 = GetOrder($ordernumbers[0]);
515 my $error = DelOrder($order1->{biblionumber}, $order1->{ordernumber});
516 ok((not defined $error), "DelOrder does not fail");
517 $order1 = GetOrder($order1->{ordernumber});
518 ok((defined $order1->{datecancellationprinted}), "order is cancelled");
519 ok((not defined $order1->{cancellationreason}), "order has no cancellation reason");
520 ok((defined Koha::Biblios->find( $order1->{biblionumber} )), "biblio still exists");
521
522 $order2 = GetOrder($ordernumbers[1]);
523 $error = DelOrder($order2->{biblionumber}, $order2->{ordernumber}, 1);
524 ok((not defined $error), "DelOrder does not fail");
525 $order2 = GetOrder($order2->{ordernumber});
526 ok((defined $order2->{datecancellationprinted}), "order is cancelled");
527 ok((not defined $order2->{cancellationreason}), "order has no cancellation reason");
528 ok((not defined Koha::Biblios->find( $order2->{biblionumber} )), "biblio does not exist anymore");
529
530 my $order4 = GetOrder($ordernumbers[3]);
531 $error = DelOrder($order4->{biblionumber}, $order4->{ordernumber}, 1, "foobar");
532 ok((not defined $error), "DelOrder does not fail");
533 $order4 = GetOrder($order4->{ordernumber});
534 ok((defined $order4->{datecancellationprinted}), "order is cancelled");
535 ok(($order4->{cancellationreason} eq "foobar"), "order has cancellation reason \"foobar\"");
536 ok((not defined Koha::Biblios->find( $order4->{biblionumber} )), "biblio does not exist anymore");
537
538 my $order5 = GetOrder($ordernumbers[4]);
539 C4::Items::AddItem( { barcode => '0102030405' }, $order5->{biblionumber} );
540 $error = DelOrder($order5->{biblionumber}, $order5->{ordernumber}, 1);
541 $order5 = GetOrder($order5->{ordernumber});
542 ok((defined $order5->{datecancellationprinted}), "order is cancelled");
543 ok((defined Koha::Biblios->find( $order5->{biblionumber} )), "biblio still exists");
544
545 # End of tests for DelOrder
546
547 subtest 'ModOrder' => sub {
548     plan tests => 1;
549     ModOrder( { ordernumber => $order1->{ordernumber}, unitprice => 42 } );
550     my $order = GetOrder( $order1->{ordernumber} );
551     is( int($order->{unitprice}), 42, 'ModOrder should work even if biblionumber if not passed');
552 };
553
554 # Budget reports
555 my $all_count = scalar GetBudgetsReport();
556 ok($all_count >= 1, "GetBudgetReport OK");
557
558 my $active_count = scalar GetBudgetsReport(1);
559 ok($active_count >= 1 , "GetBudgetsReport(1) OK");
560
561 is($all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions.");
562 ok($active_count >= scalar GetBudgetsReport(1), "GetBudgetReport doesn't return inactive budget period acquisitions.");
563
564 # "Flavoured" tests (tests that required a run for each marc flavour)
565 # Tests should be added to the run_flavoured_tests sub below
566 my $biblio_module = new Test::MockModule('C4::Biblio');
567 $biblio_module->mock(
568     'GetMarcSubfieldStructure',
569     sub {
570         my ($self) = shift;
571
572         my ( $title_field,            $title_subfield )            = get_title_field();
573         my ( $isbn_field,             $isbn_subfield )             = get_isbn_field();
574         my ( $issn_field,             $issn_subfield )             = get_issn_field();
575         my ( $biblionumber_field,     $biblionumber_subfield )     = ( '999', 'c' );
576         my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' );
577         my ( $itemnumber_field,       $itemnumber_subfield )       = get_itemnumber_field();
578
579         return {
580             'biblio.title'                 => [ { tagfield => $title_field,            tagsubfield => $title_subfield } ],
581             'biblio.biblionumber'          => [ { tagfield => $biblionumber_field,     tagsubfield => $biblionumber_subfield } ],
582             'biblioitems.isbn'             => [ { tagfield => $isbn_field,             tagsubfield => $isbn_subfield } ],
583             'biblioitems.issn'             => [ { tagfield => $issn_field,             tagsubfield => $issn_subfield } ],
584             'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ],
585             'items.itemnumber'             => [ { tagfield => $itemnumber_subfield,    tagsubfield => $itemnumber_subfield } ],
586         };
587       }
588 );
589
590 sub run_flavoured_tests {
591     my $marcflavour = shift;
592     t::lib::Mocks::mock_preference('marcflavour', $marcflavour);
593
594     #
595     # Test SearchWithISBNVariations syspref
596     #
597     my $marc_record = MARC::Record->new;
598     $marc_record->append_fields( create_isbn_field( '9780136019701', $marcflavour ) );
599     my ( $biblionumber6, $biblioitemnumber6 ) = AddBiblio( $marc_record, '' );
600
601     # Create order
602     my $ordernumber = Koha::Acquisition::Order->new( {
603             basketno     => $basketno,
604             biblionumber => $biblionumber6,
605             budget_id    => $budget->{budget_id},
606             order_internalnote => "internal note",
607             order_vendornote   => "vendor note",
608             quantity       => 1,
609             ecost          => 10,
610             rrp            => 10,
611             listprice      => 10,
612             ecost          => 10,
613             rrp            => 10,
614             discount       => 0,
615             uncertainprice => 0,
616     } )->store->ordernumber;
617
618     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
619     $orders = GetHistory( isbn => '0136019706' );
620     is( scalar(@$orders), 0, "GetHistory searches correctly by ISBN" );
621
622     t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
623     $orders = GetHistory( isbn => '0136019706' );
624     is( scalar(@$orders), 1, "GetHistory searches correctly by ISBN" );
625
626     my $order = GetOrder($ordernumber);
627     DelOrder($order->{biblionumber}, $order->{ordernumber}, 1);
628 }
629
630 # Do "flavoured" tests
631 subtest 'MARC21' => sub {
632     plan tests => 2;
633     run_flavoured_tests('MARC21');
634 };
635
636 subtest 'UNIMARC' => sub {
637     plan tests => 2;
638     run_flavoured_tests('UNIMARC');
639 };
640
641 subtest 'NORMARC' => sub {
642     plan tests => 2;
643     run_flavoured_tests('NORMARC');
644 };
645
646 ### Functions required for "flavoured" tests
647 sub get_title_field {
648     my $marc_flavour = C4::Context->preference('marcflavour');
649     return ( $marc_flavour eq 'UNIMARC' ) ? ( '200', 'a' ) : ( '245', 'a' );
650 }
651
652 sub get_isbn_field {
653     my $marc_flavour = C4::Context->preference('marcflavour');
654     return ( $marc_flavour eq 'UNIMARC' ) ? ( '010', 'a' ) : ( '020', 'a' );
655 }
656
657 sub get_issn_field {
658     my $marc_flavour = C4::Context->preference('marcflavour');
659     return ( $marc_flavour eq 'UNIMARC' ) ? ( '011', 'a' ) : ( '022', 'a' );
660 }
661
662 sub get_itemnumber_field {
663     my $marc_flavour = C4::Context->preference('marcflavour');
664     return ( $marc_flavour eq 'UNIMARC' ) ? ( '995', '9' ) : ( '952', '9' );
665 }
666
667 sub create_isbn_field {
668     my ( $isbn, $marcflavour ) = @_;
669
670     my ( $isbn_field, $isbn_subfield ) = get_isbn_field();
671     my $field = MARC::Field->new( $isbn_field, '', '', $isbn_subfield => $isbn );
672
673     # Add the price subfield
674     my $price_subfield = ( $marcflavour eq 'UNIMARC' ) ? 'd' : 'c';
675     $field->add_subfields( $price_subfield => '$100' );
676
677     return $field;
678 }
679
680 subtest 'ModReceiveOrder replacementprice tests' => sub {
681     plan tests => 2;
682     #Let's build an order, we need a couple things though
683     my $builder = t::lib::TestBuilder->new;
684     my $order_biblio = $builder->build({ source => 'Biblio' });
685     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
686     my $order_invoice = $builder->build({ source => 'Aqinvoice'});
687     my $order_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' }  });
688     my $order_vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $order_currency->{currency}, invoiceprice => $order_currency->{currency} } });
689     my $orderinfo ={
690         basketno => $order_basket->{basketno},
691         booksellerid => $order_vendor->{id},
692         rrp => 19.99,
693         replacementprice => undef,
694         quantity => 1,
695         quantityreceived => 0,
696         datereceived => undef,
697         datecancellationprinted => undef,
698     };
699     my $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
700     (undef, my $received_ordernumber) = ModReceiveOrder({
701             biblionumber => $order_biblio->{biblionumber},
702             order        => $receive_order,
703             invoice      => $order_invoice,
704             quantityreceived => $receive_order->{quantity},
705             budget_id    => $order->{budget_id},
706     });
707     my $received_order = GetOrder($received_ordernumber);
708     is ($received_order->{replacementprice},undef,"No price set if none passed in");
709     $orderinfo->{replacementprice} = 16.12;
710     $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo });
711     (undef, $received_ordernumber) = ModReceiveOrder({
712             biblionumber => $order_biblio->{biblionumber},
713             order        => $receive_order,
714             invoice      => $order_invoice,
715             quantityreceived => $receive_order->{quantity},
716             budget_id    => $order->{budget_id},
717     });
718     $received_order = GetOrder($received_ordernumber);
719     is ($received_order->{replacementprice},'16.120000',"Replacement price set if none passed in");
720 };
721
722 subtest 'ModReceiveOrder and subscription' => sub {
723     plan tests => 2;
724
725     my $builder     = t::lib::TestBuilder->new;
726     my $first_note  = 'first note';
727     my $second_note = 'second note';
728     my $subscription = $builder->build_object( { class => 'Koha::Subscriptions' } );
729     my $order = $builder->build_object(
730         {
731             class => 'Koha::Acquisition::Orders',
732             value => {
733                 subscriptionid     => $subscription->subscriptionid,
734                 order_internalnote => $first_note,
735                 quantity           => 5,
736                 quantityreceived   => 0,
737                 ecost_tax_excluded => 42,
738                 unitprice_tax_excluded => 42,
739             }
740         }
741     );
742     my $order_info = $order->unblessed;
743     # We do not want the note from the original note to be modified
744     # Keeping it will permit to display it for future receptions
745     $order_info->{order_internalnote} = $second_note;
746     my ( undef, $received_ordernumber ) = ModReceiveOrder(
747         {
748             biblionumber     => $order->biblionumber,
749             order            => $order_info,
750             invoice          => $order->{invoiceid},
751             quantityreceived => 1,
752             budget_id        => $order->budget_id,
753         }
754     );
755     my $received_order = Koha::Acquisition::Orders->find($received_ordernumber);
756     is( $received_order->order_internalnote,
757         $second_note, "No price set if none passed in" );
758
759     $order->get_from_storage;
760     is( $order->get_from_storage->order_internalnote, $first_note );
761 };
762
763 subtest 'GetHistory with additional fields' => sub {
764     plan tests => 3;
765     my $builder = t::lib::TestBuilder->new;
766     my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } });
767     my $orderinfo ={
768         basketno => $order_basket->{basketno},
769         rrp => 19.99,
770         replacementprice => undef,
771         quantity => 1,
772         quantityreceived => 0,
773         datereceived => undef,
774         datecancellationprinted => undef,
775     };
776     my $order =        $builder->build({ source => 'Aqorder', value => $orderinfo });
777     my $history = GetHistory(ordernumber => $order->{ordernumber});
778     is( scalar( @$history ), 1, 'GetHistory returns the one order');
779
780     my $additional_field = $builder->build({source => 'AdditionalField', value => {
781             tablename => 'aqbasket',
782             name => 'snakeoil',
783             authorised_value_category => "",
784         }
785     });
786     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
787     is( scalar ( @$history ), 0, 'GetHistory returns no order for an unused additional field');
788     my $basket = Koha::Acquisition::Baskets->find({ basketno => $order_basket->{basketno} });
789     $basket->set_additional_fields([{
790         id => $additional_field->{id},
791         value => 'delicious',
792     }]);
793
794     $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]);
795     is( scalar( @$history ), 1, 'GetHistory returns the order when additional field is set');
796 };
797
798 $schema->storage->txn_rollback();