Bug 31797: Add DELETE /items/:item_id endpoint
[koha.git] / t / db_dependent / api / v1 / items.t
1 #!/usr/bin/env perl
2
3 # Copyright 2016 Koha-Suomi
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 4;
23 use Test::MockModule;
24 use Test::Mojo;
25 use Test::Warn;
26
27 use t::lib::TestBuilder;
28 use t::lib::Mocks;
29
30 use C4::Auth;
31 use Koha::Items;
32 use Koha::Database;
33
34 my $schema  = Koha::Database->new->schema;
35 my $builder = t::lib::TestBuilder->new;
36
37 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
38
39 my $t = Test::Mojo->new('Koha::REST::V1');
40
41 subtest 'list() tests' => sub {
42
43     plan tests => 12;
44
45     $schema->storage->txn_begin;
46
47     my $item   = $builder->build_sample_item;
48     my $patron = $builder->build_object(
49         {
50             class => 'Koha::Patrons',
51             value => { flags => 4 }
52         }
53     );
54
55     # Make sure we have at least 10 items
56     for ( 1..10 ) {
57         $builder->build_sample_item;
58     }
59
60     my $nonprivilegedpatron = $builder->build_object(
61         {
62             class => 'Koha::Patrons',
63             value => { flags => 0 }
64         }
65     );
66
67     my $password = 'thePassword123';
68
69     $nonprivilegedpatron->set_password(
70         { password => $password, skip_validation => 1 } );
71     my $userid = $nonprivilegedpatron->userid;
72
73     $t->get_ok( "//$userid:$password@/api/v1/items" )
74       ->status_is(403)
75       ->json_is(
76         '/error' => 'Authorization failure. Missing required permission(s).' );
77
78     $patron->set_password( { password => $password, skip_validation => 1 } );
79     $userid = $patron->userid;
80
81     $t->get_ok( "//$userid:$password@/api/v1/items?_per_page=10" )
82       ->status_is( 200, 'SWAGGER3.2.2' );
83
84     my $response_count = scalar @{ $t->tx->res->json };
85
86     is( $response_count, 10, 'The API returns 10 items' );
87
88     $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )
89       ->status_is(200)
90       ->json_is( '' => [ $item->to_api ], 'SWAGGER3.3.2');
91
92     my $barcode = $item->barcode;
93     $item->delete;
94
95     $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )
96       ->status_is(200)
97       ->json_is( '' => [] );
98
99     $schema->storage->txn_rollback;
100 };
101
102
103 subtest 'get() tests' => sub {
104
105     plan tests => 30;
106
107     $schema->storage->txn_begin;
108
109     my $item = $builder->build_sample_item;
110     my $patron = $builder->build_object({
111         class => 'Koha::Patrons',
112         value => { flags => 4 }
113     });
114
115     my $nonprivilegedpatron = $builder->build_object({
116         class => 'Koha::Patrons',
117         value => { flags => 0 }
118     });
119
120     my $password = 'thePassword123';
121
122     $nonprivilegedpatron->set_password({ password => $password, skip_validation => 1 });
123     my $userid = $nonprivilegedpatron->userid;
124
125     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
126       ->status_is(403)
127       ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' );
128
129     $patron->set_password({ password => $password, skip_validation => 1 });
130     $userid = $patron->userid;
131
132     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
133       ->status_is( 200, 'SWAGGER3.2.2' )
134       ->json_is( '' => $item->to_api, 'SWAGGER3.3.2' );
135
136     my $non_existent_code = $item->itemnumber;
137     $item->delete;
138
139     $t->get_ok( "//$userid:$password@/api/v1/items/" . $non_existent_code )
140       ->status_is(404)
141       ->json_is( '/error' => 'Item not found' );
142
143     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
144
145     my $biblio = $builder->build_sample_biblio;
146     my $itype =
147       $builder->build_object( { class => 'Koha::ItemTypes' } );
148     $item = $builder->build_sample_item(
149         { biblionumber => $biblio->biblionumber, itype => $itype->itemtype } );
150
151     isnt( $biblio->itemtype, $itype->itemtype, "Test biblio level itemtype and item level itemtype do not match");
152
153     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
154       ->status_is( 200, 'SWAGGER3.2.2' )
155       ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itypes:0' )
156       ->json_is( '/effective_item_type_id' => $biblio->itemtype, 'item-level_itypes:0' );
157
158     t::lib::Mocks::mock_preference( 'item-level_itypes', 1 );
159
160     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
161       ->status_is( 200, 'SWAGGER3.2.2' )
162       ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itype:1' )
163       ->json_is( '/effective_item_type_id' => $itype->itemtype, 'item-level_itypes:1' );
164
165
166     my $biblio_itype = Koha::ItemTypes->find($biblio->itemtype);
167     $biblio_itype->notforloan(3)->store();
168     $itype->notforloan(2)->store();
169     $item->notforloan(1)->store();
170
171     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
172       ->status_is( 200, 'SWAGGER3.2.2' )
173       ->json_is( '/not_for_loan_status' => 1, 'not_for_loan_status is 1' )
174       ->json_is( '/effective_not_for_loan_status' => 1, 'effective_not_for_loan_status picks up item level' );
175
176     $item->notforloan(0)->store();
177     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
178       ->status_is( 200, 'SWAGGER3.2.2' )
179       ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )
180       ->json_is( '/effective_not_for_loan_status' => 2, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:1' );
181
182     t::lib::Mocks::mock_preference( 'item-level_itypes', 0 );
183     $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )
184       ->status_is( 200, 'SWAGGER3.2.2' )
185       ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )
186       ->json_is( '/effective_not_for_loan_status' => 3, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:0' );
187
188     $schema->storage->txn_rollback;
189 };
190
191 subtest 'delete() tests' => sub {
192
193     plan tests => 23;
194
195     $schema->storage->txn_begin;
196
197     my $fail = 0;
198     my $expected_error;
199
200     # we want to control all the safe_to_delete use cases
201     my $item_class = Test::MockModule->new('Koha::Item');
202     $item_class->mock( 'safe_to_delete', sub {
203         if ( $fail ) {
204             return Koha::Result::Boolean->new(0)->add_message({ message => $expected_error });
205         }
206         else {
207             return Koha::Result::Boolean->new(1);
208         }
209     });
210
211     my $librarian = $builder->build_object(
212         {
213             class => 'Koha::Patrons',
214             value => { flags => 2**9 }    # catalogue flag = 2
215         }
216     );
217     my $password = 'thePassword123';
218     $librarian->set_password( { password => $password, skip_validation => 1 } );
219     my $userid = $librarian->userid;
220
221     my $item = $builder->build_sample_item;
222
223     my $errors = {
224         book_on_loan       => { code => 'checked_out',        description => 'The item is checked out' },
225         book_reserved      => { code => 'found_hold',         description => 'Waiting or in-transit hold for the item' },
226         last_item_for_hold => { code => 'last_item_for_hold', description => 'The item is the last one on a record on which a biblio-level hold is placed' },
227         linked_analytics   => { code => 'linked_analytics',   description => 'The item has linked analytic records' },
228         not_same_branch    => { code => 'not_same_branch',    description => 'The item is blocked by independent branches' },
229     };
230
231     $fail = 1;
232
233     foreach my $error_code ( keys %{$errors} ) {
234
235         $expected_error = $error_code;
236
237         $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )
238           ->status_is(409)
239           ->json_is(
240             { error      => $errors->{$error_code}->{description},
241               error_code => $errors->{$error_code}->{code},
242             }
243         );
244     }
245
246     $expected_error = 'unknown_error';
247     $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )
248       ->status_is(500, 'unhandled error case generated default unhandled exception message')
249       ->json_is(
250         { error      => 'Something went wrong, check Koha logs for details.',
251           error_code => 'internal_server_error',
252         }
253     );
254
255     $fail = 0;
256
257     $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id)
258       ->status_is(204, 'SWAGGER3.2.4')
259       ->content_is('', 'SWAGGER3.3.4');
260
261     $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id)
262       ->status_is(404);
263
264     $schema->storage->txn_rollback;
265 };
266
267 subtest 'pickup_locations() tests' => sub {
268
269     plan tests => 16;
270
271     $schema->storage->txn_begin;
272
273     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
274
275     # Small trick to ease testing
276     Koha::Libraries->search->update({ pickup_location => 0 });
277
278     my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } });
279     my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } });
280     my $library_3 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } });
281
282     my $library_1_api = $library_1->to_api();
283     my $library_2_api = $library_2->to_api();
284     my $library_3_api = $library_3->to_api();
285
286     $library_1_api->{needs_override} = Mojo::JSON->false;
287     $library_2_api->{needs_override} = Mojo::JSON->false;
288     $library_3_api->{needs_override} = Mojo::JSON->true;
289
290     my $patron = $builder->build_object(
291         {
292             class => 'Koha::Patrons',
293             value => { userid => 'tomasito', flags => 0 }
294         }
295     );
296     my $password = 'thePassword123';
297     $patron->set_password( { password => $password, skip_validation => 1 } );
298     my $userid = $patron->userid;
299     $builder->build(
300         {
301             source => 'UserPermission',
302             value  => {
303                 borrowernumber => $patron->borrowernumber,
304                 module_bit     => 6,
305                 code           => 'place_holds',
306             },
307         }
308     );
309
310     my $item = $builder->build_sample_item();
311
312     my $item_class = Test::MockModule->new('Koha::Item');
313     $item_class->mock(
314         'pickup_locations',
315         sub {
316             my ( $self, $params ) = @_;
317             my $mock_patron = $params->{patron};
318             is( $mock_patron->borrowernumber,
319                 $patron->borrowernumber, 'Patron passed correctly' );
320             return Koha::Libraries->search(
321                 {
322                     branchcode => {
323                         '-in' => [
324                             $library_1->branchcode,
325                             $library_2->branchcode
326                         ]
327                     }
328                 },
329                 {   # we make sure no surprises in the order of the result
330                     order_by => { '-asc' => 'marcorgcode' }
331                 }
332             );
333         }
334     );
335
336     $t->get_ok( "//$userid:$password@/api/v1/items/"
337           . $item->id
338           . "/pickup_locations?patron_id=" . $patron->id )
339       ->json_is( [ $library_1_api, $library_2_api ] );
340
341     # filtering works!
342     $t->get_ok( "//$userid:$password@/api/v1/items/"
343           . $item->id
344           . '/pickup_locations?'
345           . 'patron_id=' . $patron->id . '&q={"marc_org_code": { "-like": "A%" }}' )
346       ->json_is( [ $library_1_api ] );
347
348     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
349
350     my $library_4 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } });
351     my $library_5 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } });
352
353     my $library_5_api = $library_5->to_api();
354     $library_5_api->{needs_override} = Mojo::JSON->true;
355
356     $t->get_ok( "//$userid:$password@/api/v1/items/"
357           . $item->id
358           . "/pickup_locations?"
359           . "patron_id=" . $patron->id . "&_order_by=marc_org_code" )
360       ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] );
361
362     subtest 'Pagination and AllowHoldPolicyOverride tests' => sub {
363
364         plan tests => 27;
365
366         t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
367
368         $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" )
369           ->json_is( [$library_1_api] )
370           ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
371           ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
372           ->header_unlike( 'Link', qr|rel="prev"| )
373           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# )
374           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
375           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# );
376
377         $t->get_ok( "//$userid:$password@/api/v1/items/"
378               . $item->id
379               . "/pickup_locations?"
380               . "patron_id="
381               . $patron->id
382               . "&_order_by=marc_org_code"
383               . "&_per_page=1&_page=3" )    # force the needs_override=1 check
384           ->json_is( [$library_3_api] )
385           ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
386           ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' )
387           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# )
388           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# )
389           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
390           ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# );
391
392         t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
393
394         $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" )
395           ->json_is( [$library_1_api] )
396           ->header_is( 'X-Total-Count', '2' )
397           ->header_is( 'X-Base-Total-Count', '2' )
398           ->header_unlike( 'Link', qr|rel="prev"| )
399           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# )
400           ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# )
401           ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# );
402     };
403
404     my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' });
405     my $deleted_patron_id = $deleted_patron->id;
406     $deleted_patron->delete;
407
408     $t->get_ok( "//$userid:$password@/api/v1/items/"
409           . $item->id
410           . "/pickup_locations?"
411           . "patron_id=" . $deleted_patron_id )
412       ->status_is( 400 )
413       ->json_is( '/error' => 'Patron not found' );
414
415     $item->delete;
416
417     $t->get_ok( "//$userid:$password@/api/v1/items/"
418           . $item->id
419           . "/pickup_locations?"
420           . "patron_id=" . $patron->id )
421       ->status_is( 404 )
422       ->json_is( '/error' => 'Item not found' );
423
424     $schema->storage->txn_rollback;
425 };