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