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