Bug 17457: Adv. Acquisition search with ISBN variations
[srvgit] / 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 => 67;
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 }
35
36 # Sub used for testing C4::Acquisition subs returning order(s):
37 #    GetOrdersByStatus, GetOrders, GetDeletedOrders, GetOrder etc.
38 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,$test_nbr_fields) =
39 #  _check_fields_of_order ($exp_fields, $original_order_content, $order_to_check);
40 # params :
41 # $exp_fields             : arrayref whose elements are the keys we expect to find
42 # $original_order_content : hashref whose 2 keys str and num contains hashrefs
43 #                           containing content fields of the order created with Koha::Acquisition::Order
44 # $order_to_check         : hashref whose keys/values are the content of an order
45 #                           returned by the C4::Acquisition sub we are testing
46 # returns :
47 # \@test_missing_fields   : arrayref void if ok ; otherwise contains the list of
48 #                           fields missing in $order_to_check
49 # \@test_extra_fields     : arrayref void if ok ; otherwise contains the list of
50 #                           fields unexpected in $order_to_check
51 # \@test_different_fields : arrayref void if ok ; otherwise contains the list of
52 #                           fields which value is not the same in between $order_to_check and
53 # $test_nbr_fields        : contains the number of fields of $order_to_check
54
55 sub _check_fields_of_order {
56     my ( $exp_fields, $original_order_content, $order_to_check ) = @_;
57     my @test_missing_fields   = ();
58     my @test_extra_fields     = ();
59     my @test_different_fields = ();
60     my $test_nbr_fields       = scalar( keys %$order_to_check );
61     foreach my $field (@$exp_fields) {
62         push @test_missing_fields, $field
63           unless exists( $order_to_check->{$field} );
64     }
65     foreach my $field ( keys %$order_to_check ) {
66         push @test_extra_fields, $field
67           unless grep ( /^$field$/, @$exp_fields );
68     }
69     foreach my $field ( keys %{ $original_order_content->{str} } ) {
70         push @test_different_fields, $field
71           unless ( !exists $order_to_check->{$field} )
72           or ( $original_order_content->{str}->{$field} eq
73             $order_to_check->{$field} );
74     }
75     foreach my $field ( keys %{ $original_order_content->{num} } ) {
76         push @test_different_fields, $field
77           unless ( !exists $order_to_check->{$field} )
78           or ( $original_order_content->{num}->{$field} ==
79             $order_to_check->{$field} );
80     }
81     return (
82         \@test_missing_fields,   \@test_extra_fields,
83         \@test_different_fields, $test_nbr_fields
84     );
85 }
86
87 # Sub used for testing C4::Acquisition subs returning several orders
88 # (\@test_missing_fields,\@test_extra_fields,\@test_different_fields,\@test_nbr_fields) =
89 #   _check_fields_of_orders ($exp_fields, $original_orders_content, $orders_to_check)
90 sub _check_fields_of_orders {
91     my ( $exp_fields, $original_orders_content, $orders_to_check ) = @_;
92     my @test_missing_fields   = ();
93     my @test_extra_fields     = ();
94     my @test_different_fields = ();
95     my @test_nbr_fields       = ();
96     foreach my $order_to_check (@$orders_to_check) {
97         my $original_order_content =
98           ( grep { $_->{str}->{ordernumber} eq $order_to_check->{ordernumber} }
99               @$original_orders_content )[0];
100         my (
101             $t_missing_fields,   $t_extra_fields,
102             $t_different_fields, $t_nbr_fields
103           )
104           = _check_fields_of_order( $exp_fields, $original_order_content,
105             $order_to_check );
106         push @test_missing_fields,   @$t_missing_fields;
107         push @test_extra_fields,     @$t_extra_fields;
108         push @test_different_fields, @$t_different_fields;
109         push @test_nbr_fields,       $t_nbr_fields;
110     }
111     @test_missing_fields = keys %{ { map { $_ => 1 } @test_missing_fields } };
112     @test_extra_fields   = keys %{ { map { $_ => 1 } @test_extra_fields } };
113     @test_different_fields =
114       keys %{ { map { $_ => 1 } @test_different_fields } };
115     return (
116         \@test_missing_fields,   \@test_extra_fields,
117         \@test_different_fields, \@test_nbr_fields
118     );
119 }
120
121
122 my $schema = Koha::Database->new()->schema();
123 $schema->storage->txn_begin();
124
125 my $dbh = C4::Context->dbh;
126 $dbh->{RaiseError} = 1;
127
128 # Creating some orders
129 my $bookseller = Koha::Acquisition::Bookseller->new(
130     {
131         name         => "my vendor",
132         address1     => "bookseller's address",
133         phone        => "0123456",
134         active       => 1,
135         deliverytime => 5,
136     }
137 )->store;
138 my $booksellerid = $bookseller->id;
139
140 my $booksellerinfo = Koha::Acquisition::Booksellers->find( $booksellerid );
141 is( $booksellerinfo->deliverytime,
142     5, 'set deliverytime when creating vendor (Bug 10556)' );
143
144 my ( $basket, $basketno );
145 ok(
146     $basketno = NewBasket( $booksellerid, 1 ),
147     "NewBasket(  $booksellerid , 1  ) returns $basketno"
148 );
149 ok( $basket = GetBasket($basketno), "GetBasket($basketno) returns $basket" );
150
151 my $bpid=AddBudgetPeriod({
152         budget_period_startdate => '2008-01-01'
153         , budget_period_enddate => '2008-12-31'
154         , budget_period_active  => 1
155         , budget_period_description    => "MAPERI"
156 });
157
158 my $budgetid = C4::Budgets::AddBudget(
159     {
160         budget_code => "budget_code_test_1",
161         budget_name => "budget_name_test_1",
162         budget_period_id => $bpid,
163     }
164 );
165 my $budget = C4::Budgets::GetBudget($budgetid);
166
167 # Prepare a sample MARC record with a ISBN to test GetHistory()
168 my $marcxml = qq{<?xml version="1.0" encoding="UTF-8"?>
169 <record
170     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
171     xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"
172     xmlns="http://www.loc.gov/MARC21/slim">
173
174   <leader>03108cam a2200277 i 4500</leader>
175   <controlfield tag="001">a2526595</controlfield>
176   <controlfield tag="003">Koha</controlfield>
177   <controlfield tag="005">20170306104815.0</controlfield>
178   <controlfield tag="006">m     o  d        </controlfield>
179   <controlfield tag="007">cr |||||||||||</controlfield>
180   <controlfield tag="008">150723s2016    vau      b    000 0 eng d</controlfield>
181   <datafield tag="020" ind1=" " ind2=" ">
182     <subfield code="a">9780136019701</subfield>
183   </datafield>
184 </record>
185 };
186
187 my @ordernumbers;
188 my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' );
189 my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' );
190 my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' );
191 my ( $biblionumber4, $biblioitemnumber4 ) = AddBiblio( MARC::Record->new, '' );
192 my ( $biblionumber5, $biblioitemnumber5 ) = AddBiblio( MARC::Record->new_from_xml( $marcxml, 'utf8', 'MARC21' ), '' );
193
194 # Prepare 5 orders, and make distinction beween fields to be tested with eq and with ==
195 # Ex : a price of 50.1 will be stored internally as 5.100000
196
197 my @order_content = (
198     {
199         str => {
200             basketno       => $basketno,
201             biblionumber   => $biblionumber1,
202             budget_id      => $budget->{budget_id},
203             uncertainprice => 0,
204             order_internalnote => "internal note",
205             order_vendornote   => "vendor note",
206             ordernumber => '',
207         },
208         num => {
209             quantity  => 24,
210             listprice => 50.121111,
211             ecost     => 38.15,
212             rrp       => 40.15,
213             discount  => 5.1111,
214         }
215     },
216     {
217         str => {
218             basketno     => $basketno,
219             biblionumber => $biblionumber2,
220             budget_id    => $budget->{budget_id}
221         },
222         num => { quantity => 42 }
223     },
224     {
225         str => {
226             basketno       => $basketno,
227             biblionumber   => $biblionumber2,
228             budget_id      => $budget->{budget_id},
229             uncertainprice => 0,
230             order_internalnote => "internal note",
231             order_vendornote   => "vendor note"
232         },
233         num => {
234             quantity  => 4,
235             ecost     => 42.1,
236             rrp       => 42.1,
237             listprice => 10.1,
238             ecost     => 38.1,
239             rrp       => 11.0,
240             discount  => 5.1,
241         }
242     },
243     {
244         str => {
245             basketno     => $basketno,
246             biblionumber => $biblionumber3,
247             budget_id    => $budget->{budget_id},
248             order_internalnote => "internal note",
249             order_vendornote   => "vendor note"
250         },
251         num => {
252             quantity       => 4,
253             ecost          => 40,
254             rrp            => 42,
255             listprice      => 10,
256             ecost          => 38.15,
257             rrp            => 11.00,
258             discount       => 0,
259             uncertainprice => 0,
260         }
261     },
262     {
263         str => {
264             basketno     => $basketno,
265             biblionumber => $biblionumber4,
266             budget_id    => $budget->{budget_id},
267             order_internalnote => "internal note",
268             order_vendornote   => "vendor note"
269         },
270         num => {
271             quantity       => 1,
272             ecost          => 10,
273             rrp            => 10,
274             listprice      => 10,
275             ecost          => 10,
276             rrp            => 10,
277             discount       => 0,
278             uncertainprice => 0,
279         }
280     },
281     {
282         str => {
283             basketno     => $basketno,
284             biblionumber => $biblionumber5,
285             budget_id    => $budget->{budget_id},
286             order_internalnote => "internal note",
287             order_vendornote   => "vendor note"
288         },
289         num => {
290             quantity       => 1,
291             ecost          => 10,
292             rrp            => 10,
293             listprice      => 10,
294             ecost          => 10,
295             rrp            => 10,
296             discount       => 0,
297             uncertainprice => 0,
298         }
299     }
300 );
301
302 # Create 5 orders in database
303 for ( 0 .. 5 ) {
304     my %ocontent;
305     @ocontent{ keys %{ $order_content[$_]->{num} } } =
306       values %{ $order_content[$_]->{num} };
307     @ocontent{ keys %{ $order_content[$_]->{str} } } =
308       values %{ $order_content[$_]->{str} };
309     $ordernumbers[$_] = Koha::Acquisition::Order->new( \%ocontent )->store->ordernumber;
310     $order_content[$_]->{str}->{ordernumber} = $ordernumbers[$_];
311 }
312
313 DelOrder( $order_content[3]->{str}->{biblionumber}, $ordernumbers[3] );
314
315 my $invoiceid = AddInvoice(
316     invoicenumber => 'invoice',
317     booksellerid  => $booksellerid,
318     unknown       => "unknown"
319 );
320
321 my $invoice = GetInvoice( $invoiceid );
322
323 my ($datereceived, $new_ordernumber) = ModReceiveOrder(
324     {
325         biblionumber      => $biblionumber4,
326         order             => Koha::Acquisition::Orders->find( $ordernumbers[4] )->unblessed,
327         quantityreceived  => 1,
328         invoice           => $invoice,
329         budget_id          => $order_content[4]->{str}->{budget_id},
330     }
331 );
332
333 my $search_orders = SearchOrders({
334     booksellerid => $booksellerid,
335     basketno     => $basketno
336 });
337 isa_ok( $search_orders, 'ARRAY' );
338 ok(
339     (
340         ( scalar @$search_orders == 5 )
341           and !grep ( $_->{ordernumber} eq $ordernumbers[3], @$search_orders )
342     ),
343     "SearchOrders only gets non-cancelled orders"
344 );
345
346 $search_orders = SearchOrders({
347     booksellerid => $booksellerid,
348     basketno     => $basketno,
349     pending      => 1
350 });
351 ok(
352     (
353         ( scalar @$search_orders == 4 ) and !grep ( (
354                      ( $_->{ordernumber} eq $ordernumbers[3] )
355                   or ( $_->{ordernumber} eq $ordernumbers[4] )
356             ),
357             @$search_orders )
358     ),
359     "SearchOrders with pending params gets only pending orders (bug 10723)"
360 );
361
362 $search_orders = SearchOrders({
363     booksellerid => $booksellerid,
364     basketno     => $basketno,
365     pending      => 1,
366     ordered      => 1,
367 });
368 is( scalar (@$search_orders), 0, "SearchOrders with pending and ordered params gets only pending ordered orders (bug 11170)" );
369
370 $search_orders = SearchOrders({
371     ordernumber => $ordernumbers[4]
372 });
373 is( scalar (@$search_orders), 1, "SearchOrders takes into account the ordernumber filter" );
374
375 $search_orders = SearchOrders({
376     biblionumber => $biblionumber4
377 });
378 is( scalar (@$search_orders), 1, "SearchOrders takes into account the biblionumber filter" );
379
380 $search_orders = SearchOrders({
381     biblionumber => $biblionumber4,
382     pending      => 1
383 });
384 is( scalar (@$search_orders), 0, "SearchOrders takes into account the biblionumber and pending filters" );
385
386 #
387 # Test GetBudgetByOrderNumber
388 #
389 ok( GetBudgetByOrderNumber( $ordernumbers[0] )->{'budget_id'} eq $budgetid,
390     "GetBudgetByOrderNumber returns expected budget" );
391
392 my @lateorders = GetLateOrders(0);
393 is( scalar grep ( $_->{basketno} eq $basketno, @lateorders ),
394     0, "GetLateOrders does not get orders from opened baskets" );
395 C4::Acquisition::CloseBasket($basketno);
396 @lateorders = GetLateOrders(0);
397 isnt( scalar grep ( $_->{basketno} eq $basketno, @lateorders ),
398     0, "GetLateOrders gets orders from closed baskets" );
399 ok( !grep ( $_->{ordernumber} eq $ordernumbers[3], @lateorders ),
400     "GetLateOrders does not get cancelled orders" );
401 ok( !grep ( $_->{ordernumber} eq $ordernumbers[4], @lateorders ),
402     "GetLateOrders does not get received orders" );
403
404 $search_orders = SearchOrders({
405     booksellerid => $booksellerid,
406     basketno     => $basketno,
407     pending      => 1,
408     ordered      => 1,
409 });
410 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)" );
411
412 #
413 # Test AddClaim
414 #
415
416 my $order = $lateorders[0];
417 AddClaim( $order->{ordernumber} );
418 my $neworder = GetOrder( $order->{ordernumber} );
419 is(
420     $neworder->{claimed_date},
421     strftime( "%Y-%m-%d", localtime(time) ),
422     "AddClaim : Check claimed_date"
423 );
424
425 my $order2 = Koha::Acquisition::Orders->find( $ordernumbers[1] )->unblessed;
426 $order2->{order_internalnote} = "my notes";
427 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
428     {
429         biblionumber     => $biblionumber2,
430         order            => $order2,
431         quantityreceived => 2,
432         invoice          => $invoice,
433     }
434 )
435 ;
436 $order2 = GetOrder( $ordernumbers[1] );
437 is( $order2->{'quantityreceived'},
438     0, 'Splitting up order did not receive any on original order' );
439 is( $order2->{'quantity'}, 40, '40 items on original order' );
440 is( $order2->{'budget_id'}, $budgetid,
441     'Budget on original order is unchanged' );
442 is( $order2->{order_internalnote}, "my notes",
443     'ModReceiveOrder and GetOrder deal with internal notes' );
444
445 $neworder = GetOrder($new_ordernumber);
446 is( $neworder->{'quantity'}, 2, '2 items on new order' );
447 is( $neworder->{'quantityreceived'},
448     2, 'Splitting up order received items on new order' );
449 is( $neworder->{'budget_id'}, $budgetid, 'Budget on new order is unchanged' );
450
451 is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' );
452 is( $neworder->{parent_ordernumber}, $ordernumbers[1], 'Split: test parent_ordernumber' );
453
454 my $orders = GetHistory( ordernumber => $ordernumbers[1] );
455 is( scalar( @$orders ), 1, 'GetHistory with a given ordernumber returns 1 order' );
456 $orders = GetHistory( ordernumber => $ordernumbers[1], search_children_too => 1 );
457 is( scalar( @$orders ), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' );
458
459 # Test GetHistory() with and without SearchWithISBNVariations
460 # The ISBN passed as a param is the ISBN-10 version of the 13-digit ISBN in the sample record declared in $marcxml
461 t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0);
462 $orders = GetHistory( isbn => '0136019706' );
463 is( scalar(@$orders), 0, "GetHistory searches correctly by ISBN" );
464
465 t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1);
466 $orders = GetHistory( isbn => '0136019706' );
467 is( scalar(@$orders), 1, "GetHistory searches correctly by ISBN" );
468
469 my $budgetid2 = C4::Budgets::AddBudget(
470     {
471         budget_code => "budget_code_test_modrecv",
472         budget_name => "budget_name_test_modrecv",
473     }
474 );
475
476 my $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
477 $order3->{order_internalnote} = "my other notes";
478 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
479     {
480         biblionumber     => $biblionumber2,
481         order            => $order3,
482         quantityreceived => 2,
483         invoice          => $invoice,
484         budget_id        => $budgetid2,
485     }
486 );
487
488 $order3 = GetOrder( $ordernumbers[2] );
489 is( $order3->{'quantityreceived'},
490     0, 'Splitting up order did not receive any on original order' );
491 is( $order3->{'quantity'}, 2, '2 items on original order' );
492 is( $order3->{'budget_id'}, $budgetid,
493     'Budget on original order is unchanged' );
494 is( $order3->{order_internalnote}, "my other notes",
495     'ModReceiveOrder and GetOrder deal with notes' );
496
497 $neworder = GetOrder($new_ordernumber);
498 is( $neworder->{'quantity'}, 2, '2 items on new order' );
499 is( $neworder->{'quantityreceived'},
500     2, 'Splitting up order received items on new order' );
501 is( $neworder->{'budget_id'}, $budgetid2, 'Budget on new order is changed' );
502
503 $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed;
504 $order3->{order_internalnote} = "my third notes";
505 ( $datereceived, $new_ordernumber ) = ModReceiveOrder(
506     {
507         biblionumber     => $biblionumber2,
508         order            => $order3,
509         quantityreceived => 2,
510         invoice          => $invoice,
511         budget_id        => $budgetid2,
512     }
513 );
514
515 $order3 = GetOrder( $ordernumbers[2] );
516 is( $order3->{'quantityreceived'}, 2,          'Order not split up' );
517 is( $order3->{'quantity'},         2,          '2 items on order' );
518 is( $order3->{'budget_id'},        $budgetid2, 'Budget has changed' );
519 is( $order3->{order_internalnote}, "my third notes", 'ModReceiveOrder and GetOrder deal with notes' );
520
521 my $nonexistent_order = GetOrder();
522 is( $nonexistent_order, undef, 'GetOrder returns undef if no ordernumber is given' );
523 $nonexistent_order = GetOrder( 424242424242 );
524 is( $nonexistent_order, undef, 'GetOrder returns undef if a nonexistent ordernumber is given' );
525
526 # Tests for DelOrder
527 my $order1 = GetOrder($ordernumbers[0]);
528 my $error = DelOrder($order1->{biblionumber}, $order1->{ordernumber});
529 ok((not defined $error), "DelOrder does not fail");
530 $order1 = GetOrder($order1->{ordernumber});
531 ok((defined $order1->{datecancellationprinted}), "order is cancelled");
532 ok((not defined $order1->{cancellationreason}), "order has no cancellation reason");
533 ok((defined Koha::Biblios->find( $order1->{biblionumber} )), "biblio still exists");
534
535 $order2 = GetOrder($ordernumbers[1]);
536 $error = DelOrder($order2->{biblionumber}, $order2->{ordernumber}, 1);
537 ok((not defined $error), "DelOrder does not fail");
538 $order2 = GetOrder($order2->{ordernumber});
539 ok((defined $order2->{datecancellationprinted}), "order is cancelled");
540 ok((not defined $order2->{cancellationreason}), "order has no cancellation reason");
541 ok((not defined Koha::Biblios->find( $order2->{biblionumber} )), "biblio does not exist anymore");
542
543 my $order4 = GetOrder($ordernumbers[3]);
544 $error = DelOrder($order4->{biblionumber}, $order4->{ordernumber}, 1, "foobar");
545 ok((not defined $error), "DelOrder does not fail");
546 $order4 = GetOrder($order4->{ordernumber});
547 ok((defined $order4->{datecancellationprinted}), "order is cancelled");
548 ok(($order4->{cancellationreason} eq "foobar"), "order has cancellation reason \"foobar\"");
549 ok((not defined Koha::Biblios->find( $order4->{biblionumber} )), "biblio does not exist anymore");
550
551 my $order5 = GetOrder($ordernumbers[4]);
552 C4::Items::AddItem( { barcode => '0102030405' }, $order5->{biblionumber} );
553 $error = DelOrder($order5->{biblionumber}, $order5->{ordernumber}, 1);
554 $order5 = GetOrder($order5->{ordernumber});
555 ok((defined $order5->{datecancellationprinted}), "order is cancelled");
556 ok((defined Koha::Biblios->find( $order5->{biblionumber} )), "biblio still exists");
557
558 # End of tests for DelOrder
559
560 subtest 'ModOrder' => sub {
561     plan tests => 1;
562     ModOrder( { ordernumber => $order1->{ordernumber}, unitprice => 42 } );
563     my $order = GetOrder( $order1->{ordernumber} );
564     is( int($order->{unitprice}), 42, 'ModOrder should work even if biblionumber if not passed');
565 };
566
567 # Budget reports
568 my $all_count = scalar GetBudgetsReport();
569 ok($all_count >= 1, "GetBudgetReport OK");
570
571 my $active_count = scalar GetBudgetsReport(1);
572 ok($active_count >= 1 , "GetBudgetsReport(1) OK");
573
574 is($all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions.");
575 ok($active_count >= scalar GetBudgetsReport(1), "GetBudgetReport doesn't return inactive budget period acquisitions.");
576
577 $schema->storage->txn_rollback();