Bug 35581: Koha::Illcomment* -> Koha::ILL::Comment*
[koha.git] / t / db_dependent / api / v1 / ill_requests.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 => 2;
21
22 use Test::MockModule;
23 use Test::MockObject;
24 use Test::Mojo;
25
26 use JSON qw(encode_json);
27
28 use t::lib::TestBuilder;
29 use t::lib::Mocks;
30
31 use Koha::AuthorisedValueCategories;
32 use Koha::Illrequests;
33 use Koha::DateUtils qw( format_sqldatetime );
34
35 my $schema  = Koha::Database->new->schema;
36 my $builder = t::lib::TestBuilder->new;
37
38 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
39
40 my $t = Test::Mojo->new('Koha::REST::V1');
41
42 subtest 'list() tests' => sub {
43
44     plan tests => 34;
45
46     # Mock ILLBackend (as object)
47     my $backend = Test::MockObject->new;
48     $backend->set_isa('Koha::Illbackends::Mock');
49     $backend->set_always('name', 'Mock');
50     $backend->set_always('capabilities', sub { return 'bar'; } );
51     $backend->mock(
52         'metadata',
53         sub {
54             my ( $self, $rq ) = @_;
55             return {
56                 ID => $rq->illrequest_id,
57                 Title => $rq->patron->borrowernumber
58             }
59         }
60     );
61     $backend->mock(
62         'status_graph', sub {},
63     );
64
65     # Mock Koha::Illrequest::load_backend (to load Mocked Backend)
66     my $illreqmodule = Test::MockModule->new('Koha::Illrequest');
67     $illreqmodule->mock( 'load_backend',
68         sub { my $self = shift; $self->{_my_backend} = $backend; return $self }
69     );
70
71     $schema->storage->txn_begin;
72
73     Koha::Illrequests->search->delete;
74
75     # create an authorized user
76     my $librarian = $builder->build_object(
77         {
78             class => 'Koha::Patrons',
79             value => { flags => 2 ** 22 } # 22 => ill
80         }
81     );
82     my $password = 'thePassword123';
83     $librarian->set_password( { password => $password, skip_validation => 1 } );
84     my $userid = $librarian->userid;
85
86     # create an unauthorized user
87     my $patron = $builder->build_object(
88         {
89             class => 'Koha::Patrons',
90             value => { flags => 0 }
91         }
92     );
93
94     $patron->set_password( { password => $password, skip_validation => 1 } );
95     my $unauth_userid = $patron->userid;
96
97     # Make sure the ILL_STATUS_ALIAS authorised value category is defined
98     unless ( Koha::AuthorisedValueCategories->search( { category_name => 'ILL_STATUS_ALIAS' } )->count > 0 ) {
99         $builder->build_object(
100             { class => 'Koha::AuthorisedValueCategories', value => { category_name => 'ILL_STATUS_ALIAS' } } );
101     }
102
103     my $tag = "Print copy";
104     my $av_code = "print_copy";
105     my $av  = $builder->build_object(
106         {   class => 'Koha::AuthorisedValues',
107             value => {
108                 category => 'ILL_STATUS_ALIAS',
109                 authorised_value => $av_code,
110                 lib      => $tag,
111             }
112         }
113     );
114
115     # No requests, expect empty
116     $t->get_ok("//$userid:$password@/api/v1/ill/requests")
117       ->status_is(200)
118       ->json_is( [] );
119
120
121     # Prepare some expected response structure
122     my $request_status = {
123         code =>"REQ",
124         str =>"Requested"
125     };
126
127     my $response_status = {
128         backend => $backend->name,
129         code =>$request_status->{code},
130         str =>$request_status->{str},
131         type =>"ill_status"
132     };
133
134     my $response_status_av = {
135         category => "ILL_STATUS_ALIAS",
136         code => $av_code,
137         str => $tag,
138         type => "av"
139     };
140
141     # Create some ILL requests
142     my $req_1 = $builder->build_object(
143         {
144             class => 'Koha::Illrequests',
145             value => {
146                 borrowernumber => $patron->borrowernumber,
147                 batch_id       => undef,
148                 status         => $request_status->{code},
149                 backend        => $backend->name,
150                 notesstaff     => '1'
151             }
152         }
153     );
154     my $req_2 = $builder->build_object(
155         {
156             class => 'Koha::Illrequests',
157             value => {
158                 batch_id     => undef,
159                 status       => $request_status->{code},
160                 backend      => $backend->name,
161                 status_alias => $av->authorised_value,
162                 notesstaff   => '2'
163             }
164
165         }
166     );
167     my $ret = $builder->build_object({ class => 'Koha::Illrequests', value => { status => 'RET' } });
168
169     # Three requests exist, expect all three to be returned
170     $t->get_ok("//$userid:$password@/api/v1/ill/requests")
171       ->status_is(200)
172       ->json_is( [ $req_1->to_api({user=> $librarian}), $req_2->to_api({user=> $librarian}), $ret->to_api({user=> $librarian}) ]);
173
174     my $status_query = encode_json({ status => 'REQ' });
175     my $status_alias_query = encode_json({ status_av => $av_code });
176
177     # x-koha-embed: +strings
178     # Two requests exist with status 'REQ', expect them to be returned
179     # One of which also has a status_alias, expect that to be in that request's body
180     $t->get_ok( "//$userid:$password@/api/v1/ill/requests?q=$status_query" => { "x-koha-embed" => "+strings" } )
181         ->status_is(200)->json_is(
182         [
183             { _strings => { status => $response_status }, %{ $req_1->to_api( { user => $librarian } ) } },
184             {
185                 _strings => { status => $response_status, status_av => $response_status_av },
186                 %{ $req_2->to_api( { user => $librarian } ) }
187             }
188         ]
189         );
190
191     # One request with status_alias 'print_copy' exists, expect that to be returned
192     $t->get_ok( "//$userid:$password@/api/v1/ill/requests?q=$status_alias_query" => { "x-koha-embed" => "+strings" } )
193         ->status_is(200)->json_is(
194         [
195             {
196                 _strings => { status => $response_status, status_av => $response_status_av },
197                 %{ $req_2->to_api( { user => $librarian } ) }
198             }
199         ]
200         );
201
202     # x-koha-embed: patron
203     my $patron_query = encode_json({ borrowernumber => $patron->borrowernumber });
204
205     # One request related to $patron, make sure it comes back
206     $t->get_ok( "//$userid:$password@/api/v1/ill/requests" => { "x-koha-embed" => "patron" } )->status_is(200)
207         ->json_has( '/0/patron', $patron->to_api( { user => $librarian } ) );
208
209     # x-koha-embed: comments
210     # Create comment
211     my $comment_text = "This is the comment";
212     my $comment = $builder->build_object({ class => 'Koha::ILL::Comments', value => { illrequest_id => $req_1->illrequest_id, comment => $comment_text , borrowernumber => $patron->borrowernumber } } );
213
214     # Make sure comments come back
215     $t->get_ok("//$userid:$password@/api/v1/ill/requests" => {"x-koha-embed" => "comments"} )
216       ->status_is(200)
217       ->json_has('/0/comments', $comment_text);
218
219     # x-koha-embed: id_prefix
220     # Mock Illrequest::Config to return a static prefix
221     my $id_prefix = 'ILL';
222     my $config = Test::MockObject->new;
223     $config->set_isa('Koha::Illrequest::Config::Mock');
224     $config->set_always('getPrefixes', $id_prefix);
225
226     # Make sure id_prefix comes back
227     $t->get_ok("//$userid:$password@/api/v1/ill/requests" => {"x-koha-embed" => "id_prefix"} )
228       ->status_is(200)
229       ->json_has('/0/id_prefix', $id_prefix);
230
231     # ILLHiddenRequestStatuses syspref
232     # Hide 'REQ', expect to return just 1 'RET'
233     t::lib::Mocks::mock_preference( 'ILLHiddenRequestStatuses', 'REQ' );
234     $t->get_ok("//$userid:$password@/api/v1/ill/requests")->status_is(200)
235         ->json_is( [ $ret->to_api( { user => $librarian } ) ] );
236
237     # Hide 'RET', expect to return 2 'REQ'
238     t::lib::Mocks::mock_preference( 'ILLHiddenRequestStatuses', 'RET' );
239     $t->get_ok("//$userid:$password@/api/v1/ill/requests?_order_by=staff_notes")->status_is(200)
240         ->json_is( [ $req_1->to_api( { user => $librarian } ), $req_2->to_api( { user => $librarian } ) ] );
241
242     # Status code
243     # Warn on unsupported query parameter
244     $t->get_ok( "//$userid:$password@/api/v1/ill/requests?request_blah=blah" )
245       ->status_is(400)
246       ->json_is(
247         [{ path => '/query/request_blah', message => 'Malformed query string'}]
248     );
249
250     # Unauthorized attempt to list
251     $t->get_ok(
252         "//$unauth_userid:$password@/api/v1/ill/requests")
253       ->status_is(403);
254
255     # DELETE method not supported
256     $t->delete_ok(
257         "//$unauth_userid:$password@/api/v1/ill/requests/1")
258       ->status_is(404);
259
260     #TODO; test complex query on extended_attributes
261
262     $schema->storage->txn_rollback;
263 };
264
265 subtest 'add() tests' => sub {
266
267     plan tests => 2;
268
269     $schema->storage->txn_begin;
270
271     # create an authorized user
272     my $patron = $builder->build_object({
273         class => 'Koha::Patrons',
274         value => { flags => 2 ** 22 } # 22 => ill
275     });
276     my $password = 'thePassword123';
277     $patron->set_password({ password => $password, skip_validation => 1 });
278     my $userid = $patron->userid;
279
280     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
281
282     # Create an ILL request
283     my $illrequest = $builder->build_object(
284         {
285             class => 'Koha::Illrequests',
286             value => {
287                 backend        => 'Mock',
288                 branchcode     => $library->branchcode,
289                 borrowernumber => $patron->borrowernumber,
290                 status         => 'STATUS1',
291             }
292         }
293     );
294
295     # Mock ILLBackend (as object)
296     my $backend = Test::MockObject->new;
297     $backend->set_isa('Koha::Illbackends::Mock');
298     $backend->set_always('name', 'Mock');
299
300     $backend->mock(
301         'metadata',
302         sub {
303             my ( $self, $rq ) = @_;
304             return {
305                 ID => $rq->illrequest_id,
306                 Title => $rq->patron->borrowernumber
307             }
308         }
309     );
310     $backend->mock(
311         'status_graph', sub {},
312     );
313
314     # Mock Koha::Illrequest::load_backend (to load Mocked Backend)
315     my $illreqmodule = Test::MockModule->new('Koha::Illrequest');
316     $illreqmodule->mock(
317         'load_backend',
318         sub { my $self = shift; $self->{_my_backend} = $backend; return $self }
319     );
320
321     $illreqmodule->mock(
322         '_backend',
323         sub {
324             my $self = shift;
325             $self->{_my_backend} = $backend if ($backend);
326
327             return $self;
328             }
329     );
330
331     $illreqmodule->mock(
332         'capabilities',
333         sub {
334             my ( $self, $name ) = @_;
335
336             my $capabilities = {
337
338                 create_api => sub {
339                     my ($body, $request ) = @_;
340
341                     my $api_req = $builder->build_object(
342                         {
343                             class => 'Koha::Illrequests',
344                             value => {
345                                 borrowernumber => $patron->borrowernumber,
346                                 batch_id       => undef,
347                                 status         => 'NEW',
348                                 backend        => $backend->name,
349                             }
350                         }
351                     );
352
353                     return $api_req;
354                 }
355             };
356
357             return $capabilities->{$name};
358         }
359     );
360
361     $schema->storage->txn_begin;
362
363     Koha::Illrequests->search->delete;
364
365     my $body = {
366         ill_backend_id => 'Mock',
367         patron_id => $patron->borrowernumber,
368         library_id => $library->branchcode
369     };
370
371     ## Authorized user test
372     $t->post_ok( "//$userid:$password@/api/v1/ill/requests" => json => $body)
373       ->status_is(201);
374
375     $schema->storage->txn_rollback;
376 };