Bug 28585: (follow-up) Tests for q= supporting date/date-time parameters
[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     plan tests => 18;
41
42     $schema->storage->txn_begin;
43
44     my $patron = $builder->build_object({
45         class => 'Koha::Patrons',
46         value => { flags => 1 }
47     });
48     my $password = 'thePassword123';
49     $patron->set_password({ password => $password, skip_validation => 1 });
50     my $userid = $patron->userid;
51
52     my $basket = $builder->build_object({ class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } });
53
54     my $biblio = $builder->build_sample_biblio;
55     my $biblioitem = $biblio->biblioitem;
56     $biblioitem->set({ isbn => 'SOMETHING' })->store;
57
58     # Create test context
59     my $order = $builder->build_object(
60         {
61             class => 'Koha::Acquisition::Orders',
62             value => {
63                 basketno     => $basket->basketno,
64                 orderstatus  => 'new',
65                 biblionumber => $biblio->biblionumber
66             }
67         }
68     );
69     my $another_order = $order->unblessed; # create a copy of $order but make
70     delete $another_order->{ordernumber};  # sure ordernumber will be regenerated
71     $another_order = $builder->build_object({ class => 'Koha::Acquisition::Orders', value => $another_order });
72
73     ## Authorized user tests
74     my $count_of_orders = Koha::Acquisition::Orders->search->count;
75     # Make sure we are returned with the correct amount of orders
76     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_per_page=-1" )
77       ->status_is( 200, 'SWAGGER3.2.2' )
78       ->json_has('/'.($count_of_orders-1).'/order_id')
79       ->json_hasnt('/'.($count_of_orders).'/order_id');
80
81     subtest 'query parameters' => sub {
82
83         my $fields = {
84             biblio_id => 'biblionumber',
85             basket_id => 'basketno',
86             fund_id   => 'budget_id',
87         };
88
89         my $size = keys %{$fields};
90
91         plan tests => $size * (2 + 2 * $size);
92
93         foreach my $field ( keys %{$fields} ) {
94             my $model_field = $fields->{ $field };
95             my $result = $t->get_ok("//$userid:$password@/api/v1/acquisitions/orders?$field=" . $order->$model_field)
96               ->status_is(200);
97
98             foreach my $key ( keys %{$fields} ) {
99               my $key_field = $fields->{ $key };
100               # Check the result order first since it's not predefined.
101               if ($result->tx->res->json->[0]->{$key} eq $order->$key_field) {
102                 $result->json_is( "/0/$key", $order->$key_field );
103                 $result->json_is( "/1/$key", $another_order->$key_field );
104               } else {
105                 $result->json_is( "/0/$key", $another_order->$key_field );
106                 $result->json_is( "/1/$key", $order->$key_field );
107               }
108             }
109         }
110     };
111
112     my $query = { "biblio.isbn" => { "-like" => "\%SOMETHING\%" } };
113
114     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => {'x-koha-embed' => 'biblio'} )
115       ->status_is( 200, "Embeddig 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     my $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?biblio_id=" . $biblio->biblionumber )
120       ->status_is( 200 );
121
122     is( scalar @{ $result->tx->res->json}, 2, 'Two orders fetched' );
123
124     # Mark $another_order as cancelled
125     $another_order->set({ orderstatus => 'cancelled' })->store;
126
127     $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?only_active=1&biblio_id=" . $biblio->biblionumber )
128       ->status_is( 200, "only_active parameter accepted" );
129
130     is( scalar @{ $result->tx->res->json}, 1, 'Only one order is active' );
131
132     # Warn on unsupported query parameter
133     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?order_blah=blah" )
134       ->status_is(400)
135       ->json_is( [{ path => '/query/order_blah', message => 'Malformed query string'}] );
136
137     $schema->storage->txn_rollback;
138 };
139
140 subtest 'get() tests' => sub {
141
142     plan tests => 6;
143
144     $schema->storage->txn_begin;
145
146     my $order = $builder->build_object(
147         {
148             class => 'Koha::Acquisition::Orders',
149             value => { orderstatus => 'new' }
150         }
151     );
152     my $patron = $builder->build_object({
153         class => 'Koha::Patrons',
154         value => { flags => 2048 }
155     });
156     my $password = 'thePassword123';
157     $patron->set_password({ password => $password, skip_validation => 1 });
158     my $userid = $patron->userid;
159
160     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
161       ->status_is( 200, 'SWAGGER3.2.2' )
162       ->json_is( '' => $order->to_api, 'SWAGGER3.3.2' );
163
164     my $non_existent_order_id = $order->ordernumber;
165     $order->delete;
166
167     $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $non_existent_order_id )
168       ->status_is(404)
169       ->json_is( '/error' => 'Order not found' );
170
171     # FIXME This does not work on all the OS we support
172     ## Regression tests for bug 25513
173     ## Pick a high value that could be transformed into exponential
174     ## representation and not considered a number by buggy DBD::mysql versions
175     #$order = $builder->build_object(
176     #    {
177     #        class => 'Koha::Acquisition::Orders',
178     #        value => {
179     #            orderstatus => 'new',
180     #            ecost_tax_excluded => 9963405519357589504,
181     #            unitprice => 10177559957753600000
182     #        }
183     #    }
184     #);
185     #
186     #$t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
187     #  ->json_is( '' => $order->to_api, 'Number representation should be consistent' );
188
189     $schema->storage->txn_rollback;
190 };
191
192 subtest 'add() tests' => sub {
193
194     plan tests => 17;
195
196     $schema->storage->txn_begin;
197
198     my $authorized_patron = $builder->build_object({
199         class => 'Koha::Patrons',
200         value => { flags => 1 }
201     });
202     my $password = 'thePassword123';
203     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
204     my $auth_userid = $authorized_patron->userid;
205
206     my $unauthorized_patron = $builder->build_object({
207         class => 'Koha::Patrons',
208         value => { flags => 4 }
209     });
210     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
211     my $unauth_userid = $unauthorized_patron->userid;
212
213     my $order_obj = $builder->build_object(
214         {
215             class => 'Koha::Acquisition::Orders',
216             value => {
217                 orderstatus => 'new',
218                 unitprice   => 10,
219                 replacementprice => 10,
220                 quantity    => 2,
221                 quantityreceived => 0,
222                 datecancellationprinted => undef,
223                 order_internalnote => 'This is a dummy note for testing'
224             }
225         }
226     );
227     my $order = $order_obj->to_api;
228     $order_obj->delete;
229     delete $order->{ordernumber};
230     $order->{uncertain_price} = Mojo::JSON->false;
231
232     # Unauthorized attempt to write
233     $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
234       ->status_is(403);
235
236     # Authorized attempt to write invalid data
237     my $order_with_invalid_field = { %$order };
238     $order_with_invalid_field->{'orderinvalid'} = 'Order invalid';
239
240     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order_with_invalid_field )
241       ->status_is(400)
242       ->json_is(
243         "/errors" => [
244             {
245                 message => "Properties not allowed: orderinvalid.",
246                 path    => "/body"
247             }
248         ]
249     );
250
251     # Authorized attempt to write
252     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
253       ->status_is( 201, 'SWAGGER3.2.1' )
254       ->json_is( '/internal_note' => $order->{internal_note}, 'SWAGGER3.3.1' )
255       ->header_like( Location => qr/\/api\/v1\/acquisitions\/orders\/\d*/, 'SWAGGER3.4.1' );
256
257     # save the order_id
258     my $order_id = $order->{order_id};
259     # Authorized attempt to create with null id
260     $order->{order_id} = undef;
261
262     $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
263       ->status_is(400)
264       ->json_has('/errors');
265
266     # Authorized attempt to create with existing id
267     $order->{order_id} = $order_id;
268
269     warning_like {
270         $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )
271           ->status_is(409)
272           ->json_has( '/error' => "Fails when trying to add an existing order_id")
273           ->json_like( '/conflict' => qr/(aqorders\.)?PRIMARY/ ); }
274         qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(aqorders\.)?PRIMARY'/;
275
276     $schema->storage->txn_rollback;
277 };
278
279 subtest 'update() tests' => sub {
280     plan tests => 13;
281
282     $schema->storage->txn_begin;
283
284     my $authorized_patron = $builder->build_object({
285         class => 'Koha::Patrons',
286         value => { flags => 1 }
287     });
288     my $password = 'thePassword123';
289     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
290     my $auth_userid = $authorized_patron->userid;
291
292     my $unauthorized_patron = $builder->build_object({
293         class => 'Koha::Patrons',
294         value => { flags => 4 }
295     });
296     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
297     my $unauth_userid = $unauthorized_patron->userid;
298
299     my $library    = $builder->build_object({ class => 'Koha::Libraries' });
300     my $library_id = $library->branchcode;
301
302     # Unauthorized attempt to update
303     $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id"
304                     => json => { name => 'New unauthorized name change' } )
305       ->status_is(403);
306
307     # Attempt partial update on a PUT
308     my $library_with_missing_field = {
309         address1 => "New library address",
310     };
311
312     my $result = $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field )
313       ->status_is(400);
314     # Check the result order first since it's not predefined.
315     if ($result->tx->res->json->{errors}->[0]->{path} eq '/body/name') {
316       $result->json_is(
317         "/errors",
318         [
319           {message => "Missing property.", path => "/body/name"},
320           {message => "Missing property.", path => "/body/library_id"}
321         ]
322       );
323     } else {
324       $result->json_is(
325         "/errors",
326         [
327           {message => "Missing property.", path => "/body/library_id"},
328           {message => "Missing property.", path => "/body/name"}
329         ]
330       );
331     }
332
333     my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } );
334     my $library_with_updated_field = $deleted_library->to_api;
335     $library_with_updated_field->{library_id} = $library_id;
336     $deleted_library->delete;
337
338     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field )
339       ->status_is(200, 'SWAGGER3.2.1')
340       ->json_is( '' => $library_with_updated_field, 'SWAGGER3.3.3' );
341
342     # Authorized attempt to write invalid data
343     my $library_with_invalid_field = { %$library_with_updated_field };
344     $library_with_invalid_field->{'branchinvalid'} = 'Library invalid';
345
346     $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field )
347       ->status_is(400)
348       ->json_is(
349         "/errors" => [
350             {
351                 message => "Properties not allowed: branchinvalid.",
352                 path    => "/body"
353             }
354         ]
355     );
356
357     my $non_existent_code = 'nope'.int(rand(10000));
358     $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field)
359       ->status_is(404);
360
361     $schema->storage->txn_rollback;
362 };
363
364 subtest 'delete() tests' => sub {
365     plan tests => 7;
366
367     $schema->storage->txn_begin;
368
369     my $authorized_patron = $builder->build_object({
370         class => 'Koha::Patrons',
371         value => { flags => 1 }
372     });
373     my $password = 'thePassword123';
374     $authorized_patron->set_password({ password => $password, skip_validation => 1 });
375     my $auth_userid = $authorized_patron->userid;
376
377     my $unauthorized_patron = $builder->build_object({
378         class => 'Koha::Patrons',
379         value => { flags => 4 }
380     });
381     $unauthorized_patron->set_password({ password => $password, skip_validation => 1 });
382     my $unauth_userid = $unauthorized_patron->userid;
383
384     my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } );
385
386     # Unauthorized attempt to delete
387     $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
388       ->status_is(403);
389
390     $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
391       ->status_is(204, 'SWAGGER3.2.4')
392       ->content_is('', 'SWAGGER3.3.4');
393
394     $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )
395       ->status_is(404);
396
397     $schema->storage->txn_rollback;
398 };