Bug 23710: (follow-up) Add tests for new features in Koha::REST::V!::Holds::add and...
[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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 $dbh->do('DELETE FROM issuingrules');
118     $dbh->do(q{
119         INSERT INTO issuingrules (categorycode, branchcode, itemtype, reservesallowed)
120         VALUES (?, ?, ?, ?)
121     }, {}, '*', '*', '*', 1);
122
123 my $reserve_id = C4::Reserves::AddReserve($branchcode, $patron_1->borrowernumber,
124     $biblio_1->biblionumber, undef, 1, undef, undef, undef, '', $item_1->itemnumber);
125
126 # Add another reserve to be able to change first reserve's rank
127 my $reserve_id2 = C4::Reserves::AddReserve($branchcode, $patron_2->borrowernumber,
128     $biblio_1->biblionumber, undef, 2, undef, undef, undef, '', $item_1->itemnumber);
129
130 my $suspended_until = DateTime->now->add(days => 10)->truncate( to => 'day' );
131 my $expiration_date = DateTime->now->add(days => 10)->truncate( to => 'day' );
132
133 my $post_data = {
134     patron_id => int($patron_1->borrowernumber),
135     biblio_id => int($biblio_1->biblionumber),
136     item_id => int($item_1->itemnumber),
137     pickup_library_id => $branchcode,
138     expiration_date => output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }),
139     priority => 2,
140 };
141 my $put_data = {
142     priority => 2,
143     suspended_until => output_pref({ dt => $suspended_until, dateformat => 'rfc3339' }),
144 };
145
146 subtest "Test endpoints without authentication" => sub {
147     plan tests => 8;
148     $t->get_ok('/api/v1/holds')
149       ->status_is(401);
150     $t->post_ok('/api/v1/holds')
151       ->status_is(401);
152     $t->put_ok('/api/v1/holds/0')
153       ->status_is(401);
154     $t->delete_ok('/api/v1/holds/0')
155       ->status_is(401);
156 };
157
158 subtest "Test endpoints without permission" => sub {
159
160     plan tests => 10;
161
162     $t->get_ok( "//$nopermission_userid:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission
163       ->status_is(403);
164
165     $t->get_ok( "//$userid_3:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )    # no permission
166       ->status_is(403);
167
168     $t->post_ok( "//$nopermission_userid:$password@/api/v1/holds" => json => $post_data )
169       ->status_is(403);
170
171     $t->put_ok( "//$nopermission_userid:$password@/api/v1/holds/0" => json => $put_data )
172       ->status_is(403);
173
174     $t->delete_ok( "//$nopermission_userid:$password@/api/v1/holds/0" )
175       ->status_is(403);
176 };
177
178 subtest "Test endpoints with permission" => sub {
179
180     plan tests => 44;
181
182     $t->get_ok( "//$userid_1:$password@/api/v1/holds" )
183       ->status_is(200)
184       ->json_has('/0')
185       ->json_has('/1')
186       ->json_hasnt('/2');
187
188     $t->get_ok( "//$userid_1:$password@/api/v1/holds?priority=2" )
189       ->status_is(200)
190       ->json_is('/0/patron_id', $patron_2->borrowernumber)
191       ->json_hasnt('/1');
192
193     $t->put_ok( "//$userid_1:$password@/api/v1/holds/$reserve_id" => json => $put_data )
194       ->status_is(200)
195       ->json_is( '/hold_id', $reserve_id )
196       ->json_is( '/suspended_until', output_pref({ dt => $suspended_until, dateformat => 'rfc3339' }) )
197       ->json_is( '/priority', 2 );
198
199     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
200       ->status_is(200);
201
202     $t->put_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" => json => $put_data )
203       ->status_is(404)
204       ->json_has('/error');
205
206     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
207       ->status_is(404)
208       ->json_has('/error');
209
210     $t->get_ok( "//$userid_2:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
211       ->status_is(200)
212       ->json_is([]);
213
214     my $inexisting_borrowernumber = $patron_2->borrowernumber * 2;
215     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=$inexisting_borrowernumber")
216       ->status_is(200)
217       ->json_is([]);
218
219     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id2" )
220       ->status_is(200);
221
222     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
223       ->status_is(201)
224       ->json_has('/hold_id');
225     # Get id from response
226     $reserve_id = $t->tx->res->json->{hold_id};
227
228     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
229       ->status_is(200)
230       ->json_is('/0/hold_id', $reserve_id)
231       ->json_is('/0/expiration_date', output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }))
232       ->json_is('/0/pickup_library_id', $branchcode);
233
234     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
235       ->status_is(403)
236       ->json_like('/error', qr/itemAlreadyOnHold/);
237
238     $post_data->{biblionumber} = int($biblio_2->biblionumber);
239     $post_data->{itemnumber}   = int($item_2->itemnumber);
240
241     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
242       ->status_is(403)
243       ->json_like('/error', qr/itemAlreadyOnHold/);
244 };
245
246 subtest 'Reserves with itemtype' => sub {
247     plan tests => 9;
248
249     my $post_data = {
250         patron_id => int($patron_1->borrowernumber),
251         biblio_id => int($biblio_1->biblionumber),
252         pickup_library_id => $branchcode,
253         item_type => $itemtype,
254     };
255
256     $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" )
257       ->status_is(200);
258
259     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
260       ->status_is(201)
261       ->json_has('/hold_id');
262
263     $reserve_id = $t->tx->res->json->{hold_id};
264
265     $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )
266       ->status_is(200)
267       ->json_is('/0/hold_id', $reserve_id)
268       ->json_is('/0/item_type', $itemtype);
269 };
270
271
272 subtest 'test AllowHoldDateInFuture' => sub {
273
274     plan tests => 6;
275
276     $dbh->do('DELETE FROM reserves');
277
278     my $future_hold_date = DateTime->now->add(days => 10)->truncate( to => 'day' );
279
280     my $post_data = {
281         patron_id => int($patron_1->borrowernumber),
282         biblio_id => int($biblio_1->biblionumber),
283         item_id => int($item_1->itemnumber),
284         pickup_library_id => $branchcode,
285         expiration_date => output_pref({ dt => $expiration_date, dateformat => 'rfc3339', dateonly => 1 }),
286         hold_date => output_pref({ dt => $future_hold_date, dateformat => 'rfc3339', dateonly => 1 }),
287         priority => 2,
288     };
289
290     t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 0 );
291
292     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
293       ->status_is(400)
294       ->json_has('/error');
295
296     t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 );
297
298     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
299       ->status_is(201)
300       ->json_is('/hold_date', output_pref({ dt => $future_hold_date, dateformat => 'rfc3339', dateonly => 1 }));
301 };
302
303 subtest 'test AllowHoldPolicyOverride' => sub {
304
305     plan tests => 5;
306
307     $dbh->do('DELETE FROM reserves');
308
309     Koha::CirculationRules->set_rules(
310         {
311             categorycode => undef,
312             itemtype     => undef,
313             branchcode   => undef,
314             rules        => {
315                 holdallowed              => 1
316             }
317         }
318     );
319
320     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 );
321
322     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
323       ->status_is(403)
324       ->json_has('/error');
325
326     t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 );
327
328     $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )
329       ->status_is(201);
330 };
331
332 $schema->storage->txn_rollback;
333
334 subtest 'suspend and resume tests' => sub {
335
336     plan tests => 21;
337
338     $schema->storage->txn_begin;
339
340     my $password = 'AbcdEFG123';
341
342     my $patron = $builder->build_object(
343         { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 1 } } );
344     $patron->set_password({ password => $password, skip_validation => 1 });
345     my $userid = $patron->userid;
346
347     # Disable logging
348     t::lib::Mocks::mock_preference( 'HoldsLog',      0 );
349     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
350
351     my $hold = $builder->build_object(
352         {   class => 'Koha::Holds',
353             value => { suspend => 0, suspend_until => undef, waitingdate => undef }
354         }
355     );
356
357     ok( !$hold->is_suspended, 'Hold is not suspended' );
358     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
359         ->status_is( 201, 'Hold suspension created' );
360
361     $hold->discard_changes;    # refresh object
362
363     ok( $hold->is_suspended, 'Hold is suspended' );
364     $t->json_is(
365         '/end_date',
366         output_pref(
367             {   dt         => dt_from_string( $hold->suspend_until ),
368                 dateformat => 'rfc3339',
369                 dateonly   => 1
370             }
371         )
372     );
373
374     $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
375       ->status_is( 204, "Correct status when deleting a resource" )
376       ->json_is( undef );
377
378     # Pass a an expiration date for the suspension
379     my $date = dt_from_string()->add( days => 5 );
380     $t->post_ok(
381               "//$userid:$password@/api/v1/holds/"
382             . $hold->id
383             . "/suspension" => json => {
384             end_date =>
385                 output_pref( { dt => $date, dateformat => 'rfc3339', dateonly => 1 } )
386             }
387     )->status_is( 201, 'Hold suspension created' )
388         ->json_is( '/end_date',
389         output_pref( { dt => $date, dateformat => 'rfc3339', dateonly => 1 } ) )
390         ->header_is( Location => "/api/v1/holds/" . $hold->id . "/suspension", 'The Location header is set' );
391
392     $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
393       ->status_is( 204, "Correct status when deleting a resource" )
394       ->json_is( undef );
395
396     $hold->set_waiting->discard_changes;
397
398     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
399       ->status_is( 400, 'Cannot suspend waiting hold' )
400       ->json_is( '/error', 'Found hold cannot be suspended. Status=W' );
401
402     $hold->set_waiting(1)->discard_changes;
403
404     $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )
405       ->status_is( 400, 'Cannot suspend waiting hold' )
406       ->json_is( '/error', 'Found hold cannot be suspended. Status=T' );
407
408     $schema->storage->txn_rollback;
409 };
410
411 subtest 'PUT /holds/{hold_id}/priority tests' => sub {
412
413     plan tests => 14;
414
415     $schema->storage->txn_begin;
416
417     my $password = 'AbcdEFG123';
418
419     my $library  = $builder->build_object({ class => 'Koha::Libraries' });
420     my $patron_np = $builder->build_object(
421         { class => 'Koha::Patrons', value => { flags => 0 } } );
422     $patron_np->set_password( { password => $password, skip_validation => 1 } );
423     my $userid_np = $patron_np->userid;
424
425     my $patron = $builder->build_object(
426         { class => 'Koha::Patrons', value => { flags => 0 } } );
427     $patron->set_password( { password => $password, skip_validation => 1 } );
428     my $userid = $patron->userid;
429     $builder->build(
430         {
431             source => 'UserPermission',
432             value  => {
433                 borrowernumber => $patron->borrowernumber,
434                 module_bit     => 6,
435                 code           => 'modify_holds_priority',
436             },
437         }
438     );
439
440     # Disable logging
441     t::lib::Mocks::mock_preference( 'HoldsLog',      0 );
442     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
443
444     my $biblio   = $builder->build_sample_biblio;
445     my $patron_1 = $builder->build_object(
446         {
447             class => 'Koha::Patrons',
448             value => { branchcode => $library->branchcode }
449         }
450     );
451     my $patron_2 = $builder->build_object(
452         {
453             class => 'Koha::Patrons',
454             value => { branchcode => $library->branchcode }
455         }
456     );
457     my $patron_3 = $builder->build_object(
458         {
459             class => 'Koha::Patrons',
460             value => { branchcode => $library->branchcode }
461         }
462     );
463
464     my $hold_1 = Koha::Holds->find(
465         AddReserve(
466             $library->branchcode,  $patron_1->borrowernumber,
467             $biblio->biblionumber, undef,
468             1
469         )
470     );
471     my $hold_2 = Koha::Holds->find(
472         AddReserve(
473             $library->branchcode,  $patron_2->borrowernumber,
474             $biblio->biblionumber, undef,
475             2
476         )
477     );
478     my $hold_3 = Koha::Holds->find(
479         AddReserve(
480             $library->branchcode,  $patron_3->borrowernumber,
481             $biblio->biblionumber, undef,
482             3
483         )
484     );
485
486     $t->put_ok( "//$userid_np:$password@/api/v1/holds/"
487           . $hold_3->id
488           . "/priority" => json => 1 )->status_is(403);
489
490     $t->put_ok( "//$userid:$password@/api/v1/holds/"
491           . $hold_3->id
492           . "/priority" => json => 1 )->status_is(200)->json_is(1);
493
494     is( $hold_1->discard_changes->priority, 2, 'Priority adjusted correctly' );
495     is( $hold_2->discard_changes->priority, 3, 'Priority adjusted correctly' );
496     is( $hold_3->discard_changes->priority, 1, 'Priority adjusted correctly' );
497
498     $t->put_ok( "//$userid:$password@/api/v1/holds/"
499           . $hold_3->id
500           . "/priority" => json => 3 )->status_is(200)->json_is(3);
501
502     is( $hold_1->discard_changes->priority, 1, 'Priority adjusted correctly' );
503     is( $hold_2->discard_changes->priority, 2, 'Priority adjusted correctly' );
504     is( $hold_3->discard_changes->priority, 3, 'Priority adjusted correctly' );
505
506     $schema->storage->txn_rollback;
507 };