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