Bug 29234: Further clean Z3950 Tests
[koha-ffzg.git] / t / db_dependent / api / v1 / acquisitions_orders.t
1 #!/usr/bin/env 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 Test::More tests => 5;
21 use Test::Mojo;
22 use Test::Warn;
23
24 use t::lib::TestBuilder;
25 use t::lib::Mocks;
26
27 use JSON qw( encode_json );
28
29 use Koha::Acquisition::Orders;
30 use Koha::Database;
31
32 my $schema  = Koha::Database->new->schema;
33 my $builder = t::lib::TestBuilder->new;
34
35 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
36
37 my $t = Test::Mojo->new('Koha::REST::V1');
38
39 subtest 'list() tests' => sub {
40
41     plan tests => 24;
42
43     $schema->storage->txn_begin;
44
45     my $patron = $builder->build_object({
46         class => 'Koha::Patrons',
47         value => { flags => 1 }
48     });
49     my $password = 'thePassword123';
50     $patron->set_password({ password => $password, skip_validation => 1 });
51     my $userid = $patron->userid;
52
53     my $basket = $builder->build_object({ class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } });
54
55     my $biblio = $builder->build_sample_biblio;
56     my $biblioitem = $biblio->biblioitem;
57     $biblioitem->set({ isbn => 'SOMETHING' })->store;
58
59     # Create test context
60     my $order = $builder->build_object(
61         {
62             class => 'Koha::Acquisition::Orders',
63             value => {
64                 basketno     => $basket->basketno,
65                 orderstatus  => 'new',
66                 biblionumber => $biblio->biblionumber
67             }
68         }
69     );
70     my $another_order = $order->unblessed; # create a copy of $order but make
71     delete $another_order->{ordernumber};  # sure ordernumber will be regenerated
72     $another_order = $builder->build_object({ class => 'Koha::Acquisition::Orders', value => $another_order });
73
74     ## Authorized user tests
75     my $count_of_orders = Koha::Acquisition::Orders->search->count;
76     # Make sure we are returned with the correct amount of orders
77     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_per_page=-1" )
78       ->status_is( 200, 'SWAGGER3.2.2' )
79       ->json_has('/'.($count_of_orders-1).'/order_id')
80       ->json_hasnt('/'.($count_of_orders).'/order_id');
81
82     subtest 'query parameters' => sub {
83
84         my $fields = {
85             biblio_id => 'biblionumber',
86             basket_id => 'basketno',
87             fund_id   => 'budget_id',
88         };
89
90         my $size = keys %{$fields};
91
92         plan tests => $size * (2 + 2 * $size);
93
94         foreach my $field ( keys %{$fields} ) {
95             my $model_field = $fields->{ $field };
96             my $result = $t->get_ok("//$userid:$password@/api/v1/acquisitions/orders?$field=" . $order->$model_field)
97               ->status_is(200);
98
99             foreach my $key ( keys %{$fields} ) {
100               my $key_field = $fields->{ $key };
101               # Check the result order first since it's not predefined.
102               if ($result->tx->res->json->[0]->{$key} eq $order->$key_field) {
103                 $result->json_is( "/0/$key", $order->$key_field );
104                 $result->json_is( "/1/$key", $another_order->$key_field );
105               } else {
106                 $result->json_is( "/0/$key", $another_order->$key_field );
107                 $result->json_is( "/1/$key", $order->$key_field );
108               }
109             }
110         }
111     };
112
113     my $query = { "biblio.isbn" => { "-like" => "\%SOMETHING\%" } };
114     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => {'x-koha-embed' => 'biblio'} )
115       ->status_is( 200, "Embedding biblio and searching on biblio.isbn doesn't make it explode" )
116       ->json_has( "/0/biblio", "biblio object correctly embedded" )
117       ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitems column works!' );
118
119     $query = { "biblio.isbn" => { "-like" => "\%SOMETHING\%" }, "biblio.title" => { -like => "\%\%" } };
120     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => {'x-koha-embed' => 'biblio'} )
121       ->status_is( 200, "Embedding biblio and searching on biblio.isbn and biblio.title doesn't make it explode" )
122       ->json_has( "/0/biblio", "biblio object correctly embedded" )
123       ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitem column works!' )
124       ->json_is( "/0/biblio/title", $biblio->title, 'Filtering by a biblioitem and biblio columns works!' );
125
126     my $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?biblio_id=" . $biblio->biblionumber )
127       ->status_is( 200 );
128
129     is( scalar @{ $result->tx->res->json}, 2, 'Two orders fetched' );
130
131     # Mark $another_order as cancelled
132     $another_order->set({ orderstatus => 'cancelled' })->store;
133
134     $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?only_active=1&biblio_id=" . $biblio->biblionumber )
135       ->status_is( 200, "only_active parameter accepted" );
136
137     is( scalar @{ $result->tx->res->json}, 1, 'Only one order is active' );
138
139     # Warn on unsupported query parameter
140     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?order_blah=blah" )
141       ->status_is(400)
142       ->json_is( [{ path => '/query/order_blah', message => 'Malformed query string'}] );
143
144     subtest 'sorting tests' => sub {
145
146         plan tests => 14;
147
148         $schema->storage->txn_begin;
149
150         my $biblio_1 = $builder->build_sample_biblio();
151         my $biblio_2 = $builder->build_sample_biblio();
152
153         my $basket = $builder->build_object({ class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } });
154         my $order_1 = $builder->build_object(
155             {
156                 class => 'Koha::Acquisition::Orders',
157                 value => {
158                     basketno     => $basket->basketno,
159                     orderstatus  => 'new',
160                     biblionumber => $biblio_1->biblionumber
161                 }
162             }
163         );
164         my $order_2 = $builder->build_object(
165             {
166                 class => 'Koha::Acquisition::Orders',
167                 value => {
168                     basketno     => $basket->basketno,
169                     orderstatus  => 'new',
170                     biblionumber => $biblio_2->biblionumber
171                 }
172             }
173         );
174
175         # order by order_id
176         my $result =
177           $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=+me.order_id&basket_id=" . $basket->id )
178             ->status_is( 200, "query successful" )
179             ->tx->res->json;
180
181         is( scalar @$result, 2, 'Two elements returned' );
182
183         is( $result->[0]->{order_id}, $order_1->id, 'The first element is order_1' );
184         is( $result->[1]->{order_id}, $order_2->id, 'The second element is order_2' );
185
186         # now reverse order
187         $result =
188           $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-me.order_id&basket_id=" . $basket->id )
189             ->status_is( 200, "query successful" )
190             ->tx->res->json;
191
192         is( scalar @$result, 2, 'Two elements returned' );
193
194         is( $result->[0]->{order_id}, $order_2->id, 'The first element is order_2' );
195         is( $result->[1]->{order_id}, $order_1->id, 'The second element is order_1' );
196
197         $biblio_1->biblioitem->set(
198             {
199                 isbn          => 'A',
200                 ean           => 'Y',
201                 publishercode => 'M',
202             }
203         )->store;
204
205         $biblio_2->biblioitem->set(
206             {
207                 isbn          => 'B',
208                 ean           => 'X',
209                 publishercode => 'L',
210             }
211         )->store;
212
213         $result =
214           $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-biblio.isbn,+biblio.ean,-biblio.publisher&basket_id=" . $basket->id => {'x-koha-embed' => 'biblio'} )
215             ->status_is( 200, "query successful" )
216             ->tx->res->json;
217
218         is( $result->[0]->{order_id}, $order_2->id, 'Ordered correctly' );
219         is( $result->[1]->{order_id}, $order_1->id, 'Ordered correctly' );
220
221         $schema->storage->txn_rollback;
222     };
223
224     $schema->storage->txn_rollback;
225 };
226
227 subtest 'get() tests' => sub {
228
229     plan tests => 6;
230
231     $schema->storage->txn_begin;
232
233     my $order = $builder->build_object(
234         {
235             class => 'Koha::Acquisition::Orders',
236             value => { orderstatus => 'new' }
237         }
238     );
239     my $patron = $builder->build_object({
240         class => 'Koha::Patrons',
241         value => { flags => 2048 }
242     });
243     my $password = 'thePassword123';
244     $patron->set_password({ password => $password, skip_validation => 1 });
245     my $userid = $patron->userid;
246
247     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
248       ->status_is( 200, 'SWAGGER3.2.2' )
249       ->json_is( '' => $order->to_api, 'SWAGGER3.3.2' );
250
251     my $non_existent_order_id = $order->ordernumber;
252     $order->delete;
253
254     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $non_existent_order_id )
255       ->status_is(404)
256       ->json_is( '/error' => 'Order not found' );
257
258     # FIXME This does not work on all the OS we support
259     ## Regression tests for bug 25513
260     ## Pick a high value that could be transformed into exponential
261     ## representation and not considered a number by buggy DBD::mysql versions
262     #$order = $builder->build_object(
263     #    {
264     #        class => 'Koha::Acquisition::Orders',
265     #        value => {
266     #            orderstatus => 'new',
267     #            ecost_tax_excluded => 9963405519357589504,
268     #            unitprice => 10177559957753600000
269     #        }
270     #    }
271     #);
272     #
273     #$t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
274     #  ->json_is( '' => $order->to_api, 'Number representation should be consistent' );
275
276     $schema->storage->txn_rollback;
277 };
278
279 subtest 'add() tests' => sub {
280
281     plan tests => 17;
282
283     $schema->storage->txn_begin;
284
285     my $authorized_patron = $builder->build_object({
286         class => 'Koha::Patrons',
287         value => { flags => 1 }
288     });
289     my $password = 'thePassword123';
290     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
291     my $auth_userid = $authorized_patron->userid;
292
293     my $unauthorized_patron = $builder->build_object({
294         class => 'Koha::Patrons',
295         value => { flags => 4 }
296     });
297     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
298     my $unauth_userid = $unauthorized_patron->userid;
299
300     my $order_obj = $builder->build_object(
301         {
302             class => 'Koha::Acquisition::Orders',
303             value => {
304                 orderstatus => 'new',
305                 unitprice   => 10,
306                 replacementprice => 10,
307                 quantity    => 2,
308                 quantityreceived => 0,
309                 datecancellationprinted => undef,
310                 order_internalnote => 'This is a dummy note for testing'
311             }
312         }
313     );
314     my $order = $order_obj->to_api;
315     $order_obj->delete;
316     delete $order->{ordernumber};
317     $order->{uncertain_price} = Mojo::JSON->false;
318
319     # Unauthorized attempt to write
320     $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
321       ->status_is(403);
322
323     # Authorized attempt to write invalid data
324     my $order_with_invalid_field = { %$order };
325     $order_with_invalid_field->{'orderinvalid'} = 'Order invalid';
326
327     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order_with_invalid_field )
328       ->status_is(400)
329       ->json_is(
330         "/errors" => [
331             {
332                 message => "Properties not allowed: orderinvalid.",
333                 path    => "/body"
334             }
335         ]
336     );
337
338     # Authorized attempt to write
339     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
340       ->status_is( 201, 'SWAGGER3.2.1' )
341       ->json_is( '/internal_note' => $order->{internal_note}, 'SWAGGER3.3.1' )
342       ->header_like( Location => qr/\/api\/v1\/acquisitions\/orders\/\d*/, 'SWAGGER3.4.1' );
343
344     # save the order_id
345     my $order_id = $order->{order_id};
346     # Authorized attempt to create with null id
347     $order->{order_id} = undef;
348
349     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
350       ->status_is(400)
351       ->json_has('/errors');
352
353     # Authorized attempt to create with existing id
354     $order->{order_id} = $order_id;
355
356     warning_like {
357         $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
358           ->status_is(409)
359           ->json_has( '/error' => "Fails when trying to add an existing order_id")
360           ->json_like( '/conflict' => qr/(aqorders\.)?PRIMARY/ ); }
361         qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(aqorders\.)?PRIMARY'/;
362
363     $schema->storage->txn_rollback;
364 };
365
366 subtest 'update() tests' => sub {
367     plan tests => 13;
368
369     $schema->storage->txn_begin;
370
371     my $authorized_patron = $builder->build_object({
372         class => 'Koha::Patrons',
373         value => { flags => 1 }
374     });
375     my $password = 'thePassword123';
376     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
377     my $auth_userid = $authorized_patron->userid;
378
379     my $unauthorized_patron = $builder->build_object({
380         class => 'Koha::Patrons',
381         value => { flags => 4 }
382     });
383     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
384     my $unauth_userid = $unauthorized_patron->userid;
385
386     my $library    = $builder->build_object({ class => 'Koha::Libraries' });
387     my $library_id = $library->branchcode;
388
389     # Unauthorized attempt to update
390     $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id"
391                     => json => { name => 'New unauthorized name change' } )
392       ->status_is(403);
393
394     # Attempt partial update on a PUT
395     my $library_with_missing_field = {
396         address1 => "New library address",
397     };
398
399     my $result = $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field )
400       ->status_is(400);
401     # Check the result order first since it's not predefined.
402     if ($result->tx->res->json->{errors}->[0]->{path} eq '/body/name') {
403       $result->json_is(
404         "/errors",
405         [
406           {message => "Missing property.", path => "/body/name"},
407           {message => "Missing property.", path => "/body/library_id"}
408         ]
409       );
410     } else {
411       $result->json_is(
412         "/errors",
413         [
414           {message => "Missing property.", path => "/body/library_id"},
415           {message => "Missing property.", path => "/body/name"}
416         ]
417       );
418     }
419
420     my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } );
421     my $library_with_updated_field = $deleted_library->to_api;
422     $library_with_updated_field->{library_id} = $library_id;
423     $deleted_library->delete;
424
425     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field )
426       ->status_is(200, 'SWAGGER3.2.1')
427       ->json_is( '' => $library_with_updated_field, 'SWAGGER3.3.3' );
428
429     # Authorized attempt to write invalid data
430     my $library_with_invalid_field = { %$library_with_updated_field };
431     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
432
433     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field )
434       ->status_is(400)
435       ->json_is(
436         "/errors" => [
437             {
438                 message => "Properties not allowed: branchinvalid.",
439                 path    => "/body"
440             }
441         ]
442     );
443
444     my $non_existent_code = 'nope'.int(rand(10000));
445     $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field)
446       ->status_is(404);
447
448     $schema->storage->txn_rollback;
449 };
450
451 subtest 'delete() tests' => sub {
452     plan tests => 7;
453
454     $schema->storage->txn_begin;
455
456     my $authorized_patron = $builder->build_object({
457         class => 'Koha::Patrons',
458         value => { flags => 1 }
459     });
460     my $password = 'thePassword123';
461     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
462     my $auth_userid = $authorized_patron->userid;
463
464     my $unauthorized_patron = $builder->build_object({
465         class => 'Koha::Patrons',
466         value => { flags => 4 }
467     });
468     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
469     my $unauth_userid = $unauthorized_patron->userid;
470
471     my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } );
472
473     # Unauthorized attempt to delete
474     $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
475       ->status_is(403);
476
477     $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
478       ->status_is(204, 'SWAGGER3.2.4')
479       ->content_is('', 'SWAGGER3.3.4');
480
481     $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
482       ->status_is(404);
483
484     $schema->storage->txn_rollback;
485 };