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