172a04993aa02f08e961f5ed4407bfc5fc9c25fc
[srvgit] / t / db_dependent / api / v1 / patrons.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 => 7;
21 use Test::MockModule;
22 use Test::Mojo;
23 use Test::Warn;
24
25 use t::lib::TestBuilder;
26 use t::lib::Mocks;
27 use t::lib::Dates;
28
29 use C4::Auth;
30 use C4::Members::Messaging;
31 use Koha::Database;
32 use Koha::DateUtils qw(dt_from_string output_pref);
33 use Koha::Exceptions::Patron;
34 use Koha::Exceptions::Patron::Attribute;
35 use Koha::Old::Patrons;
36 use Koha::Patron::Attributes;
37 use Koha::Patron::Debarments qw( AddDebarment );
38
39 use JSON qw(encode_json);
40
41 my $schema  = Koha::Database->new->schema;
42 my $builder = t::lib::TestBuilder->new;
43
44 my $t = Test::Mojo->new('Koha::REST::V1');
45 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
46
47 subtest 'list() tests' => sub {
48
49     plan tests => 3;
50
51     $schema->storage->txn_begin;
52     unauthorized_access_tests('GET', undef, undef);
53     $schema->storage->txn_rollback;
54
55     subtest 'librarian access tests' => sub {
56
57         plan tests => 19;
58
59         $schema->storage->txn_begin;
60
61         my $librarian = $builder->build_object(
62             {
63                 class => 'Koha::Patrons',
64                 value => { flags => 2**4 }    # borrowers flag = 4
65             }
66         );
67         my $password = 'thePassword123';
68         $librarian->set_password( { password => $password, skip_validation => 1 } );
69         my $userid = $librarian->userid;
70
71         $t->get_ok("//$userid:$password@/api/v1/patrons")
72           ->status_is(200);
73
74         $t->get_ok("//$userid:$password@/api/v1/patrons?cardnumber=" . $librarian->cardnumber)
75           ->status_is(200)
76           ->json_is('/0/cardnumber' => $librarian->cardnumber);
77
78         $t->get_ok("//$userid:$password@/api/v1/patrons?q={\"cardnumber\":\"" . $librarian->cardnumber ."\"}")
79           ->status_is(200)
80           ->json_is('/0/cardnumber' => $librarian->cardnumber);
81
82         $t->get_ok("//$userid:$password@/api/v1/patrons?address2=" . $librarian->address2)
83           ->status_is(200)
84           ->json_is('/0/address2' => $librarian->address2);
85
86         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
87         AddDebarment({ borrowernumber => $patron->borrowernumber });
88
89         $t->get_ok("//$userid:$password@/api/v1/patrons?restricted=" . Mojo::JSON->true . "&cardnumber=" . $patron->cardnumber )
90           ->status_is(200)
91           ->json_has('/0/restricted')
92           ->json_is( '/0/restricted' => Mojo::JSON->true )
93           ->json_hasnt('/1');
94
95         $t->get_ok( "//$userid:$password@/api/v1/patrons?"
96               . 'q={"extended_attributes.type":"CODE"}' =>
97               { 'x-koha-embed' => 'extended_attributes' } )
98           ->status_is( 200, "Works, doesn't explode" );
99
100         subtest 'searching date and date-time fields' => sub {
101
102             plan tests => 12;
103
104             my $date_of_birth = '1980-06-18';
105             my $last_seen     = '2021-06-25 14:05:35';
106
107             my $patron = $builder->build_object(
108                 {
109                     class => 'Koha::Patrons',
110                     value => {
111                         dateofbirth => $date_of_birth,
112                         lastseen    => $last_seen,
113                     }
114                 }
115             );
116
117             my $last_seen_rfc3339 = $last_seen . "z";
118
119             $t->get_ok("//$userid:$password@/api/v1/patrons?date_of_birth=" . $date_of_birth . "&cardnumber=" . $patron->cardnumber)
120               ->status_is(200)
121               ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' );
122
123             $t->get_ok("//$userid:$password@/api/v1/patrons?last_seen=" . $last_seen_rfc3339 . "&cardnumber=" . $patron->cardnumber)
124               ->status_is(200)
125               ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' );
126
127             my $q = encode_json(
128                 {
129                     date_of_birth => $date_of_birth,
130                     cardnumber    => $patron->cardnumber,
131                 }
132             );
133
134             $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q")
135               ->status_is(200)
136               ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' );
137
138             $q = encode_json(
139                 {
140                     last_seen  => $last_seen_rfc3339,
141                     cardnumber => $patron->cardnumber,
142                 }
143             );
144
145             $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q")
146               ->status_is(200)
147               ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' );
148         };
149
150         $schema->storage->txn_rollback;
151     };
152
153     subtest 'search_limited() tests' => sub {
154
155         plan tests => 9;
156
157         $schema->storage->txn_begin;
158
159         my $library_1 = $builder->build_object({ class => 'Koha::Libraries' });
160         my $library_2 = $builder->build_object({ class => 'Koha::Libraries' });
161
162         my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } });
163         my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } });
164         my $patron_3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_2->id } });
165
166         my @libraries_where_can_see_patrons = ($library_1->id, $library_2->id);
167
168         my $mocked_patron = Test::MockModule->new('Koha::Patron');
169         $mocked_patron->mock( 'libraries_where_can_see_patrons', sub
170             {
171                 return @libraries_where_can_see_patrons;
172             }
173         );
174
175         my $librarian = $builder->build_object(
176             {
177                 class => 'Koha::Patrons',
178                 value => { flags => 2**4 }    # borrowers flag = 4
179             }
180         );
181         my $password = 'thePassword123';
182         $librarian->set_password( { password => $password, skip_validation => 1 } );
183         my $userid = $librarian->userid;
184
185         $t->get_ok("//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" . encode_json({ library_id => [ $library_1->id, $library_2->id ] }))
186           ->status_is(200)
187           ->json_is( '/0/patron_id' => $patron_1->id )
188           ->json_is( '/1/patron_id' => $patron_2->id )
189           ->json_is( '/2/patron_id' => $patron_3->id );
190
191         @libraries_where_can_see_patrons = ($library_2->id);
192
193         my $res = $t->get_ok("//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" . encode_json({ library_id => [ $library_1->id, $library_2->id ] }))
194           ->status_is(200)
195           ->json_is( '/0/patron_id' => $patron_3->id, 'Returns the only allowed patron' )
196           ->tx->res->json;
197
198         is( scalar @{$res}, 1, 'Only one patron returned' );
199
200         $schema->storage->txn_rollback;
201     };
202 };
203
204 subtest 'get() tests' => sub {
205
206     plan tests => 3;
207
208     $schema->storage->txn_begin;
209     unauthorized_access_tests('GET', -1, undef);
210     $schema->storage->txn_rollback;
211
212     subtest 'librarian access tests' => sub {
213         plan tests => 6;
214
215         $schema->storage->txn_begin;
216
217         my $librarian = $builder->build_object(
218             {
219                 class => 'Koha::Patrons',
220                 value => { flags => 2**4 }    # borrowers flag = 4
221             }
222         );
223         my $password = 'thePassword123';
224         $librarian->set_password( { password => $password, skip_validation => 1 } );
225         my $userid = $librarian->userid;
226
227         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
228
229         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id)
230           ->status_is(200)
231           ->json_is('/patron_id'        => $patron->id)
232           ->json_is('/category_id'      => $patron->categorycode )
233           ->json_is('/surname'          => $patron->surname)
234           ->json_is('/patron_card_lost' => Mojo::JSON->false );
235
236         $schema->storage->txn_rollback;
237     };
238
239     subtest 'search_limited() tests' => sub {
240
241         plan tests => 12;
242
243         $schema->storage->txn_begin;
244
245         my $library_1 = $builder->build_object({ class => 'Koha::Libraries' });
246         my $library_2 = $builder->build_object({ class => 'Koha::Libraries' });
247         my $library_3 = $builder->build_object({ class => 'Koha::Libraries' });
248
249         my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } });
250         my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_2->id } });
251         my $patron_3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_3->id } });
252
253         my @libraries_where_can_see_patrons = ($library_1->id, $library_2->id);
254
255         my $mocked_patron = Test::MockModule->new('Koha::Patron');
256         $mocked_patron->mock( 'libraries_where_can_see_patrons', sub
257             {
258                 return @libraries_where_can_see_patrons;
259             }
260         );
261
262         my $librarian = $builder->build_object(
263             {   class => 'Koha::Patrons',
264                 value => { flags => 2**4, branchcode => $library_3->id }    # borrowers flag = 4
265             }
266         );
267         my $password = 'thePassword123';
268         $librarian->set_password( { password => $password, skip_validation => 1 } );
269         my $userid = $librarian->userid;
270
271         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_1->id )
272           ->status_is(200)
273           ->json_is( '/patron_id' => $patron_1->id );
274
275         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->id )
276           ->status_is(200)
277           ->json_is( '/patron_id' => $patron_2->id );
278
279         @libraries_where_can_see_patrons = ($library_1->id);
280
281         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_1->id )
282           ->status_is(200)
283           ->json_is( '/patron_id' => $patron_1->id );
284
285         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->id )
286           ->status_is(404)
287           ->json_is({ error => "Patron not found." });
288
289         $schema->storage->txn_rollback;
290     };
291 };
292
293 subtest 'add() tests' => sub {
294     plan tests => 2;
295
296     $schema->storage->txn_begin;
297
298     my $patron = $builder->build_object( { class => 'Koha::Patrons' } )->to_api;
299
300     unauthorized_access_tests('POST', undef, $patron);
301
302     $schema->storage->txn_rollback;
303
304     subtest 'librarian access tests' => sub {
305         plan tests => 25;
306
307         $schema->storage->txn_begin;
308
309         my $extended_attrs_exception;
310         my $type = 'hey';
311         my $code = 'ho';
312         my $attr = "Let's go";
313
314         # Disable trigger to notify patrons of password changes for these tests
315         t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 );
316
317         # Mock early, so existing mandatory attributes don't break all the tests
318         my $mocked_patron = Test::MockModule->new('Koha::Patron');
319         $mocked_patron->mock(
320             'extended_attributes',
321             sub {
322
323                 if ($extended_attrs_exception) {
324                     if ( $extended_attrs_exception eq 'Koha::Exceptions::Patron::Attribute::NonRepeatable'
325                         or $extended_attrs_exception eq 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint'
326                       )
327                     {
328                         $extended_attrs_exception->throw(
329                             attribute => Koha::Patron::Attribute->new(
330                                 { code => $code, attribute => $attr }
331                             )
332                         );
333                     }
334                     else {
335                         $extended_attrs_exception->throw( type => $type );
336                     }
337                 }
338                 return [];
339             }
340         );
341
342         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
343         my $newpatron = $patron->to_api;
344         # delete RO attributes
345         delete $newpatron->{patron_id};
346         delete $newpatron->{restricted};
347         delete $newpatron->{anonymized};
348
349         # Create a library just to make sure its ID doesn't exist on the DB
350         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
351         my $deleted_library_id = $library_to_delete->id;
352         # Delete library
353         $library_to_delete->delete;
354
355         my $librarian = $builder->build_object(
356             {
357                 class => 'Koha::Patrons',
358                 value => { flags => 2**4 }    # borrowers flag = 4
359             }
360         );
361         my $password = 'thePassword123';
362         $librarian->set_password( { password => $password, skip_validation => 1 } );
363         my $userid = $librarian->userid;
364
365         $newpatron->{library_id} = $deleted_library_id;
366
367         warning_like {
368             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
369               ->status_is(409)
370               ->json_is('/error' => "Duplicate ID"); }
371             qr/DBD::mysql::st execute failed: Duplicate entry/;
372
373         $newpatron->{library_id} = $patron->branchcode;
374
375         # Create a library just to make sure its ID doesn't exist on the DB
376         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
377         my $deleted_category_id = $category_to_delete->id;
378         # Delete library
379         $category_to_delete->delete;
380
381         $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category
382
383         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
384           ->status_is(400)
385           ->json_is('/error' => "Given category_id does not exist");
386         $newpatron->{category_id} = $patron->categorycode;
387
388         $newpatron->{falseproperty} = "Non existent property";
389
390         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
391           ->status_is(400);
392
393         delete $newpatron->{falseproperty};
394
395         my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
396         $newpatron = $patron_to_delete->to_api;
397         # delete RO attributes
398         delete $newpatron->{patron_id};
399         delete $newpatron->{restricted};
400         delete $newpatron->{anonymized};
401         $patron_to_delete->delete;
402
403         # Set a date field
404         $newpatron->{date_of_birth} = '1980-06-18';
405         # Set a date-time field
406         $newpatron->{last_seen} = output_pref({ dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' });
407
408         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
409           ->status_is(201, 'Patron created successfully')
410           ->header_like(
411             Location => qr|^\/api\/v1\/patrons/\d*|,
412             'SWAGGER3.4.1'
413           )
414           ->json_has('/patron_id', 'got a patron_id')
415           ->json_is( '/cardnumber'    => $newpatron->{ cardnumber })
416           ->json_is( '/surname'       => $newpatron->{ surname })
417           ->json_is( '/firstname'     => $newpatron->{ firstname })
418           ->json_is( '/date_of_birth' => $newpatron->{ date_of_birth }, 'Date field set (Bug 28585)' )
419           ->json_is( '/last_seen'     => $newpatron->{ last_seen }, 'Date-time field set (Bug 28585)' );
420
421         warning_like {
422             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
423               ->status_is(409)
424               ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' )
425               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
426             qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
427
428         subtest 'extended_attributes handling tests' => sub {
429
430             plan tests => 19;
431
432             my $patrons_count = Koha::Patrons->search->count;
433
434             $extended_attrs_exception = 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute';
435             $t->post_ok(
436                 "//$userid:$password@/api/v1/patrons" => json => {
437                     "firstname"   => "Katrina",
438                     "surname"     => "Fischer",
439                     "address"     => "Somewhere",
440                     "category_id" => "ST",
441                     "city"        => "Konstanz",
442                     "library_id"  => "MPL"
443                 }
444             )->status_is(400)
445               ->json_is( '/error' =>
446                   "Missing mandatory extended attribute (type=$type)" );
447
448             is( Koha::Patrons->search->count, $patrons_count, 'No patron added' );
449
450             $extended_attrs_exception = 'Koha::Exceptions::Patron::Attribute::InvalidType';
451             $t->post_ok(
452                 "//$userid:$password@/api/v1/patrons" => json => {
453                     "firstname"   => "Katrina",
454                     "surname"     => "Fischer",
455                     "address"     => "Somewhere",
456                     "category_id" => "ST",
457                     "city"        => "Konstanz",
458                     "library_id"  => "MPL"
459                 }
460             )->status_is(400)
461               ->json_is( '/error' =>
462                   "Tried to use an invalid attribute type. type=$type" );
463
464             is( Koha::Patrons->search->count, $patrons_count, 'No patron added' );
465
466             $extended_attrs_exception = 'Koha::Exceptions::Patron::Attribute::NonRepeatable';
467             $t->post_ok(
468                 "//$userid:$password@/api/v1/patrons" => json => {
469                     "firstname"   => "Katrina",
470                     "surname"     => "Fischer",
471                     "address"     => "Somewhere",
472                     "category_id" => "ST",
473                     "city"        => "Konstanz",
474                     "library_id"  => "MPL"
475                 }
476             )->status_is(400)
477               ->json_is( '/error' =>
478                   "Tried to add more than one non-repeatable attributes. type=$code value=$attr" );
479
480             is( Koha::Patrons->search->count, $patrons_count, 'No patron added' );
481
482             $extended_attrs_exception = 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint';
483             $t->post_ok(
484                 "//$userid:$password@/api/v1/patrons" => json => {
485                     "firstname"   => "Katrina",
486                     "surname"     => "Fischer",
487                     "address"     => "Somewhere",
488                     "category_id" => "ST",
489                     "city"        => "Konstanz",
490                     "library_id"  => "MPL"
491                 }
492             )->status_is(400)
493               ->json_is( '/error' =>
494                   "Your action breaks a unique constraint on the attribute. type=$code value=$attr" );
495
496             is( Koha::Patrons->search->count, $patrons_count, 'No patron added' );
497
498             $mocked_patron->unmock('extended_attributes');
499             # Temporarily get rid of mandatory attribute types
500             Koha::Patron::Attribute::Types->search({ mandatory => 1 })->delete;
501             # Create a couple attribute attribute types
502             my $repeatable_1 = $builder->build_object(
503                 {
504                     class => 'Koha::Patron::Attribute::Types',
505                     value => {
506                         mandatory     => 0,
507                         repeatable    => 1,
508                         unique_id     => 0,
509                         category_code => 'ST'
510                     }
511                 }
512             );
513             my $repeatable_2 = $builder->build_object(
514                 {
515                     class => 'Koha::Patron::Attribute::Types',
516                     value => {
517                         mandatory     => 0,
518                         repeatable    => 1,
519                         unique_id     => 0,
520                         category_code => 'ST'
521                     }
522                 }
523             );
524
525             my $patron_id = $t->post_ok(
526                 "//$userid:$password@/api/v1/patrons" => json => {
527                     "firstname"   => "Katrina",
528                     "surname"     => "Fischer",
529                     "address"     => "Somewhere",
530                     "category_id" => "ST",
531                     "city"        => "Konstanz",
532                     "library_id"  => "MPL",
533                     "extended_attributes" => [
534                         { type => $repeatable_1->code, value => 'a' },
535                         { type => $repeatable_1->code, value => 'b' },
536                         { type => $repeatable_1->code, value => 'c' },
537                         { type => $repeatable_2->code, value => 'd' },
538                         { type => $repeatable_2->code, value => 'e' }
539                     ]
540                 }
541             )->status_is(201, 'Patron added')->tx->res->json->{patron_id};
542             my $extended_attributes = join( ' ', sort map {$_->attribute} Koha::Patrons->find($patron_id)->extended_attributes->as_list);
543             is( $extended_attributes, 'a b c d e', 'Extended attributes are stored correctly');
544         };
545
546         subtest 'default patron messaging preferences handling' => sub {
547
548             plan tests => 3;
549
550             t::lib::Mocks::mock_preference( 'EnhancedMessagingPreferences', 1 );
551
552             C4::Members::Messaging::SetMessagingPreference({
553                 categorycode => 'ST',
554                 message_attribute_id => 1,
555                 message_transport_types => ['email'],
556                 wants_digest => 1
557             });
558
559             my $patron_id = $t->post_ok(
560                 "//$userid:$password@/api/v1/patrons" => json => {
561                     "firstname"   => "Nick",
562                     "surname"     => "Clemens",
563                     "address"     => "Somewhere",
564                     "category_id" => "ST",
565                     "city"        => "Smallville",
566                     "library_id"  => "MPL",
567                 }
568             )->status_is(201, 'Patron added')->tx->res->json->{patron_id};
569
570             my $messaging_preferences = C4::Members::Messaging::GetMessagingPreferences({ borrowernumber => $patron_id, message_name => 'Item_Due' });
571
572             is_deeply(
573                 $messaging_preferences,
574                 {
575                     letter_code => 'DUEDGST',
576                     wants_digest => 1,
577                     transports => { email => 'DUEDGST' }
578                 } ,
579                 'Default messaging preferences set correctly'
580             );
581         };
582
583         $schema->storage->txn_rollback;
584     };
585 };
586
587 subtest 'update() tests' => sub {
588     plan tests => 2;
589
590     $schema->storage->txn_begin;
591     unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'});
592     $schema->storage->txn_rollback;
593
594     subtest 'librarian access tests' => sub {
595         plan tests => 45;
596
597         $schema->storage->txn_begin;
598
599         my $authorized_patron = $builder->build_object(
600             {
601                 class => 'Koha::Patrons',
602                 value => { flags => 1 }
603             }
604         );
605         my $password = 'thePassword123';
606         $authorized_patron->set_password(
607             { password => $password, skip_validation => 1 } );
608         my $userid = $authorized_patron->userid;
609
610         my $unauthorized_patron = $builder->build_object(
611             {
612                 class => 'Koha::Patrons',
613                 value => { flags => 0 }
614             }
615         );
616         $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } );
617         my $unauth_userid = $unauthorized_patron->userid;
618
619         my $patron_1  = $authorized_patron;
620         my $patron_2  = $unauthorized_patron;
621         my $newpatron = $unauthorized_patron->to_api;
622         # delete RO attributes
623         delete $newpatron->{patron_id};
624         delete $newpatron->{restricted};
625         delete $newpatron->{anonymized};
626
627         $t->put_ok("//$userid:$password@/api/v1/patrons/-1" => json => $newpatron)
628           ->status_is(404)
629           ->json_has('/error', 'Fails when trying to PUT nonexistent patron');
630
631         # Create a library just to make sure its ID doesn't exist on the DB
632         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
633         my $deleted_category_id = $category_to_delete->id;
634         # Delete library
635         $category_to_delete->delete;
636
637         # Use an invalid category
638         $newpatron->{category_id} = $deleted_category_id;
639
640         $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
641           ->status_is(400)
642           ->json_is('/error' => "Given category_id does not exist");
643
644         # Restore the valid category
645         $newpatron->{category_id} = $patron_2->categorycode;
646
647         # Create a library just to make sure its ID doesn't exist on the DB
648         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
649         my $deleted_library_id = $library_to_delete->id;
650         # Delete library
651         $library_to_delete->delete;
652
653         # Use an invalid library_id
654         $newpatron->{library_id} = $deleted_library_id;
655
656         warning_like {
657             $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
658               ->status_is(400)
659               ->json_is('/error' => "Given library_id does not exist"); }
660             qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
661
662         # Restore the valid library_id
663         $newpatron->{library_id} = $patron_2->branchcode;
664
665         # Use an invalid attribute
666         $newpatron->{falseproperty} = "Non existent property";
667
668         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
669           ->status_is(400)
670           ->json_is('/errors/0/message' =>
671                     'Properties not allowed: falseproperty.');
672
673         # Get rid of the invalid attribute
674         delete $newpatron->{falseproperty};
675
676         # Set both cardnumber and userid to already existing values
677         $newpatron->{cardnumber} = $patron_1->cardnumber;
678         $newpatron->{userid}     = $patron_1->userid;
679
680         warning_like {
681             $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
682               ->status_is(409)
683               ->json_has( '/error', "Fails when trying to update to an existing cardnumber or userid")
684               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
685             qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
686
687         $newpatron->{ cardnumber } = $patron_1->id . $patron_2->id;
688         $newpatron->{ userid }     = "user" . $patron_1->id.$patron_2->id;
689         $newpatron->{ surname }    = "user" . $patron_1->id.$patron_2->id;
690
691         ## Trying to set to null on specially handled cases
692         # Special case: a date
693         $newpatron->{ date_of_birth } = undef;
694         # Special case: a date-time
695         $newpatron->{ last_seen } = undef;
696
697         my $result = $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
698           ->status_is(200, 'Patron updated successfully');
699
700         # Put back the RO attributes
701         $newpatron->{patron_id} = $unauthorized_patron->to_api->{patron_id};
702         $newpatron->{restricted} = $unauthorized_patron->to_api->{restricted};
703         $newpatron->{anonymized} = $unauthorized_patron->to_api->{anonymized};
704
705         my $got = $result->tx->res->json;
706         my $updated_on_got = delete $got->{updated_on};
707         my $updated_on_expected = delete $newpatron->{updated_on};
708         is_deeply($got, $newpatron, 'Returned patron from update matches expected');
709         is(
710             t::lib::Dates::compare(
711                 dt_from_string( $updated_on_got,      'rfc3339' ),
712                 dt_from_string( $updated_on_expected, 'rfc3339' )
713             ),
714             0,
715             'updated_on values matched'
716         );
717
718         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
719            $newpatron->{ cardnumber }, 'Patron is really updated!');
720
721         my $superlibrarian = $builder->build_object(
722             {
723                 class => 'Koha::Patrons',
724                 value => { flags => 1 }
725             }
726         );
727
728         $newpatron->{cardnumber} = $superlibrarian->cardnumber;
729         $newpatron->{userid}     = $superlibrarian->userid;
730         $newpatron->{email}      = 'nosense@no.no';
731         # delete RO attributes
732         delete $newpatron->{patron_id};
733         delete $newpatron->{restricted};
734         delete $newpatron->{anonymized};
735
736         # attempt to update
737         $authorized_patron->flags( 2**4 )->store; # borrowers flag = 4
738         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
739           ->status_is(403, "Non-superlibrarian user change of superlibrarian email forbidden")
740           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
741
742         # attempt to unset
743         $newpatron->{email} = undef;
744         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
745           ->status_is(403, "Non-superlibrarian user change of superlibrarian email to undefined forbidden")
746           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
747
748         $newpatron->{email}           = $superlibrarian->email;
749         $newpatron->{secondary_email} = 'nonsense@no.no';
750
751         # attempt to update
752         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
753           ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email forbidden")
754           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
755
756         # attempt to unset
757         $newpatron->{secondary_email} = undef;
758         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
759           ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email to undefined forbidden")
760           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
761
762         $newpatron->{secondary_email}  = $superlibrarian->emailpro;
763         $newpatron->{altaddress_email} = 'nonsense@no.no';
764
765         # attempt to update
766         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
767           ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email forbidden")
768           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
769
770         # attempt to unset
771         $newpatron->{altaddress_email} = undef;
772         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
773           ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email to undefined forbidden")
774           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
775
776         # update patron without sending email
777         delete $newpatron->{email};
778         delete $newpatron->{secondary_email};
779         delete $newpatron->{altaddress_email};
780
781         # Set a date field
782         $newpatron->{date_of_birth} = '1980-06-18';
783         # Set a date-time field
784         $newpatron->{last_seen} = output_pref({ dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' });
785
786         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
787           ->status_is(200, "Non-superlibrarian user can edit superlibrarian successfully if not changing email")
788           ->json_is( '/date_of_birth' => $newpatron->{ date_of_birth }, 'Date field set (Bug 28585)' )
789           ->json_is( '/last_seen'     => $newpatron->{ last_seen }, 'Date-time field set (Bug 28585)' );
790
791         $schema->storage->txn_rollback;
792     };
793 };
794
795 subtest 'delete() tests' => sub {
796     plan tests => 2;
797
798     $schema->storage->txn_begin;
799     unauthorized_access_tests('DELETE', 123, undef);
800     $schema->storage->txn_rollback;
801
802     subtest 'librarian access test' => sub {
803         plan tests => 18;
804
805         $schema->storage->txn_begin;
806
807         my $authorized_patron = $builder->build_object(
808             {
809                 class => 'Koha::Patrons',
810                 value => { flags => 2**4 }    # borrowers flag = 4
811             }
812         );
813         my $password = 'thePassword123';
814         $authorized_patron->set_password(
815             { password => $password, skip_validation => 1 } );
816         my $userid = $authorized_patron->userid;
817
818         $t->delete_ok("//$userid:$password@/api/v1/patrons/-1")
819           ->status_is(404, 'Patron not found');
820
821         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
822
823         t::lib::Mocks::mock_preference('AnonymousPatron', $patron->borrowernumber);
824         $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber )
825           ->status_is( 409, 'Anonymous patron cannot be deleted' )
826           ->json_is(
827             {
828                 error      => 'Anonymous patron cannot be deleted',
829                 error_code => 'is_anonymous_patron'
830             }
831           );
832         t::lib::Mocks::mock_preference('AnonymousPatron', 0); # back to default
833
834         t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' );
835
836         my $checkout = $builder->build_object(
837             {
838                 class => 'Koha::Checkouts',
839                 value => { borrowernumber => $patron->borrowernumber }
840             }
841         );
842         my $debit = $patron->account->add_debit({ amount => 10, interface => 'intranet', type => 'MANUAL' });
843         my $guarantee = $builder->build_object({ class => 'Koha::Patrons' });
844
845         $guarantee->add_guarantor({ guarantor_id => $patron->id, relationship => 'parent' });
846
847         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
848           ->status_is(409, 'Patron with checkouts cannot be deleted')
849           ->json_is(
850             {
851                 error      => 'Pending checkouts prevent deletion',
852                 error_code => 'has_checkouts'
853             }
854           );
855
856         # Make sure it has no pending checkouts
857         $checkout->delete;
858
859         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
860           ->status_is(409, 'Patron with debt cannot be deleted')
861           ->json_is(
862             {
863                 error      => 'Pending debts prevent deletion',
864                 error_code => 'has_debt'
865             }
866           );
867
868         # Make sure it has no debt
869         $patron->account->pay({ amount => 10, debits => [ $debit ] });
870
871         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
872           ->status_is(409, 'Patron with guarantees cannot be deleted')
873           ->json_is(
874             {
875                 error      => 'Patron is a guarantor and it prevents deletion',
876                 error_code => 'has_guarantees'
877             }
878           );
879
880         # Remove guarantee
881         $patron->guarantee_relationships->delete;
882
883         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
884           ->status_is(204, 'SWAGGER3.2.4')
885           ->content_is('', 'SWAGGER3.3.4');
886
887         my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber =>  $patron->borrowernumber });
888         is( $deleted_patrons->count, 1, 'The patron has been moved to the vault' );
889
890         $schema->storage->txn_rollback;
891     };
892 };
893
894 subtest 'guarantors_can_see_charges() tests' => sub {
895
896     plan tests => 11;
897
898     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
899     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
900
901     $schema->storage->txn_begin;
902
903     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } });
904     my $password = 'thePassword123';
905     $patron->set_password({ password => $password, skip_validation => 1 });
906     my $userid = $patron->userid;
907     my $patron_id = $patron->borrowernumber;
908
909     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 0 );
910
911     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
912       ->status_is( 403 )
913       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
914
915     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 1 );
916
917     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
918       ->status_is( 200 )
919       ->json_is( {} );
920
921     ok( $patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
922
923     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->false } )
924       ->status_is( 200 )
925       ->json_is( {} );
926
927     ok( !$patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
928
929     $schema->storage->txn_rollback;
930 };
931
932 subtest 'guarantors_can_see_checkouts() tests' => sub {
933
934     plan tests => 11;
935
936     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
937     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
938
939     $schema->storage->txn_begin;
940
941     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } });
942     my $password = 'thePassword123';
943     $patron->set_password({ password => $password, skip_validation => 1 });
944     my $userid = $patron->userid;
945     my $patron_id = $patron->borrowernumber;
946
947     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 0 );
948
949     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
950       ->status_is( 403 )
951       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
952
953     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 1 );
954
955     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
956       ->status_is( 200 )
957       ->json_is( {} );
958
959     ok( $patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
960
961     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->false } )
962       ->status_is( 200 )
963       ->json_is( {} );
964
965     ok( !$patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
966
967     $schema->storage->txn_rollback;
968 };
969
970 # Centralized tests for 401s and 403s assuming the endpoint requires
971 # borrowers flag for access
972 sub unauthorized_access_tests {
973     my ($verb, $patron_id, $json) = @_;
974
975     my $endpoint = '/api/v1/patrons';
976     $endpoint .= ($patron_id) ? "/$patron_id" : '';
977
978     subtest 'unauthorized access tests' => sub {
979         plan tests => 5;
980
981         my $verb_ok = lc($verb) . '_ok';
982
983         $t->$verb_ok($endpoint => json => $json)
984           ->status_is(401);
985
986         my $unauthorized_patron = $builder->build_object(
987             {
988                 class => 'Koha::Patrons',
989                 value => { flags => 0 }
990             }
991         );
992         my $password = "thePassword123!";
993         $unauthorized_patron->set_password(
994             { password => $password, skip_validation => 1 } );
995         my $unauth_userid = $unauthorized_patron->userid;
996
997         $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )
998           ->status_is(403)
999           ->json_has('/required_permissions');
1000     };
1001 }