Bug 22522: Fix several REST API tests
[koha.git] / t / db_dependent / api / v1 / holds.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 => 8;
21 use Test::Mojo;
22 use t::lib::TestBuilder;
23 use t::lib::Mocks;
24
25 use DateTime;
26
27 use C4::Context;
28 use Koha::Patrons;
29 use C4::Reserves;
30 use C4::Items;
31
32 use Koha::Database;
33 use Koha::DateUtils;
34 use Koha::Biblios;
35 use Koha::Biblioitems;
36 use Koha::Items;
37 use Koha::CirculationRules;
38
39 my $schema  = Koha::Database->new->schema;
40 my $builder = t::lib::TestBuilder->new();
41
42 $schema->storage->txn_begin;
43
44 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
45
46 my $t = Test::Mojo->new('Koha::REST::V1');
47
48 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
49 my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
50 my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype};
51
52 # Generic password for everyone
53 my $password = 'thePassword123';
54
55 # User without any permissions
56 my $nopermission = $builder->build_object({
57     class => 'Koha::Patrons',
58     value => {
59         branchcode   => $branchcode,
60         categorycode => $categorycode,
61         flags        => 0
62     }
63 });
64 $nopermission->set_password( { password => $password, skip_validation => 1 } );
65 my $nopermission_userid = $nopermission->userid;
66
67 my $patron_1 = $builder->build_object(
68     {
69         class => 'Koha::Patrons',
70         value => {
71             categorycode => $categorycode,
72             branchcode   => $branchcode,
73             surname      => 'Test Surname',
74             flags        => 80, #borrowers and reserveforothers flags
75         }
76     }
77 );
78 $patron_1->set_password( { password => $password, skip_validation => 1 } );
79 my $userid_1 = $patron_1->userid;
80
81 my $patron_2 = $builder->build_object(
82     {
83         class => 'Koha::Patrons',
84         value => {
85             categorycode => $categorycode,
86             branchcode   => $branchcode,
87             surname      => 'Test Surname 2',
88             flags        => 16, # borrowers flag
89         }
90     }
91 );
92 $patron_2->set_password( { password => $password, skip_validation => 1 } );
93 my $userid_2 = $patron_2->userid;
94
95 my $patron_3 = $builder->build_object(
96     {
97         class => 'Koha::Patrons',
98         value => {
99             categorycode => $categorycode,
100             branchcode   => $branchcode,
101             surname      => 'Test Surname 3',
102             flags        => 64, # reserveforothers flag
103         }
104     }
105 );
106 $patron_3->set_password( { password => $password, skip_validation => 1 } );
107 my $userid_3 = $patron_3->userid;
108
109 my $biblio_1 = $builder->build_sample_biblio;
110 my $item_1   = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber, itype => $itemtype });
111
112 my $biblio_2 = $builder->build_sample_biblio;
113 my $item_2   = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber, itype => $itemtype });
114
115 my $dbh = C4::Context->dbh;
116 $dbh->do('DELETE FROM reserves');
117 Koha::CirculationRules->search()->delete();
118 Koha::CirculationRules->set_rules(
119     {
120         categorycode => undef,
121         branchcode   => undef,
122         itemtype     => undef,
123         rules        => {
124             reservesallowed => 1,
125             holds_per_record => 99
126         }
127     }
128 );
129
130 my $reserve_id = C4::Reserves::AddReserve(
131     {
132         branchcode     => $branchcode,
133         borrowernumber => $patron_1->borrowernumber,
134         biblionumber   => $biblio_1->biblionumber,
135         priority       => 1,
136         itemnumber     => $item_1->itemnumber,
137     }
138 );
139
140 # Add another reserve to be able to change first reserve's rank
141 my $reserve_id2 = C4::Reserves::AddReserve(
142     {
143         branchcode     => $branchcode,
144         borrowernumber => $patron_2->borrowernumber,
145         biblionumber   => $biblio_1->biblionumber,
146         priority       => 2,
147         itemnumber     => $item_1->itemnumber,
148     }
149 );
150
151 my $suspended_until = DateTime->now->add(days => 10)->truncate( to => 'day' );
152 my $expiration_date = DateTime->now->add(days => 10)->truncate( to => 'day' );
153
154 my $post_data = {
155     patron_id => int($patron_1->borrowernumber),
156     biblio_id => int($biblio_1->biblionumber),
157     item_id => int($item_1->itemnumber),
158     pickup_library_id => $branchcode,
159     expiration_date => output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }),
160     priority => 2,
161 };
162 my $put_data = {
163     priority => 2,
164     suspended_until => output_pref({ dt => $suspended_until, dateformat => 'rfc3339' }),
165 };
166
167 subtest "Test endpoints without authentication" => sub {
168     plan tests => 8;
169     $t->get_ok('/api/v1/holds')
170       ->status_is(401);
171     $t->post_ok('/api/v1/holds')
172       ->status_is(401);
173     $t->put_ok('/api/v1/holds/0')
174       ->status_is(401);
175     $t->delete_ok('/api/v1/holds/0')
176       ->status_is(401);
177 };
178
179 subtest "Test endpoints without permission" => sub {
180
181     plan tests => 10;
182
183     $t->get_ok( "//$nopermission_userid:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission
184       ->status_is(403);
185
186     $t->get_ok( "//$userid_3:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )    # no permission
187       ->status_is(403);
188
189     $t->post_ok( "//$nopermission_userid:$password@/api/v1/holds" => json => $post_data )
190       ->status_is(403);
191
192     $t->put_ok( "//$nopermission_userid:$password@/api/v1/holds/0" => json => $put_data )
193       ->status_is(403);
194
195     $t->delete_ok( "//$nopermission_userid:$password@/api/v1/holds/0" )
196       ->status_is(403);
197 };
198
199 subtest "Test endpoints with permission" => sub {
200
201     plan tests => 44;
202
203     $t->get_ok( "//$userid_1:$password@/api/v1/holds" )
204       ->status_is(200)
205       ->json_has('/0')
206       ->json_has('/1')
207       ->json_hasnt('/2');
208
209     $t->get_ok( "//$userid_1:$password@/api/v1/holds?priority=2" )
210       ->status_is(200)
211       ->json_is('/0/patron_id', $patron_2->borrowernumber)
212       ->json_hasnt('/1');
213
214     # While suspended_until is date-time, it's always set to midnight.
215     my $expected_suspended_until = $suspended_until->strftime('%FT00:00:00%z');
216     substr($expected_suspended_until, -2, 0, ':');
217
218     $t->put_ok( "//$userid_1:$password@/api/v1/holds/$reserve_id" => json => $put_data )
219       ->status_is(200)
220       ->json_is( '/hold_id', $reserve_id )
221       ->json_is( '/suspended_until', $expected_suspended_until )
222       ->json_is( '/priority', 2 );
223
224     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
225       ->status_is(200);
226
227     $t->put_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" => json => $put_data )
228       ->status_is(404)
229       ->json_has('/error');
230
231     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
232       ->status_is(404)
233       ->json_has('/error');
234
235     $t->get_ok( "//$userid_2:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
236       ->status_is(200)
237       ->json_is([]);
238
239     my $inexisting_borrowernumber = $patron_2->borrowernumber * 2;
240     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=$inexisting_borrowernumber")
241       ->status_is(200)
242       ->json_is([]);
243
244     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id2" )
245       ->status_is(200);
246
247     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
248       ->status_is(201)
249       ->json_has('/hold_id');
250     # Get id from response
251     $reserve_id = $t->tx->res->json->{hold_id};
252
253     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
254       ->status_is(200)
255       ->json_is('/0/hold_id', $reserve_id)
256       ->json_is('/0/expiration_date', output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }))
257       ->json_is('/0/pickup_library_id', $branchcode);
258
259     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
260       ->status_is(403)
261       ->json_like('/error', qr/itemAlreadyOnHold/);
262
263     $post_data->{biblionumber} = int($biblio_2->biblionumber);
264     $post_data->{itemnumber}   = int($item_2->itemnumber);
265
266     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
267       ->status_is(403)
268       ->json_like('/error', qr/itemAlreadyOnHold/);
269 };
270
271 subtest 'Reserves with itemtype' => sub {
272     plan tests => 9;
273
274     my $post_data = {
275         patron_id => int($patron_1->borrowernumber),
276         biblio_id => int($biblio_1->biblionumber),
277         pickup_library_id => $branchcode,
278         item_type => $itemtype,
279     };
280
281     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
282       ->status_is(200);
283
284     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
285       ->status_is(201)
286       ->json_has('/hold_id');
287
288     $reserve_id = $t->tx->res->json->{hold_id};
289
290     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
291       ->status_is(200)
292       ->json_is('/0/hold_id', $reserve_id)
293       ->json_is('/0/item_type', $itemtype);
294 };
295
296
297 subtest 'test AllowHoldDateInFuture' => sub {
298
299     plan tests => 6;
300
301     $dbh->do('DELETE FROM reserves');
302
303     my $future_hold_date = DateTime->now->add(days => 10)->truncate( to => 'day' );
304
305     my $post_data = {
306         patron_id => int($patron_1->borrowernumber),
307         biblio_id => int($biblio_1->biblionumber),
308         item_id => int($item_1->itemnumber),
309         pickup_library_id => $branchcode,
310         expiration_date => output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }),
311         hold_date => output_pref({ dt => $future_hold_date, dateformat => 'rfc3339', dateonly => 1 }),
312         priority => 2,
313     };
314
315     t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 0 );
316
317     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
318       ->status_is(400)
319       ->json_has('/error');
320
321     t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 );
322
323     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
324       ->status_is(201)
325       ->json_is('/hold_date', output_pref({ dt => $future_hold_date, dateformat => 'rfc3339', dateonly => 1 }));
326 };
327
328 subtest 'test AllowHoldPolicyOverride' => sub {
329
330     plan tests => 5;
331
332     $dbh->do('DELETE FROM reserves');
333
334     Koha::CirculationRules->set_rules(
335         {
336             itemtype     => undef,
337             branchcode   => undef,
338             rules        => {
339                 holdallowed              => 1
340             }
341         }
342     );
343
344     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
345
346     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
347       ->status_is(403)
348       ->json_has('/error');
349
350     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
351
352     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
353       ->status_is(201);
354 };
355
356 $schema->storage->txn_rollback;
357
358 subtest 'suspend and resume tests' => sub {
359
360     plan tests => 21;
361
362     $schema->storage->txn_begin;
363
364     my $password = 'AbcdEFG123';
365
366     my $patron = $builder->build_object(
367         { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 1 } } );
368     $patron->set_password({ password => $password, skip_validation => 1 });
369     my $userid = $patron->userid;
370
371     # Disable logging
372     t::lib::Mocks::mock_preference( 'HoldsLog',      0 );
373     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
374
375     my $hold = $builder->build_object(
376         {   class => 'Koha::Holds',
377             value => { suspend => 0, suspend_until => undef, waitingdate => undef }
378         }
379     );
380
381     ok( !$hold->is_suspended, 'Hold is not suspended' );
382     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
383         ->status_is( 201, 'Hold suspension created' );
384
385     $hold->discard_changes;    # refresh object
386
387     ok( $hold->is_suspended, 'Hold is suspended' );
388     $t->json_is(
389         '/end_date',
390         output_pref(
391             {   dt         => dt_from_string( $hold->suspend_until ),
392                 dateformat => 'rfc3339',
393                 dateonly   => 1
394             }
395         )
396     );
397
398     $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
399       ->status_is( 204, "Correct status when deleting a resource" )
400       ->json_is( undef );
401
402     # Pass a an expiration date for the suspension
403     my $date = dt_from_string()->add( days => 5 );
404     $t->post_ok(
405               "//$userid:$password@/api/v1/holds/"
406             . $hold->id
407             . "/suspension" => json => {
408             end_date =>
409                 output_pref( { dt => $date, dateformat => 'rfc3339', dateonly => 1 } )
410             }
411     )->status_is( 201, 'Hold suspension created' )
412         ->json_is( '/end_date',
413         output_pref( { dt => $date, dateformat => 'rfc3339', dateonly => 1 } ) )
414         ->header_is( Location => "/api/v1/holds/" . $hold->id . "/suspension", 'The Location header is set' );
415
416     $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
417       ->status_is( 204, "Correct status when deleting a resource" )
418       ->json_is( undef );
419
420     $hold->set_waiting->discard_changes;
421
422     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
423       ->status_is( 400, 'Cannot suspend waiting hold' )
424       ->json_is( '/error', 'Found hold cannot be suspended. Status=W' );
425
426     $hold->set_waiting(1)->discard_changes;
427
428     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
429       ->status_is( 400, 'Cannot suspend waiting hold' )
430       ->json_is( '/error', 'Found hold cannot be suspended. Status=T' );
431
432     $schema->storage->txn_rollback;
433 };
434
435 subtest 'PUT /holds/{hold_id}/priority tests' => sub {
436
437     plan tests => 14;
438
439     $schema->storage->txn_begin;
440
441     my $password = 'AbcdEFG123';
442
443     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
444     my $patron_np = $builder->build_object(
445         { class => 'Koha::Patrons', value => { flags => 0 } } );
446     $patron_np->set_password( { password => $password, skip_validation => 1 } );
447     my $userid_np = $patron_np->userid;
448
449     my $patron = $builder->build_object(
450         { class => 'Koha::Patrons', value => { flags => 0 } } );
451     $patron->set_password( { password => $password, skip_validation => 1 } );
452     my $userid = $patron->userid;
453     $builder->build(
454         {
455             source => 'UserPermission',
456             value  => {
457                 borrowernumber => $patron->borrowernumber,
458                 module_bit     => 6,
459                 code           => 'modify_holds_priority',
460             },
461         }
462     );
463
464     # Disable logging
465     t::lib::Mocks::mock_preference( 'HoldsLog',      0 );
466     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
467
468     my $biblio   = $builder->build_sample_biblio;
469     my $patron_1 = $builder->build_object(
470         {
471             class => 'Koha::Patrons',
472             value => { branchcode => $library->branchcode }
473         }
474     );
475     my $patron_2 = $builder->build_object(
476         {
477             class => 'Koha::Patrons',
478             value => { branchcode => $library->branchcode }
479         }
480     );
481     my $patron_3 = $builder->build_object(
482         {
483             class => 'Koha::Patrons',
484             value => { branchcode => $library->branchcode }
485         }
486     );
487
488     my $hold_1 = Koha::Holds->find(
489         AddReserve(
490             {
491                 branchcode     => $library->branchcode,
492                 borrowernumber => $patron_1->borrowernumber,
493                 biblionumber   => $biblio->biblionumber,
494                 priority       => 1,
495             }
496         )
497     );
498     my $hold_2 = Koha::Holds->find(
499         AddReserve(
500             {
501                 branchcode     => $library->branchcode,
502                 borrowernumber => $patron_2->borrowernumber,
503                 biblionumber   => $biblio->biblionumber,
504                 priority       => 2,
505             }
506         )
507     );
508     my $hold_3 = Koha::Holds->find(
509         AddReserve(
510             {
511                 branchcode     => $library->branchcode,
512                 borrowernumber => $patron_3->borrowernumber,
513                 biblionumber   => $biblio->biblionumber,
514                 priority       => 3,
515             }
516         )
517     );
518
519     $t->put_ok( "//$userid_np:$password@/api/v1/holds/"
520           . $hold_3->id
521           . "/priority" => json => 1 )->status_is(403);
522
523     $t->put_ok( "//$userid:$password@/api/v1/holds/"
524           . $hold_3->id
525           . "/priority" => json => 1 )->status_is(200)->json_is(1);
526
527     is( $hold_1->discard_changes->priority, 2, 'Priority adjusted correctly' );
528     is( $hold_2->discard_changes->priority, 3, 'Priority adjusted correctly' );
529     is( $hold_3->discard_changes->priority, 1, 'Priority adjusted correctly' );
530
531     $t->put_ok( "//$userid:$password@/api/v1/holds/"
532           . $hold_3->id
533           . "/priority" => json => 3 )->status_is(200)->json_is(3);
534
535     is( $hold_1->discard_changes->priority, 1, 'Priority adjusted correctly' );
536     is( $hold_2->discard_changes->priority, 2, 'Priority adjusted correctly' );
537     is( $hold_3->discard_changes->priority, 3, 'Priority adjusted correctly' );
538
539     $schema->storage->txn_rollback;
540 };