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