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