Bug 33608: Redirect UpdateStats to Koha namespace
[koha.git] / t / db_dependent / Koha / Patrons.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 Koha Development team
4 #
5 # This file is part of Koha
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Test::More tests => 43;
23 use Test::Warn;
24 use Test::Exception;
25 use Test::MockModule;
26 use Time::Fake;
27 use DateTime;
28 use JSON;
29 use utf8;
30
31 use C4::Circulation qw( AddIssue AddReturn );
32 use C4::Biblio;
33 use C4::Auth qw( checkpw checkpw_hash );
34
35 use Koha::ActionLogs;
36 use Koha::Holds;
37 use Koha::Old::Holds;
38 use Koha::Patrons;
39 use Koha::Old::Patrons;
40 use Koha::Patron::Attribute::Types;
41 use Koha::Patron::Categories;
42 use Koha::Patron::Relationship;
43 use Koha::Database;
44 use Koha::DateUtils qw( dt_from_string output_pref );
45 use Koha::Virtualshelf;
46 use Koha::Virtualshelves;
47 use Koha::Notice::Messages;
48
49 use t::lib::TestBuilder;
50 use t::lib::Mocks;
51
52 my $schema = Koha::Database->new->schema;
53 $schema->storage->txn_begin;
54
55 my $builder       = t::lib::TestBuilder->new;
56 my $library = $builder->build({source => 'Branch' });
57 my $category = $builder->build({source => 'Category' });
58 my $nb_of_patrons = Koha::Patrons->search->count;
59 my $new_patron_1  = Koha::Patron->new(
60     {   cardnumber => 'test_cn_1',
61         branchcode => $library->{branchcode},
62         categorycode => $category->{categorycode},
63         surname => 'surname for patron1',
64         firstname => 'firstname for patron1',
65         userid => 'a_nonexistent_userid_1',
66         flags => 1, # Is superlibrarian
67     }
68 )->store;
69 my $new_patron_2  = Koha::Patron->new(
70     {   cardnumber => 'test_cn_2',
71         branchcode => $library->{branchcode},
72         categorycode => $category->{categorycode},
73         surname => 'surname for patron2',
74         firstname => 'firstname for patron2',
75         userid => 'a_nonexistent_userid_2',
76     }
77 )->store;
78
79 t::lib::Mocks::mock_userenv({ patron => $new_patron_1 });
80
81 is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' );
82
83 my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber );
84 is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' );
85
86 subtest 'library' => sub {
87     plan tests => 2;
88     is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' );
89     is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' );
90 };
91
92 subtest 'sms_provider' => sub {
93     plan tests => 3;
94     my $sms_provider = $builder->build({source => 'SmsProvider' });
95     is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' );
96     $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store;
97     is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' );
98     is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' );
99 };
100
101 subtest 'guarantees' => sub {
102
103     plan tests => 9;
104
105     t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' );
106
107     my $guarantees = $new_patron_1->guarantee_relationships;
108     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' );
109     is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' );
110
111     my $guarantee_1 = $builder->build({ source => 'Borrower' });
112     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
113     my $guarantee_2 = $builder->build({ source => 'Borrower' });
114     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
115
116     $guarantees = $new_patron_1->guarantee_relationships;
117     is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' );
118     is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' );
119
120     $guarantees->delete;
121
122     #Test return order of guarantees BZ 18635
123     my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
124     my $branchcode = $builder->build({ source => 'Branch' })->{branchcode};
125
126     my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } );
127
128     my $order_guarantee1 = $builder->build_object(
129         {
130             class => 'Koha::Patrons',
131             value => {
132                 surname     => 'Zebra',
133             }
134         }
135     )->borrowernumber;
136     $builder->build_object(
137         {
138             class => 'Koha::Patron::Relationships',
139             value => {
140                 guarantor_id  => $guarantor->id,
141                 guarantee_id => $order_guarantee1,
142                 relationship => 'test',
143             }
144         }
145     );
146
147     my $order_guarantee2 = $builder->build_object(
148         {
149             class => 'Koha::Patrons',
150             value => {
151                 surname     => 'Yak',
152             }
153         }
154     )->borrowernumber;
155     $builder->build_object(
156         {
157             class => 'Koha::Patron::Relationships',
158             value => {
159                 guarantor_id  => $guarantor->id,
160                 guarantee_id => $order_guarantee2,
161                 relationship => 'test',
162             }
163         }
164     );
165
166     my $order_guarantee3 = $builder->build_object(
167         {
168             class => 'Koha::Patrons',
169             value => {
170                 surname     => 'Xerus',
171                 firstname   => 'Walrus',
172             }
173         }
174     )->borrowernumber;
175     $builder->build_object(
176         {
177             class => 'Koha::Patron::Relationships',
178             value => {
179                 guarantor_id  => $guarantor->id,
180                 guarantee_id => $order_guarantee3,
181                 relationship => 'test',
182             }
183         }
184     );
185
186     my $order_guarantee4 = $builder->build_object(
187         {
188             class => 'Koha::Patrons',
189             value => {
190                 surname     => 'Xerus',
191                 firstname   => 'Vulture',
192             }
193         }
194     )->borrowernumber;
195     $builder->build_object(
196         {
197             class => 'Koha::Patron::Relationships',
198             value => {
199                 guarantor_id  => $guarantor->id,
200                 guarantee_id => $order_guarantee4,
201                 relationship => 'test',
202             }
203         }
204     );
205
206     my $order_guarantee5 = $builder->build_object(
207         {
208             class => 'Koha::Patrons',
209             value => {
210                 surname     => 'Xerus',
211                 firstname   => 'Unicorn',
212             }
213         }
214     )->borrowernumber;
215     my $r = $builder->build_object(
216         {
217             class => 'Koha::Patron::Relationships',
218             value => {
219                 guarantor_id  => $guarantor->id,
220                 guarantee_id => $order_guarantee5,
221                 relationship => 'test',
222             }
223         }
224     );
225
226     $guarantees = $guarantor->guarantee_relationships->guarantees;
227
228     is( $guarantees->next()->borrowernumber, $order_guarantee5, "Return first guarantor alphabetically" );
229     is( $guarantees->next()->borrowernumber, $order_guarantee4, "Return second guarantor alphabetically" );
230     is( $guarantees->next()->borrowernumber, $order_guarantee3, "Return third guarantor alphabetically" );
231     is( $guarantees->next()->borrowernumber, $order_guarantee2, "Return fourth guarantor alphabetically" );
232     is( $guarantees->next()->borrowernumber, $order_guarantee1, "Return fifth guarantor alphabetically" );
233 };
234
235 subtest 'category' => sub {
236     plan tests => 2;
237     my $patron_category = $new_patron_1->category;
238     is( ref( $patron_category), 'Koha::Patron::Category', );
239     is( $patron_category->categorycode, $category->{categorycode}, );
240 };
241
242 subtest 'siblings' => sub {
243
244     plan tests => 6;
245
246     my $siblings = $new_patron_1->siblings;
247     is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' );
248     my $guarantee_1 = $builder->build( { source => 'Borrower' } );
249     my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store();
250     my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1);
251     $siblings = $retrieved_guarantee_1->siblings;
252     is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' );
253     is( $siblings->count,  0,       'guarantee_1 should not have siblings yet' );
254     my $guarantee_2 = $builder->build( { source => 'Borrower' } );
255     my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store();
256     my $guarantee_3 = $builder->build( { source => 'Borrower' } );
257     my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store();
258     $siblings = $retrieved_guarantee_1->siblings;
259     is( $siblings->count,               2,                               'guarantee_1 should have 2 siblings' );
260     is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' );
261     is( $guarantee_3->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_3 should exist in the guarantees' );
262     $_->delete for $retrieved_guarantee_1->siblings;
263     $retrieved_guarantee_1->delete;
264 };
265
266 subtest 'has_overdues' => sub {
267     plan tests => 3;
268
269     my $item_1 = $builder->build_sample_item;
270     my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
271     is( $retrieved_patron->has_overdues, 0, );
272
273     my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 );
274     my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store();
275     is( $retrieved_patron->has_overdues, 0, );
276     $issue->delete();
277     my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 );
278     $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store();
279     $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber );
280     is( $retrieved_patron->has_overdues, 1, );
281     $issue->delete();
282 };
283
284 subtest 'is_expired' => sub {
285     plan tests => 4;
286     my $patron = $builder->build({ source => 'Borrower' });
287     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
288     $patron->dateexpiry( undef )->store->discard_changes;
289     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set');
290     $patron->dateexpiry( dt_from_string )->store->discard_changes;
291     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today');
292     $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes;
293     is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow');
294     $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes;
295     is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday');
296
297     $patron->delete;
298 };
299
300 subtest 'is_going_to_expire' => sub {
301     plan tests => 9;
302
303     my $today = dt_from_string(undef, undef, 'floating');
304     my $patron = $builder->build({ source => 'Borrower' });
305     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
306     $patron->dateexpiry( undef )->store->discard_changes;
307     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set');
308
309     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
310     $patron->dateexpiry( $today )->store->discard_changes;
311     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today');
312
313     $patron->dateexpiry( $today )->store->discard_changes;
314     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0');
315
316     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
317     $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes;
318     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10');
319
320     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0);
321     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
322     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0');
323
324     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
325     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
326     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10');
327     $patron->delete;
328
329     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10);
330     $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes;
331     is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10');
332
333     t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20);
334     $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes;
335     is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20');
336
337     { # Testing invalid is going to expiry date
338         t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30);
339         # mock_config does not work here, because of tz vs timezone subroutines
340         my $context = Test::MockModule->new('C4::Context');
341         $context->mock( 'tz', sub {
342             'America/Sao_Paulo';
343         });
344         $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store;
345         eval { $patron->is_going_to_expire };
346         is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"');
347         $context->unmock('tz');
348     };
349
350     $patron->delete;
351 };
352
353
354 subtest 'renew_account' => sub {
355     plan tests => 48;
356
357     for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) {
358         my $dt = dt_from_string( $date, 'iso' );
359         Time::Fake->offset( $dt->epoch );
360         my $a_month_ago                = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' );
361         my $a_year_later               = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
362         my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
363         my $a_month_later              = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' );
364         my $a_year_later_plus_a_month  = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' );
365         my $patron_category = $builder->build(
366             {   source => 'Category',
367                 value  => {
368                     enrolmentperiod     => 12,
369                     enrolmentperioddate => undef,
370                 }
371             }
372         );
373         my $patron = $builder->build(
374             {   source => 'Borrower',
375                 value  => {
376                     dateexpiry   => $a_month_ago,
377                     categorycode => $patron_category->{categorycode},
378                     date_renewed => undef, # Force builder to not populate the column for new patron
379                 }
380             }
381         );
382         my $patron_2 = $builder->build(
383             {  source => 'Borrower',
384                value  => {
385                    dateexpiry => $a_month_ago,
386                    categorycode => $patron_category->{categorycode},
387                 }
388             }
389         );
390         my $patron_3 = $builder->build(
391             {  source => 'Borrower',
392                value  => {
393                    dateexpiry => $a_month_later,
394                    categorycode => $patron_category->{categorycode},
395                }
396             }
397         );
398         my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
399         my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} );
400         my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} );
401
402         is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" );
403
404         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' );
405         t::lib::Mocks::mock_preference( 'BorrowersLog',              1 );
406         my $expiry_date = $retrieved_patron->renew_account;
407         is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
408         my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry;
409         is( dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" );
410         my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
411         is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' );
412
413         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' );
414         t::lib::Mocks::mock_preference( 'BorrowersLog',              0 );
415         $expiry_date = $retrieved_patron->renew_account;
416         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
417         $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
418         is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" );
419         $retrieved_expiry_date = $retrieved_patron->dateexpiry;
420         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
421         $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count;
422         is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' );
423
424         t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' );
425         $expiry_date = $retrieved_patron_2->renew_account;
426         is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" );
427         $retrieved_expiry_date = Koha::Patrons->find( $patron_2->{borrowernumber} )->dateexpiry;
428         is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" );
429
430         $expiry_date = $retrieved_patron_3->renew_account;
431         is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
432         $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry;
433         is( dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" );
434
435         $retrieved_patron->delete;
436         $retrieved_patron_2->delete;
437         $retrieved_patron_3->delete;
438     }
439     Time::Fake->reset;
440 };
441
442 subtest "move_to_deleted" => sub {
443     plan tests => 5;
444     my $originally_updated_on = '2016-01-01 12:12:12';
445     my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } );
446     my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} );
447     is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' )
448       ;    # FIXME This should be Koha::Deleted::Patron
449     my $deleted_patron = $schema->resultset('Deletedborrower')
450         ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } )
451         ->next;
452     ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' );
453     ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' );
454     isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column');
455     $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields
456     is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' );
457     $retrieved_patron->delete( $patron->{borrowernumber} );    # Cleanup
458 };
459
460 subtest "delete" => sub {
461     plan tests => 16;
462     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
463     t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' );
464     t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef );
465     Koha::Virtualshelves->delete;
466
467     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
468     my $patron_for_sharing = $builder->build_object({ class => 'Koha::Patrons' });
469     my $staff_patron = $builder->build_object({ class => 'Koha::Patrons' });
470     t::lib::Mocks::mock_userenv({ patron => $staff_patron });
471
472     my $hold = $builder->build_object({ class => 'Koha::Holds', value => { borrowernumber => $patron->borrowernumber } });
473     my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->borrowernumber } });
474     my $private_list = Koha::Virtualshelf->new({
475         shelfname => "private",
476         owner => $patron->borrowernumber,
477         public => 0,
478     })->store;
479     my $public_list = Koha::Virtualshelf->new({
480         shelfname => "public",
481         owner => $patron->borrowernumber,
482         public => 1,
483     })->store;
484     my $list_to_share = Koha::Virtualshelf->new({
485         shelfname => "shared",
486         owner => $patron->borrowernumber,
487         public => 0,
488     })->store;
489
490     $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
491     $list_to_share->share("valid key")->accept( "valid key", $staff_patron->borrowernumber ); # this share should be removed at deletion too
492     my $deleted = $patron->delete;
493     is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' );
494     ok( $patron->borrowernumber, 'Still have the deleted borrowernumber' );
495
496     is( Koha::Patrons->find( $patron->borrowernumber ), undef, 'Koha::Patron->delete should have deleted the patron' );
497
498     is (Koha::Old::Holds->search({ reserve_id => $hold->reserve_id })->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| );
499
500     is( Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| );
501
502     my $transferred_lists = Koha::Virtualshelves->search({ owner => $staff_patron->borrowernumber })->count;
503     is( $transferred_lists, 2, 'Public and shared lists should stay in database under a different owner with a unique name, while private lists delete, with ListOwnershipPatronDeletion set to Transfer');
504     is( Koha::Virtualshelfshares->search({ borrowernumber => $staff_patron->borrowernumber })->count, 0, "New owner of list should have shares removed" );
505     is( Koha::Virtualshelfshares->search({ borrowernumber => $patron_for_sharing->borrowernumber })->count, 1, "But the other share is still there" );
506     is( Koha::Virtualshelves->search({ owner => $patron->borrowernumber })->count, 0, q|Koha::Patron->delete should have deleted patron's lists/removed their ownership| );
507
508     is( Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| );
509
510     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $patron->borrowernumber } )->count;
511     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' );
512
513     # Test deletion with designated fallback owner
514     my $designated_owner = $builder->build_object({ class => 'Koha::Patrons' });
515     t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $designated_owner->id );
516     $patron = $builder->build_object({ class => 'Koha::Patrons' });
517     $private_list = Koha::Virtualshelf->new({ shelfname => "PR1", owner => $patron->id })->store;
518     $public_list = Koha::Virtualshelf->new({ shelfname => "PU1", public => 1, owner => $patron->id })->store;
519     $list_to_share = Koha::Virtualshelf->new({ shelfname => "SH1", owner => $patron->id })->store;
520     $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->id );
521     $patron->delete;
522     is( Koha::Virtualshelves->find( $private_list->id ), undef, 'Private list gone' );
523     is( $public_list->discard_changes->get_column('owner'), $designated_owner->id, 'Public list transferred' );
524     is( $list_to_share->discard_changes->get_column('owner'), $designated_owner->id, 'Shared list transferred' );
525
526     # Finally test deleting lists
527     t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'delete' );
528     Koha::Virtualshelves->delete;
529     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
530     my $private_list2 = Koha::Virtualshelf->new({
531          shelfname => "private",
532          owner => $patron2->borrowernumber,
533          public => 0,
534     })->store;
535     my $public_list2 = Koha::Virtualshelf->new({
536         shelfname => "public",
537         owner => $patron2->borrowernumber,
538         public => 1,
539     })->store;
540     my $list_to_share2 = Koha::Virtualshelf->new({
541         shelfname => "shared",
542         owner => $patron2->borrowernumber,
543         public => 0,
544     })->store;
545     $list_to_share2->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber );
546
547     # Delete patron2, check if shelves and shares are now empty
548     $patron2->delete;
549     is( Koha::Virtualshelves->count, 0, 'All lists should be gone now' );
550     is( Koha::Virtualshelfshares->count, 0, 'All shares should be gone too' );
551 };
552
553 subtest 'Koha::Patrons->delete' => sub {
554     plan tests => 3;
555
556     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
557     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
558     my $id1 = $patron1->borrowernumber;
559     my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
560     is( $set->count, 2, 'Two patrons found as expected' );
561     is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' );
562     my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}});
563     is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' );
564
565     # See other tests in t/db_dependent/Koha/Objects.t
566 };
567
568 subtest 'add_enrolment_fee_if_needed' => sub {
569     plan tests => 4;
570
571     my $enrolmentfees = { K  => 5, J => 10, YA => 20 };
572     foreach( keys %{$enrolmentfees} ) {
573         ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store;
574     }
575     my $enrolmentfee_K  = $enrolmentfees->{K};
576     my $enrolmentfee_J  = $enrolmentfees->{J};
577     my $enrolmentfee_YA = $enrolmentfees->{YA};
578
579     my %borrower_data = (
580         firstname    => 'my firstname',
581         surname      => 'my surname',
582         categorycode => 'K',
583         branchcode   => $library->{branchcode},
584     );
585
586     my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber;
587     $borrower_data{borrowernumber} = $borrowernumber;
588
589     my $patron = Koha::Patrons->find( $borrowernumber );
590     my $total = $patron->account->balance;
591     is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" );
592
593     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 );
594     $borrower_data{categorycode} = 'J';
595     $patron->set(\%borrower_data)->store;
596     $total = $patron->account->balance;
597     is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " );
598
599     $borrower_data{categorycode} = 'K';
600     $patron->set(\%borrower_data)->store;
601     t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 );
602
603     $borrower_data{categorycode} = 'J';
604     $patron->set(\%borrower_data)->store;
605     $total = $patron->account->balance;
606     is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) );
607
608     # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed
609     $patron->categorycode('YA')->store;
610     $total = $patron->account->balance;
611     is( int($total),
612         int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA),
613         "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA )
614     );
615
616     $patron->delete;
617 };
618
619 subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub {
620     plan tests => 17;
621
622     my $library = $builder->build( { source => 'Branch' } );
623     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
624     my $item_1 = $builder->build_sample_item(
625         {
626             library      => $library->{branchcode},
627             biblionumber => $biblionumber_1,
628         }
629     );
630     my $item_2 = $builder->build_sample_item(
631         {
632             library      => $library->{branchcode},
633             biblionumber => $biblionumber_1,
634         }
635     );
636     my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
637     my $item_3 = $builder->build_sample_item(
638         {
639             library      => $library->{branchcode},
640             biblionumber => $biblionumber_2,
641         }
642     );
643     my $patron = $builder->build(
644         {
645             source => 'Borrower',
646             value  => { branchcode => $library->{branchcode} }
647         }
648     );
649
650     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
651     my $checkouts = $patron->checkouts;
652     is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' );
653     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
654     my $pending_checkouts = $patron->pending_checkouts;
655     is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' );
656     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
657     my $old_checkouts = $patron->old_checkouts;
658     is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' );
659     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
660
661     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
662
663     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
664     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
665     AddIssue( $patron, $item_3->barcode );
666
667     $checkouts = $patron->checkouts;
668     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
669     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
670     $pending_checkouts = $patron->pending_checkouts;
671     is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
672     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
673
674     my $first_checkout = $pending_checkouts->next;
675     is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
676
677     my $overdues = $patron->overdues;
678     is( $overdues->count, 2, 'Patron should have 2 overdues');
679     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' );
680     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
681     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
682
683
684     C4::Circulation::AddReturn( $item_1->barcode );
685     C4::Circulation::AddReturn( $item_2->barcode );
686     $old_checkouts = $patron->old_checkouts;
687     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
688     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
689
690     # Clean stuffs
691     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
692     $patron->delete;
693 };
694
695 subtest 'get_routing_lists' => sub {
696     plan tests => 5;
697
698     my $biblio = Koha::Biblio->new()->store();
699     my $subscription = Koha::Subscription->new({
700         biblionumber => $biblio->biblionumber,
701         }
702     )->store;
703
704     my $patron = $builder->build( { source => 'Borrower' } );
705     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
706
707     is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
708
709     my $routinglist_count = Koha::Subscription::Routinglists->count;
710     my $routinglist = Koha::Subscription::Routinglist->new({
711         borrowernumber   => $patron->borrowernumber,
712         ranking          => 5,
713         subscriptionid   => $subscription->subscriptionid
714     })->store;
715
716     is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
717
718     my $routinglists = $patron->get_routing_lists;
719     is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
720     is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
721
722     my $subscription2 = Koha::Subscription->new({
723         biblionumber => $biblio->biblionumber,
724         }
725     )->store;
726     my $routinglist2 = Koha::Subscription::Routinglist->new({
727         borrowernumber   => $patron->borrowernumber,
728         ranking          => 1,
729         subscriptionid   => $subscription2->subscriptionid
730     })->store;
731
732     is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
733
734     $patron->delete; # Clean up for later tests
735
736 };
737
738 subtest 'get_age' => sub {
739     plan tests => 31;
740
741     # Following tests implicitly assume timezone UTC
742     delete $C4::Context::context->{tz};
743     local %ENV;
744     $ENV{TZ} = 'Etc/UTC';
745
746     my $patron = $builder->build( { source => 'Borrower' } );
747     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
748
749     my @dates = (
750         {
751             today            => '2020-02-28',
752             has_12           => { date => '2007-08-27', expected_age => 12 },
753             almost_18        => { date => '2002-03-01', expected_age => 17 },
754             has_18_today     => { date => '2002-02-28', expected_age => 18 },
755             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
756             almost_16        => { date => '2004-02-29', expected_age => 15 },
757             has_16_today     => { date => '2004-02-28', expected_age => 16 },
758             had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
759             new_born         => { date => '2020-01-27', expected_age => 0 },
760         },
761         {
762             today            => '2020-02-29',
763             has_12           => { date => '2007-08-27', expected_age => 12 },
764             almost_18        => { date => '2002-03-01', expected_age => 17 },
765             has_18_today     => { date => '2002-02-28', expected_age => 18 },
766             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
767             almost_16        => { date => '2004-03-01', expected_age => 15 },
768             has_16_today     => { date => '2004-02-29', expected_age => 16 },
769             had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
770             new_born         => { date => '2020-01-27', expected_age => 0 },
771         },
772         {
773             today            => '2020-03-01',
774             has_12           => { date => '2007-08-27', expected_age => 12 },
775             almost_18        => { date => '2002-03-02', expected_age => 17 },
776             has_18_today     => { date => '2002-03-01', expected_age => 18 },
777             had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
778             almost_16        => { date => '2004-03-02', expected_age => 15 },
779             has_16_today     => { date => '2004-03-01', expected_age => 16 },
780             had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
781         },
782         {
783             today            => '2019-01-31',
784             has_12           => { date => '2006-08-27', expected_age => 12 },
785             almost_18        => { date => '2001-02-01', expected_age => 17 },
786             has_18_today     => { date => '2001-01-31', expected_age => 18 },
787             had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
788             almost_16        => { date => '2003-02-01', expected_age => 15 },
789             has_16_today     => { date => '2003-01-31', expected_age => 16 },
790             had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
791         },
792     );
793
794     $patron->dateofbirth( undef );
795     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
796
797     for my $date ( @dates ) {
798
799         my $dt = dt_from_string($date->{today});
800
801         Time::Fake->offset( $dt->epoch );
802
803         for my $k ( keys %$date ) {
804             next if $k eq 'today';
805
806             my $dob = $date->{$k};
807             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
808             is(
809                 $patron->get_age,
810                 $dob->{expected_age},
811                 sprintf(
812                     "Today=%s, dob=%s, should be %d",
813                     $date->{today}, $dob->{date}, $dob->{expected_age}
814                 )
815             );
816         }
817
818         Time::Fake->reset;
819
820     }
821
822     $patron->delete;
823
824     # Remove timezone change
825     delete $C4::Context::context->{tz};
826 };
827
828 subtest 'is_valid_age' => sub {
829     plan tests => 10;
830
831     # Following tests implicitly assume timezone UTC
832     delete $C4::Context::context->{tz};
833     local %ENV;
834     $ENV{TZ} = 'Etc/UTC';
835
836     my $dt = dt_from_string('2020-02-28');
837
838     Time::Fake->offset( $dt->epoch );
839
840     my $category = $builder->build({
841         source => 'Category',
842         value => {
843             categorycode        => 'AGE_5_10',
844             dateofbirthrequired => 5,
845             upperagelimit       => 10
846         }
847     });
848     $category = Koha::Patron::Categories->find( $category->{categorycode} );
849
850     my $patron = $builder->build({
851         source => 'Borrower',
852         value => {
853             categorycode        => $category->categorycode
854         }
855     });
856     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
857
858
859     $patron->dateofbirth( undef );
860     is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
861
862     my @dates = (
863         {
864             today => '2020-02-28',
865             add_m12_m6_m1 =>
866               { date => '2007-08-27', expected_age => 12, valid => 0 },
867             add_m3_m6_m1 =>
868               { date => '2016-08-27', expected_age => 3, valid => 0 },
869             add_m7_m6_m1 =>
870               { date => '2013-02-28', expected_age => 7, valid => 1 },
871             add_m5_0_0 =>
872               { date => '2015-02-28', expected_age => 5, valid => 1 },
873             add_m5_0_p1 =>
874               { date => '2015-03-01', expected_age => 4, valid => 0 },
875             add_m5_0_m1 =>
876               { date => '2015-02-27', expected_age => 5, valid => 1 },
877             add_m11_0_0 =>
878               { date => '2009-02-28', expected_age => 11, valid => 0 },
879             add_m11_0_p1 =>
880               { date => '2009-03-01', expected_age => 10, valid => 1 },
881             add_m11_0_m1 =>
882               { date => '2009-02-27', expected_age => 11, valid => 0 },
883         },
884     );
885
886     for my $date ( @dates ) {
887
888         my $dt = dt_from_string($date->{today});
889
890         Time::Fake->offset( $dt->epoch );
891
892         for my $k ( sort keys %$date ) {
893             next if $k eq 'today';
894
895             my $dob = $date->{$k};
896             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
897             is(
898                 $patron->is_valid_age,
899                 $dob->{valid},
900                 sprintf(
901                     "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
902                     $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
903                 )
904             );
905         }
906
907         Time::Fake->reset;
908
909     }
910
911     $patron->delete;
912     $category->delete;
913
914     # Remove timezone change
915     delete $C4::Context::context->{tz};
916 };
917
918 subtest 'account' => sub {
919     plan tests => 1;
920
921     my $patron = $builder->build({source => 'Borrower'});
922
923     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
924     my $account = $patron->account;
925     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
926
927     $patron->delete;
928 };
929
930 subtest 'search_upcoming_membership_expires' => sub {
931     plan tests => 9;
932
933     my $expiry_days = 15;
934     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
935     my $nb_of_days_before = 1;
936     my $nb_of_days_after = 2;
937
938     my $builder = t::lib::TestBuilder->new();
939
940     my $library = $builder->build({ source => 'Branch' });
941
942     # before we add borrowers to this branch, add the expires we have now
943     # note that this pertains to the current mocked setting of the pref
944     # for this reason we add the new branchcode to most of the tests
945     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
946
947     my $patron_1 = $builder->build({
948         source => 'Borrower',
949         value  => {
950             branchcode              => $library->{branchcode},
951             dateexpiry              => dt_from_string->add( days => $expiry_days )
952         },
953     });
954
955     my $patron_2 = $builder->build({
956         source => 'Borrower',
957         value  => {
958             branchcode              => $library->{branchcode},
959             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
960         },
961     });
962
963     my $patron_3 = $builder->build({
964         source => 'Borrower',
965         value  => {
966             branchcode              => $library->{branchcode},
967             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
968         },
969     });
970
971     # Test without extra parameters
972     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
973     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
974
975     # Test with branch
976     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
977     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
978     my $expired = $upcoming_mem_expires->next;
979     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
980     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
981     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
982
983     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
984     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
985     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
986
987     # Test MembershipExpiryDaysNotice == undef
988     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
989     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
990     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
991
992     # Test the before parameter
993     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
994     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
995     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
996     # Test after parameter also
997     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
998     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
999     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
1000 };
1001
1002 subtest 'holds and old_holds' => sub {
1003     plan tests => 6;
1004
1005     my $library = $builder->build( { source => 'Branch' } );
1006     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1007     my $item_1 = $builder->build_sample_item(
1008         {
1009             library      => $library->{branchcode},
1010             biblionumber => $biblionumber_1,
1011         }
1012     );
1013     my $item_2 = $builder->build_sample_item(
1014         {
1015             library      => $library->{branchcode},
1016             biblionumber => $biblionumber_1,
1017         }
1018     );
1019     my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
1020     my $item_3 = $builder->build_sample_item(
1021         {
1022             library      => $library->{branchcode},
1023             biblionumber => $biblionumber_2,
1024         }
1025     );
1026
1027     my $patron = $builder->build(
1028         {
1029             source => 'Borrower',
1030             value  => { branchcode => $library->{branchcode} }
1031         }
1032     );
1033
1034     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1035     my $holds = $patron->holds;
1036     is( ref($holds), 'Koha::Holds',
1037         'Koha::Patron->holds should return a Koha::Holds objects' );
1038     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1039
1040     C4::Reserves::AddReserve(
1041         {
1042             branchcode     => $library->{branchcode},
1043             borrowernumber => $patron->borrowernumber,
1044             biblionumber   => $biblionumber_1
1045         }
1046     );
1047     # In the future
1048     C4::Reserves::AddReserve(
1049         {
1050             branchcode      => $library->{branchcode},
1051             borrowernumber  => $patron->borrowernumber,
1052             biblionumber    => $biblionumber_2,
1053             expiration_date => dt_from_string->add( days => 2 )
1054         }
1055     );
1056
1057     $holds = $patron->holds;
1058     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1059
1060     my $old_holds = $patron->old_holds;
1061     is( ref($old_holds), 'Koha::Old::Holds',
1062         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1063     is( $old_holds->count, 0, 'There should not be any old holds yet');
1064
1065     my $hold = $holds->next;
1066     $hold->cancel;
1067
1068     $old_holds = $patron->old_holds;
1069     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
1070
1071     $old_holds->delete;
1072     $holds->delete;
1073     $patron->delete;
1074 };
1075
1076 subtest 'search_patrons_to_anonymise' => sub {
1077
1078     plan tests => 5;
1079
1080     # TODO create a subroutine in t::lib::Mocks
1081     my $branch = $builder->build({ source => 'Branch' });
1082     my $userenv_patron = $builder->build_object({
1083         class  => 'Koha::Patrons',
1084         value  => { branchcode => $branch->{branchcode}, flags => 0 },
1085     });
1086     t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1087
1088     my $anonymous = $builder->build( { source => 'Borrower', }, );
1089
1090     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1091
1092     subtest 'Anonymous Patron should be undeleteable' => sub {
1093         plan tests => 2;
1094
1095         my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1096         throws_ok { $anonymous_patron->delete(); }
1097             'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1098             'Attempt to delete anonymous patron throws exception.';
1099         $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1100         is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1101     };
1102
1103     subtest 'patron privacy is 1 (default)' => sub {
1104         plan tests => 9;
1105
1106         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1107         my $patron = $builder->build(
1108             {   source => 'Borrower',
1109                 value  => { privacy => 1, }
1110             }
1111         );
1112         my $item_1 = $builder->build_sample_item;
1113         my $issue_1 = $builder->build(
1114             {   source => 'Issue',
1115                 value  => {
1116                     borrowernumber => $patron->{borrowernumber},
1117                     itemnumber     => $item_1->itemnumber,
1118                 },
1119             }
1120         );
1121         my $item_2 = $builder->build_sample_item;
1122         my $issue_2 = $builder->build(
1123             {   source => 'Issue',
1124                 value  => {
1125                     borrowernumber => $patron->{borrowernumber},
1126                     itemnumber     => $item_2->itemnumber,
1127                 },
1128             }
1129         );
1130
1131         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1132         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1133         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1134
1135         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1136         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1137
1138         my $rows_affected = Koha::Old::Checkouts->search(
1139             {
1140                 borrowernumber => [
1141                     Koha::Patrons->search_patrons_to_anonymise(
1142                         { before => '2011-11-12' }
1143                     )->get_column('borrowernumber')
1144                 ],
1145                 returndate => { '<' => '2011-10-11', }
1146             }
1147         )->anonymize;
1148         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1149
1150         $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1151         is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1152
1153         my $dbh = C4::Context->dbh;
1154         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1155         $sth->execute($item_1->itemnumber);
1156         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1157         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1158         $sth->execute($item_2->itemnumber);
1159         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1160         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1161
1162         $rows_affected = Koha::Old::Checkouts->search(
1163             {
1164                 borrowernumber => [
1165                     Koha::Patrons->search_patrons_to_anonymise(
1166                         { before => '2011-11-12' }
1167                     )->get_column('borrowernumber')
1168                 ],
1169                 returndate => { '<' => '2011-11-12', }
1170             }
1171         )->anonymize;
1172         $sth->execute($item_2->itemnumber);
1173         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1174         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1175
1176         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1177         $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1178         $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1179         $rows_affected = Koha::Old::Checkouts->search(
1180             {
1181                 borrowernumber => [
1182                     Koha::Patrons->search_patrons_to_anonymise->get_column(
1183                         'borrowernumber')
1184                 ]
1185             }
1186         )->anonymize;
1187         $sth->execute($item_1->itemnumber);
1188         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1189         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1190         $sth->execute($item_2->itemnumber);
1191         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1192         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1193
1194         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1195     };
1196
1197     subtest 'patron privacy is 0 (forever)' => sub {
1198         plan tests => 2;
1199
1200         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1201         my $patron = $builder->build(
1202             {   source => 'Borrower',
1203                 value  => { privacy => 0, }
1204             }
1205         );
1206         my $item = $builder->build_sample_item;
1207         my $issue = $builder->build(
1208             {   source => 'Issue',
1209                 value  => {
1210                     borrowernumber => $patron->{borrowernumber},
1211                     itemnumber     => $item->itemnumber,
1212                 },
1213             }
1214         );
1215
1216         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1217         is( $returned, 1, 'The item should have been returned' );
1218
1219         my $dbh = C4::Context->dbh;
1220         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1221             SELECT borrowernumber FROM old_issues where itemnumber = ?
1222         |, undef, $item->itemnumber);
1223         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1224         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1225     };
1226
1227     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1228
1229     subtest 'AnonymousPatron is not defined' => sub {
1230
1231         plan tests => 2;
1232
1233         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1234         my $patron = $builder->build(
1235             {   source => 'Borrower',
1236                 value  => { privacy => 1, }
1237             }
1238         );
1239         my $item = $builder->build_sample_item;
1240         my $issue = $builder->build(
1241             {   source => 'Issue',
1242                 value  => {
1243                     borrowernumber => $patron->{borrowernumber},
1244                     itemnumber     => $item->itemnumber,
1245                 },
1246             }
1247         );
1248
1249         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1250         is( $returned, 1, 'The item should have been returned' );
1251         my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1252         ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' );
1253
1254         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1255     };
1256
1257     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1258         plan tests => 1;
1259         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1260         my $patron = $builder->build(
1261             {   source => 'Borrower',
1262                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1263             }
1264         );
1265         my $item = $builder->build_sample_item;
1266         my $issue = $builder->build(
1267             {   source => 'Issue',
1268                 value  => {
1269                     borrowernumber => $patron->{borrowernumber},
1270                     itemnumber     => $item->itemnumber,
1271                 },
1272             }
1273         );
1274
1275         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1276         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1277         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1278     };
1279
1280     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1281     $userenv_patron->delete;
1282
1283     # Reset IndependentBranches for further tests
1284     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1285 };
1286
1287 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1288     plan tests => 3;
1289
1290     # group1
1291     #   + library_11
1292     #   + library_12
1293     # group2
1294     #   + library21
1295     $nb_of_patrons = Koha::Patrons->search->count;
1296     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1297     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1298     my $library_11 = $builder->build( { source => 'Branch' } );
1299     my $library_12 = $builder->build( { source => 'Branch' } );
1300     my $library_21 = $builder->build( { source => 'Branch' } );
1301     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1302     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1303     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1304     Koha::Library::Group->new(
1305         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1306     Koha::Library::Group->new(
1307         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1308     Koha::Library::Group->new(
1309         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1310
1311     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1312     # 2 patrons from library_11 (group1)
1313     # patron_11_1 see patron's infos from outside its group
1314     # Setting flags => undef to not be considered as superlibrarian
1315     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1316     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1317     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1318     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1319     # patron_11_2 can only see patron's info from its group
1320     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1321     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1322     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1323     # 1 patron from library_12 (group1)
1324     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1325     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1326     # 1 patron from library_21 (group2) can only see patron's info from its group
1327     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1328     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1329     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1330
1331     # Pfiou, we can start now!
1332     subtest 'libraries_where_can_see_patrons' => sub {
1333         plan tests => 3;
1334
1335         my @branchcodes;
1336
1337         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1338         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1339         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1340
1341         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1342         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1343         is_deeply( \@branchcodes, [ sort ( $library_11->branchcode, $library_12->branchcode ) ], q|patron_11_2 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1344
1345         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1346         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1347         is_deeply( \@branchcodes, [$library_21->branchcode], q|patron_21 has not view_borrower_infos_from_any_libraries => Can only see patron's from its group| );
1348     };
1349     subtest 'can_see_patron_infos' => sub {
1350         plan tests => 6;
1351
1352         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1353         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1354         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1355         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1356
1357         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1358         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1359         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1360         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1361     };
1362     subtest 'search_limited' => sub {
1363         plan tests => 6;
1364
1365         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1366         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1367         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1368         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1369
1370         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1371         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1372         is( Koha::Patrons->search_limited->count, 3, 'patron_12_1 is not allowed to see patrons from other groups, only patron_11_1, patron_11_2 and patron_12' );
1373
1374         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1375         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1376         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1377     };
1378     $patron_11_1->delete;
1379     $patron_11_2->delete;
1380     $patron_12->delete;
1381     $patron_21->delete;
1382 };
1383
1384 subtest 'account_locked' => sub {
1385     plan tests => 13;
1386     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1387     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1388     for my $value ( undef, '', 0 ) {
1389         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1390         $patron->login_attempts(0)->store;
1391         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1392         $patron->login_attempts(1)->store;
1393         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1394         $patron->login_attempts(-1)->store;
1395         is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1396     }
1397
1398     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1399     $patron->login_attempts(2)->store;
1400     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1401     $patron->login_attempts(3)->store;
1402     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1403     $patron->login_attempts(4)->store;
1404     is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1405     $patron->login_attempts(-1)->store;
1406     is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1407
1408     $patron->delete;
1409 };
1410
1411 subtest 'is_child | is_adult' => sub {
1412     plan tests => 8;
1413     my $category = $builder->build_object(
1414         {
1415             class => 'Koha::Patron::Categories',
1416             value => { category_type => 'A' }
1417         }
1418     );
1419     my $patron_adult = $builder->build_object(
1420         {
1421             class => 'Koha::Patrons',
1422             value => { categorycode => $category->categorycode }
1423         }
1424     );
1425     $category = $builder->build_object(
1426         {
1427             class => 'Koha::Patron::Categories',
1428             value => { category_type => 'I' }
1429         }
1430     );
1431     my $patron_adult_i = $builder->build_object(
1432         {
1433             class => 'Koha::Patrons',
1434             value => { categorycode => $category->categorycode }
1435         }
1436     );
1437     $category = $builder->build_object(
1438         {
1439             class => 'Koha::Patron::Categories',
1440             value => { category_type => 'C' }
1441         }
1442     );
1443     my $patron_child = $builder->build_object(
1444         {
1445             class => 'Koha::Patrons',
1446             value => { categorycode => $category->categorycode }
1447         }
1448     );
1449     $category = $builder->build_object(
1450         {
1451             class => 'Koha::Patron::Categories',
1452             value => { category_type => 'O' }
1453         }
1454     );
1455     my $patron_other = $builder->build_object(
1456         {
1457             class => 'Koha::Patrons',
1458             value => { categorycode => $category->categorycode }
1459         }
1460     );
1461     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1462     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1463     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1464     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1465
1466     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1467     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1468     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1469     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1470
1471     # Clean up
1472     $patron_adult->delete;
1473     $patron_adult_i->delete;
1474     $patron_child->delete;
1475     $patron_other->delete;
1476 };
1477
1478 subtest 'overdues' => sub {
1479     plan tests => 7;
1480
1481     my $library = $builder->build( { source => 'Branch' } );
1482     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1483     my $item_1 = $builder->build_sample_item(
1484         {
1485             library      => $library->{branchcode},
1486             biblionumber => $biblionumber_1,
1487         }
1488     );
1489     my $item_2 = $builder->build_sample_item(
1490         {
1491             library      => $library->{branchcode},
1492             biblionumber => $biblionumber_1,
1493         }
1494     );
1495     my $item_3 = $builder->build_sample_item(
1496         {
1497             library      => $library->{branchcode},
1498         }
1499     );
1500
1501     my $patron = $builder->build(
1502         {
1503             source => 'Borrower',
1504             value  => { branchcode => $library->{branchcode} }
1505         }
1506     );
1507
1508     t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1509
1510     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1511
1512     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1513     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1514     AddIssue( $patron, $item_3->barcode );
1515
1516     my $overdues = $patron->overdues;
1517     is( $overdues->count, 2, 'Patron should have 2 overdues');
1518     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1519     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1520
1521     my $o = $overdues->reset->next;
1522     my $unblessed_overdue = $o->unblessed_all_relateds;
1523     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1524     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1525     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1526     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1527
1528     # Clean stuffs
1529     $patron->checkouts->delete;
1530     $patron->delete;
1531 };
1532
1533 subtest 'userid_is_valid' => sub {
1534     plan tests => 9;
1535
1536     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1537     my $patron_category = $builder->build_object(
1538         {
1539             class => 'Koha::Patron::Categories',
1540             value => { category_type => 'P', enrolmentfee => 0 }
1541         }
1542     );
1543     my %data = (
1544         cardnumber   => "123456789",
1545         firstname    => "Tomasito",
1546         surname      => "None",
1547         categorycode => $patron_category->categorycode,
1548         branchcode   => $library->branchcode,
1549     );
1550
1551     my $expected_userid_patron_1 = 'tomasito.none';
1552     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1553     my $patron_1       = Koha::Patrons->find($borrowernumber);
1554     is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1555     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1556
1557     $patron_1->userid( 'tomasito.non' );
1558     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1559         1, 'recently created userid -> unique (borrowernumber passed)' );
1560
1561     $patron_1->userid( 'tomasitoxxx' );
1562     is( $patron_1->has_valid_userid,
1563         1, 'non-existent userid -> unique (borrowernumber passed)' );
1564     $patron_1->discard_changes; # We compare with the original userid later
1565
1566     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1567     is( $patron_not_in_storage->has_valid_userid,
1568         0, 'userid exists for another patron, patron is not in storage yet' );
1569
1570     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1571     is( $patron_not_in_storage->has_valid_userid,
1572         1, 'non-existent userid, patron is not in storage yet' );
1573
1574     # Regression tests for BZ12226
1575     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1576     is( $db_patron->has_valid_userid,
1577         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1578
1579     # Add a new borrower with the same userid but different cardnumber
1580     $data{cardnumber} = "987654321";
1581     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1582     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1583     $patron_2->userid($patron_1->userid);
1584     is( $patron_2->has_valid_userid,
1585         0, 'The userid is already in used, it cannot be used for another patron' );
1586
1587     my $new_userid = 'a_user_id';
1588     $data{cardnumber} = "234567890";
1589     $data{userid}     = 'a_user_id';
1590     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1591     my $patron_3 = Koha::Patrons->find($borrowernumber);
1592     is( $patron_3->userid, $new_userid,
1593         'Koha::Patron->store should insert the given userid' );
1594
1595     # Cleanup
1596     $patron_1->delete;
1597     $patron_2->delete;
1598     $patron_3->delete;
1599 };
1600
1601 $nb_of_patrons = Koha::Patrons->search->count;
1602 $retrieved_patron_1->delete;
1603 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1604
1605 subtest 'BorrowersLog tests' => sub {
1606     plan tests => 4;
1607
1608     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1609     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1610
1611     my $cardnumber = $patron->cardnumber;
1612     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1613     $patron->store;
1614
1615     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1616     my $log_info = from_json( $logs[0]->info );
1617     is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1618     is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1619     is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1620
1621     t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' );
1622     $patron->update_lastseen('connection');
1623     @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1624     is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivityTriggers we should not spam the logs');
1625 };
1626 $schema->storage->txn_rollback;
1627
1628 subtest 'Test Koha::Patrons::merge' => sub {
1629     plan tests => 110;
1630
1631     my $schema = Koha::Database->new()->schema();
1632
1633     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1634
1635     $schema->storage->txn_begin;
1636
1637     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1638     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1639     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1640
1641     my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1642     my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1643     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1644
1645     while (my ($r, $field) = each(%$resultsets)) {
1646         $builder->build({ source => $r, value => { $field => $keeper->id } });
1647         $builder->build({ source => $r, value => { $field => $loser_1 } });
1648         $builder->build({ source => $r, value => { $field => $loser_2 } });
1649
1650         my $keeper_rs =
1651           $schema->resultset($r)->search( { $field => $keeper->id } );
1652         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1653
1654         my $loser_1_rs =
1655           $schema->resultset($r)->search( { $field => $loser_1 } );
1656         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1657
1658         my $loser_2_rs =
1659           $schema->resultset($r)->search( { $field => $loser_2 } );
1660         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1661     }
1662
1663     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1664
1665     while (my ($r, $field) = each(%$resultsets)) {
1666         my $keeper_rs =
1667           $schema->resultset($r)->search( {$field => $keeper->id } );
1668         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1669     }
1670
1671     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1672     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1673     is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1674
1675     $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1676     $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1677     is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1678     is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1679
1680     subtest 'extended attributes' => sub {
1681         plan tests => 8;
1682
1683         my $keep_patron =
1684           $builder->build_object( { class => 'Koha::Patrons' } );
1685         my $merge_patron =
1686           $builder->build_object( { class => 'Koha::Patrons' } );
1687
1688         my $attribute_type_normal_1 = $builder->build_object(
1689             {
1690                 class => 'Koha::Patron::Attribute::Types',
1691                 value => { repeatable => 0, unique_id => 0 }
1692             }
1693         );
1694         my $attribute_type_normal_2 = $builder->build_object(
1695             {
1696                 class => 'Koha::Patron::Attribute::Types',
1697                 value => { repeatable => 0, unique_id => 0 }
1698             }
1699         );
1700
1701         my $attribute_type_repeatable = $builder->build_object(
1702             {
1703                 class => 'Koha::Patron::Attribute::Types',
1704                 value => { repeatable => 1, unique_id => 0 }
1705             }
1706         );
1707
1708         my $attr_keep = [
1709             {
1710                 code      => $attribute_type_normal_1->code,
1711                 attribute => 'from attr 1'
1712             },
1713             {
1714                 code      => $attribute_type_repeatable->code,
1715                 attribute => 'from attr repeatable'
1716             }
1717         ];
1718
1719         my $attr_merge = [
1720             {
1721                 code      => $attribute_type_normal_2->code,
1722                 attribute => 'to attr 2'
1723             },
1724             {
1725                 code      => $attribute_type_repeatable->code,
1726                 attribute => 'to attr repeatable'
1727             },
1728         ];
1729
1730         $keep_patron->extended_attributes($attr_keep);
1731         $merge_patron->extended_attributes($attr_merge);
1732
1733         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1734         my $merged_attributes = $keep_patron->extended_attributes;
1735         is( $merged_attributes->count, 4 );
1736
1737         sub compare_attributes {
1738             my ( $got, $expected, $code ) = @_;
1739
1740             is_deeply(
1741                 [
1742                     sort $got->search( { code => $code } )
1743                       ->get_column('attribute')
1744                 ],
1745                 $expected
1746             );
1747         }
1748         compare_attributes(
1749             $merged_attributes,
1750             ['from attr 1'],
1751             $attribute_type_normal_1->code
1752         );
1753         compare_attributes(
1754             $merged_attributes,
1755             ['to attr 2'],
1756             $attribute_type_normal_2->code
1757         );
1758         compare_attributes(
1759             $merged_attributes,
1760             [ 'from attr repeatable', 'to attr repeatable' ],
1761             $attribute_type_repeatable->code
1762         );
1763
1764         # Cleanup
1765         $keep_patron->delete;
1766         $merge_patron->delete;
1767
1768         # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep
1769         $keep_patron =
1770           $builder->build_object( { class => 'Koha::Patrons' } );
1771         $merge_patron =
1772           $builder->build_object( { class => 'Koha::Patrons' } );
1773
1774         $keep_patron->extended_attributes($attr_keep);
1775         $merge_patron->extended_attributes(
1776             [
1777                 @$attr_merge,
1778                 {
1779                     code      => $attribute_type_normal_1->code,
1780                     attribute => 'yet another attribute for non-repeatable'
1781                 }
1782             ]
1783         );
1784
1785         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1786         $merged_attributes = $keep_patron->extended_attributes;
1787         is( $merged_attributes->count, 4 );
1788         compare_attributes(
1789             $merged_attributes,
1790             ['from attr 1'],
1791             $attribute_type_normal_1->code
1792         );
1793         compare_attributes(
1794             $merged_attributes,
1795             ['to attr 2'],
1796             $attribute_type_normal_2->code
1797         );
1798         compare_attributes(
1799             $merged_attributes,
1800             [ 'from attr repeatable', 'to attr repeatable' ],
1801             $attribute_type_repeatable->code
1802         );
1803
1804     };
1805
1806     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1807     $schema->storage->txn_rollback;
1808 };
1809
1810 subtest '->store' => sub {
1811     plan tests => 11;
1812     my $schema = Koha::Database->new->schema;
1813     $schema->storage->txn_begin;
1814
1815     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1816     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1817
1818     throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1819         'Koha::Exceptions::Patron::InvalidUserid',
1820         'Koha::Patron->store raises an exception on duplicate ID';
1821
1822     # Clear userid and check regeneration
1823     $patron_2->userid(undef)->store;
1824     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1825     $patron_2->userid('')->store;
1826     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1827     $patron_2->userid(0)->store;
1828     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1829
1830     # Test password
1831     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1832     my $password = 'password';
1833     $patron_1->set_password({ password => $password });
1834     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1835     my $digest = $patron_1->password;
1836     $patron_1->surname('xxx')->store;
1837     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1838
1839     # Test uppercasesurnames
1840     t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1841     my $surname = lc $patron_1->surname;
1842     $patron_1->surname($surname)->store;
1843     isnt( $patron_1->surname, $surname,
1844         'Surname converts to uppercase on store.');
1845     t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1846     $patron_1->surname($surname)->store;
1847     is( $patron_1->surname, $surname,
1848         'Surname remains unchanged on store.');
1849
1850     # Test relationship
1851     $patron_1->relationship("")->store;
1852     is( $patron_1->relationship, undef, );
1853
1854     $schema->storage->txn_rollback;
1855
1856     subtest 'skip updated_on for BorrowersLog' => sub {
1857         plan tests => 1;
1858         $schema->storage->txn_begin;
1859         t::lib::Mocks::mock_preference('BorrowersLog', 1);
1860         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1861         $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1862         my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1863         is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1864         $schema->storage->txn_rollback;
1865     };
1866
1867     subtest 'create user usage' => sub {
1868         plan tests => 1;
1869         $schema->storage->txn_begin;
1870
1871         my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1872         my $patron_category = $builder->build_object(
1873             {
1874                 class => 'Koha::Patron::Categories',
1875                 value => { category_type => 'P', enrolmentfee => 0 }
1876             }
1877         );
1878         my %data = (
1879             cardnumber   => "123456789",
1880             firstname    => "Tômàsító",
1881             surname      => "Ñoné",
1882             password     => 'Funk3y',
1883             categorycode => $patron_category->categorycode,
1884             branchcode   => $library->branchcode,
1885         );
1886
1887         # Enable notifying patrons of password changes for these tests
1888         t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1889         my $new_patron     = Koha::Patron->new( \%data )->store();
1890         my $queued_notices = Koha::Notice::Messages->search(
1891             { borrowernumber => $new_patron->borrowernumber }
1892         );
1893         is(
1894             $queued_notices->count, 0,
1895             "No notice queued when NotifyPasswordChange enabled and this is a new patron"
1896         );
1897
1898         $schema->storage->txn_rollback;
1899     };
1900 };
1901
1902 subtest '->set_password' => sub {
1903
1904     plan tests => 16;
1905
1906     t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro|email' );
1907
1908     $schema->storage->txn_begin;
1909
1910     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1911
1912     # Disable logging password changes for these tests
1913     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1914
1915     # Disable notifying patrons of password changes for these tests
1916     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 );
1917
1918     # Password-length tests
1919     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1920     throws_ok { $patron->set_password({ password => 'ab' }); }
1921         'Koha::Exceptions::Password::TooShort',
1922         'minPasswordLength is undef, fall back to 3, fail test';
1923     is( "$@",
1924         'Password length (2) is shorter than required (3)',
1925         'Exception parameters passed correctly'
1926     );
1927
1928     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1929     throws_ok { $patron->set_password({ password => 'ab' }); }
1930         'Koha::Exceptions::Password::TooShort',
1931         'minPasswordLength is 2, fall back to 3, fail test';
1932
1933     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1934     throws_ok { $patron->set_password({ password => 'abcb' }); }
1935         'Koha::Exceptions::Password::TooShort',
1936         'minPasswordLength is 5, fail test';
1937
1938     # Trailing spaces tests
1939     throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
1940         'Koha::Exceptions::Password::WhitespaceCharacters',
1941         'Password contains trailing spaces, exception is thrown';
1942
1943     # Require strong password tests
1944     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1945     throws_ok { $patron->set_password({ password => 'abcd   a' }); }
1946         'Koha::Exceptions::Password::TooWeak',
1947         'Password is too weak, exception is thrown';
1948
1949     # Refresh patron from DB, just to make sure
1950     $patron->discard_changes;
1951     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1952
1953     $patron->set_password({ password => 'abcD12 34' });
1954     $patron->discard_changes;
1955
1956     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1957
1958     lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
1959         'Password is weak, but skip_validation was passed, so no exception thrown';
1960
1961     # Completeness
1962     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1963     $patron->login_attempts(3)->store;
1964     my $old_digest = $patron->password;
1965     $patron->set_password({ password => 'abcd   a' });
1966     $patron->discard_changes;
1967
1968     isnt( $patron->password, $old_digest, 'Password has been updated' );
1969     ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
1970     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1971
1972     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1973     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1974
1975     # Enable logging password changes
1976     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1977     $patron->set_password({ password => 'abcd   b' });
1978
1979     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1980     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1981
1982     # Enable notifying patrons of password changes
1983     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1984     $patron->set_password({ password => 'abcd   c' });
1985     my $queued_notices = Koha::Notice::Messages->search({ borrowernumber => $patron->borrowernumber });
1986     is( $queued_notices->count, 1, "One notice queued when NotifyPasswordChange enabled" );
1987     my $THE_notice = $queued_notices->next;
1988     is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address."); #FIXME Mock sending mail
1989     $schema->storage->txn_rollback;
1990 };
1991
1992 $schema->storage->txn_begin;
1993 subtest 'filter_by_expiration_date' => sub {
1994     plan tests => 3;
1995     my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
1996     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
1997     $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
1998     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
1999     $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
2000     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
2001     $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
2002     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
2003 };
2004
2005 subtest 'search_unsubscribed' => sub {
2006     plan tests => 4;
2007
2008     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2009     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
2010     is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
2011
2012     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2013     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2014
2015     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
2016     Koha::Patron::Consents->delete; # for correct counts
2017     Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
2018     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
2019
2020     # Add another refusal but shift the period
2021     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
2022     Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
2023     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
2024
2025     # Try another (special) attempts setting
2026     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
2027     # Lockout is now disabled
2028     # Patron2 still matches: refused earlier, not locked
2029     is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
2030 };
2031
2032 subtest 'search_anonymize_candidates' => sub {
2033     plan tests => 7;
2034     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2035     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2036     $patron1->anonymized(0);
2037     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2038     $patron2->anonymized(0);
2039     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2040
2041     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
2042     is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
2043
2044     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
2045     my $cnt = Koha::Patrons->search_anonymize_candidates->count;
2046     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2047     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2048     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
2049
2050     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
2051     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2052     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2053     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2054     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2055     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2056     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
2057
2058     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
2059     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2060     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2061     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2062     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2063     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2064     is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
2065
2066     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2067     $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2068     $patron1->login_attempts(0)->store;
2069     $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2070     $patron2->login_attempts(0)->store;
2071     $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
2072     $patron1->login_attempts(3)->store;
2073     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2074         $cnt+1, 'Locked flag' );
2075
2076     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2077     # Patron 1 still on 3 == locked
2078     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2079         $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2080     $patron1->login_attempts(0)->store;
2081     # Patron 1 unlocked
2082     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2083         $cnt, 'Patron 1 unlocked' );
2084 };
2085
2086 subtest 'search_anonymized' => sub {
2087     plan tests => 3;
2088     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2089
2090     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2091     is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2092
2093     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2094     $patron1->dateexpiry( dt_from_string );
2095     $patron1->anonymized(0)->store;
2096     my $cnt = Koha::Patrons->search_anonymized->count;
2097     $patron1->anonymized(1)->store;
2098     is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2099     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2100     is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2101 };
2102
2103 subtest 'lock' => sub {
2104     plan tests => 8;
2105
2106     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2107     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2108     my $hold = $builder->build_object({
2109         class => 'Koha::Holds',
2110         value => { borrowernumber => $patron1->borrowernumber },
2111     });
2112
2113     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2114     my $expiry = dt_from_string->add(days => 1);
2115     $patron1->dateexpiry( $expiry );
2116     $patron1->lock;
2117     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2118     is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2119     is( $patron1->holds->count, 1, 'No holds removed' );
2120
2121     $patron1->lock({ expire => 1, remove => 1});
2122     isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2123     is( $patron1->holds->count, 0, 'Holds removed' );
2124
2125     # Disable lockout feature
2126     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2127     $patron1->login_attempts(0);
2128     $patron1->dateexpiry( $expiry );
2129     $patron1->store;
2130     $patron1->lock;
2131     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2132
2133     # Trivial wrapper test (Koha::Patrons->lock)
2134     $patron1->login_attempts(0)->store;
2135     Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2136     $patron1->discard_changes; # refresh
2137     $patron2->discard_changes;
2138     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2139     is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2140 };
2141
2142 subtest 'anonymize' => sub {
2143     plan tests => 10;
2144
2145     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2146     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2147
2148     # First try patron with issues
2149     my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2150     warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2151     $issue->delete;
2152
2153     t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2154     my $surname = $patron1->surname; # expect change, no clear
2155     my $branchcode = $patron1->branchcode; # expect skip
2156     $patron1->anonymize;
2157     is($patron1->anonymized, 1, 'Check flag' );
2158
2159     is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2160     is( $patron1->firstname, undef, 'First name cleared' );
2161     isnt( $patron1->surname, $surname, 'Surname changed' );
2162     ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2163     is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2164     is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2165
2166     # Test wrapper in Koha::Patrons
2167     $patron1->surname($surname)->store; # restore
2168     my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2169     $patron1->discard_changes; # refresh
2170     isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2171     $patron2->discard_changes; # refresh
2172     is( $patron2->firstname, undef, 'First name patron2 cleared' );
2173 };
2174
2175 subtest 'queue_notice' => sub {
2176     plan tests => 11;
2177
2178     my $dbh = C4::Context->dbh;
2179     t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'email' );
2180     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2181     my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2182     my $letter_e = $builder->build_object( {
2183         class => 'Koha::Notice::Templates',
2184         value => {
2185             branchcode => $branch->branchcode,
2186             message_transport_type => 'email',
2187             lang => 'default'
2188         }
2189     });
2190     my $letter_p = $builder->build_object( {
2191         class => 'Koha::Notice::Templates',
2192         value => {
2193             code => $letter_e->code,
2194             module => $letter_e->module,
2195             branchcode => $branch->branchcode,
2196             message_transport_type => 'print',
2197             lang => 'default'
2198         }
2199     });
2200     my $letter_s = $builder->build_object( {
2201         class => 'Koha::Notice::Templates',
2202         value => {
2203             code => $letter_e->code,
2204             module => $letter_e->module,
2205             branchcode => $branch->branchcode,
2206             message_transport_type => 'sms',
2207             lang => 'default'
2208         }
2209     });
2210
2211     my $letter_params = {
2212         letter_code => $letter_e->code,
2213         branchcode  => $letter_e->branchcode,
2214         module      => $letter_e->module,
2215         borrowernumber => $patron->borrowernumber,
2216         tables => {
2217             borrowers => $patron->borrowernumber,
2218         }
2219     };
2220     my @mtts = ('email');
2221
2222     is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2223     is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2224     is_deeply(
2225         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2226         {sent => ['email'] }, "Email sent"
2227     );
2228     $patron->email("")->store;
2229     is_deeply(
2230         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2231         {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2232     );
2233     push @mtts, 'sms';
2234     is_deeply(
2235         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2236         {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2237     );
2238     $patron->smsalertnumber("")->store;
2239     my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2240     is_deeply(
2241         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2242         {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2243     );
2244     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2245
2246     # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2247     $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2248     my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2249     $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2250
2251     is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2252
2253     $patron->email(q|awesome@ismymiddle.name|)->store;
2254     is_deeply(
2255         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2256         {sent => ['email'] }, "Email sent when using borrower preferences"
2257     );
2258     $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2259     is_deeply(
2260         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2261         {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2262     );
2263     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2264 };
2265
2266 subtest 'filter_by_amount_owed' => sub {
2267     plan tests => 6;
2268
2269     my $library = $builder->build({source => 'Branch' });
2270     my $category = $builder->build({source => 'Category' });
2271
2272     my $new_patron_cf_1 = Koha::Patron->new(
2273         {
2274             cardnumber   => 'test_cn_cf_1',
2275             branchcode   => $library->{branchcode},
2276             categorycode => $category->{categorycode},
2277             surname      => 'surname for patron1',
2278             firstname    => 'firstname for patron1',
2279             userid       => 'a_nonexistent_userid_cf_1',
2280         }
2281     )->store;
2282     my $new_patron_cf_2 = Koha::Patron->new(
2283         {
2284             cardnumber   => 'test_cn_cf_2',
2285             branchcode   => $library->{branchcode},
2286             categorycode => $category->{categorycode},
2287             surname      => 'surname for patron2',
2288             firstname    => 'firstname for patron2',
2289             userid       => 'a_nonexistent_userid_cf_2',
2290         }
2291     )->store;
2292     my $new_patron_cf_3 = Koha::Patron->new(
2293         {
2294             cardnumber   => 'test_cn_cf_3',
2295             branchcode   => $library->{branchcode},
2296             categorycode => $category->{categorycode},
2297             surname      => 'surname for patron3',
2298             firstname    => 'firstname for patron3',
2299             userid       => 'a_nonexistent_userid_cf_3',
2300         }
2301     )->store;
2302
2303     my $results = Koha::Patrons->search(
2304         {
2305             'me.borrowernumber' => [
2306                 $new_patron_cf_1->borrowernumber,
2307                 $new_patron_cf_2->borrowernumber,
2308                 $new_patron_cf_3->borrowernumber
2309             ]
2310         }
2311     );
2312
2313     my $fine1 = $builder->build(
2314         {
2315             source => 'Accountline',
2316             value  => {
2317                 borrowernumber    => $new_patron_cf_1->borrowernumber,
2318                 amountoutstanding => 12.00,
2319                 amount            => 12.00,
2320                 debit_type_code   => 'OVERDUE',
2321                 branchcode        => $library->{branchcode}
2322             },
2323         }
2324     );
2325     my $fine2 = $builder->build(
2326         {
2327             source => 'Accountline',
2328             value  => {
2329                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2330                 amountoutstanding => 8.00,
2331                 amount            => 8.00,
2332                 debit_type_code   => 'OVERDUE',
2333                 branchcode        => $library->{branchcode}
2334
2335             },
2336         }
2337     );
2338     my $fine3 = $builder->build(
2339         {
2340             source => 'Accountline',
2341             value  => {
2342                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2343                 amountoutstanding => 10.00,
2344                 amount            => 10.00,
2345                 debit_type_code   => 'OVERDUE',
2346                 branchcode        => $library->{branchcode}
2347             },
2348         }
2349     );
2350
2351     my $filtered = $results->filter_by_amount_owed();
2352     is( ref($filtered), 'Koha::Patrons',
2353 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context'
2354     );
2355
2356     my $lower_limit = 12.00;
2357     my $upper_limit = 16.00;
2358
2359     # Catch user with 1 x 12.00 fine and user with no fines.
2360     $filtered =
2361       $results->filter_by_amount_owed( { less_than => $upper_limit } );
2362     is( $filtered->_resultset->as_subselect_rs->count, 2,
2363 "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons"
2364     );
2365
2366     # Catch user with 1 x 8.00 and 1 x 10.00 fine
2367     $filtered =
2368       $results->filter_by_amount_owed( { more_than => $lower_limit } );
2369     is( $filtered->_resultset->as_subselect_rs->count, 1,
2370 "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons"
2371     );
2372
2373     # User with 2 fines falls above upper limit - Excluded,
2374     # user with 1 fine falls below lower limit - Excluded
2375     # and user with no fines falls below lower limit - Excluded.
2376     $filtered = $results->filter_by_amount_owed(
2377         { more_than => $lower_limit, less_than => $upper_limit } );
2378     is( $filtered->_resultset->as_subselect_rs->count, 0,
2379 "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons"
2380     );
2381
2382     my $library2 = $builder->build({source => 'Branch' });
2383     my $fine4 = $builder->build(
2384         {
2385             source => 'Accountline',
2386             value  => {
2387                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2388                 amountoutstanding => 10.00,
2389                 amount            => 10.00,
2390                 debit_type_code   => 'HOLD',
2391                 branchcode        => $library2->{branchcode}
2392             },
2393         }
2394     );
2395
2396     # Catch only the user with a HOLD fee over 6.00
2397     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } );
2398     is( $filtered->_resultset->as_subselect_rs->count, 1,
2399 "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron"
2400     );
2401
2402     # Catch only the user with a fee over 6.00 at the specified library
2403     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } );
2404     is( $filtered->_resultset->as_subselect_rs->count, 1,
2405 "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron"
2406     );
2407 };
2408
2409 subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => sub {
2410     plan tests => 2;
2411
2412     $schema->storage->txn_begin;
2413     my $dbh = $schema->storage->dbh;
2414
2415     $dbh->do("DELETE FROM library_groups");
2416
2417     # group1
2418     #   library_1A
2419     #   library_1B
2420     # group2
2421     #   library_2A
2422     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store;
2423     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store;
2424     my $library_1A = $builder->build( { source => 'Branch' } );
2425     my $library_1B = $builder->build( { source => 'Branch' } );
2426     my $library_2A = $builder->build( { source => 'Branch' } );
2427     $library_1A = Koha::Libraries->find( $library_1A->{branchcode} );
2428     $library_1B = Koha::Libraries->find( $library_1B->{branchcode} );
2429     $library_2A = Koha::Libraries->find( $library_2A->{branchcode} );
2430     Koha::Library::Group->new( { branchcode => $library_1A->branchcode, parent_id => $group_1->id } )->store;
2431     Koha::Library::Group->new( { branchcode => $library_1B->branchcode, parent_id => $group_1->id } )->store;
2432     Koha::Library::Group->new( { branchcode => $library_2A->branchcode, parent_id => $group_2->id } )->store;
2433
2434     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|); # 9 for editcatalogue
2435     # 2 patrons from library_1A (group1)
2436     # patron_1A_1 see patron's infos from outside its group
2437     # Setting flags => undef to not be considered as superlibrarian
2438     my $patron_1A_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2439     $patron_1A_1 = Koha::Patrons->find( $patron_1A_1->{borrowernumber} );
2440     $sth->execute( $patron_1A_1->borrowernumber, 'edit_items' );
2441     $sth->execute( $patron_1A_1->borrowernumber, 'edit_any_item' );
2442     # patron_1A_2 can only see patron's info from its group
2443     my $patron_1A_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2444     $patron_1A_2 = Koha::Patrons->find( $patron_1A_2->{borrowernumber} );
2445     $sth->execute( $patron_1A_2->borrowernumber, 'edit_items' );
2446     # 1 patron from library_1B (group1)
2447     my $patron_1B = $builder->build({ source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, }});
2448     $patron_1B = Koha::Patrons->find( $patron_1B->{borrowernumber} );
2449     # 1 patron from library_2A (group2) can only see patron's info from its group
2450     my $patron_2A = $builder->build({ source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, }});
2451     $patron_2A = Koha::Patrons->find( $patron_2A->{borrowernumber} );
2452     $sth->execute( $patron_2A->borrowernumber, 'edit_items' );
2453
2454     subtest 'libraries_where_can_edit_items' => sub {
2455         plan tests => 3;
2456
2457         my @branchcodes;
2458
2459         @branchcodes = $patron_1A_1->libraries_where_can_edit_items;
2460         is_deeply( \@branchcodes, [], "patron_1A_1 has edit_any_item => No restrictions" );
2461
2462         @branchcodes = $patron_1A_2->libraries_where_can_edit_items;
2463         is_deeply( \@branchcodes, [ sort ( $library_1A->branchcode, $library_1B->branchcode ) ], "patron_1A_2 doesn't have edit_any_item => Can only edit items from its group" );
2464
2465         @branchcodes = $patron_2A->libraries_where_can_edit_items;
2466         is_deeply( \@branchcodes, [$library_2A->branchcode], "patron_2A doesn't have edit_any_item => Can only see patron's from its group" );
2467     };
2468
2469     subtest 'can_edit_items_from' => sub {
2470         plan tests => 6;
2471
2472         t::lib::Mocks::mock_userenv({ patron => $patron_1A_1 });
2473         is( $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, "patron_1A_1 can see patron_1A_2, from its library" );
2474         is( $patron_1A_1->can_edit_items_from( $library_1B->id ),   1, "patron_1A_1 can see patron_1B, from its group" );
2475         is( $patron_1A_1->can_edit_items_from( $library_2A->id ),   1, "patron_1A_1 can see patron_1A_2, from another group" );
2476
2477         t::lib::Mocks::mock_userenv({ patron => $patron_1A_2 });
2478         is( $patron_1A_2->can_edit_items_from( $library_1A->id ),   1, "patron_1A_2 can see patron_1A_1, from its library" );
2479         is( $patron_1A_2->can_edit_items_from( $library_1B->id ),   1, "patron_1A_2 can see patron_1B, from its group" );
2480         is( $patron_1A_2->can_edit_items_from( $library_2A->id ),   0, "patron_1A_2 can NOT see patron_2A, from another group" );
2481     };
2482 };
2483
2484 subtest 'filter_by_have_permission' => sub {
2485     plan tests => 5;
2486
2487     $schema->storage->txn_begin;
2488
2489     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
2490     my $patron_1 = $builder->build_object(
2491         {
2492             class => 'Koha::Patrons',
2493             value => { flags => 1, branchcode => $library->branchcode }
2494         }
2495     );
2496
2497     my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions
2498         {
2499             class => 'Koha::Patrons',
2500             value => { flags => 4096, branchcode => $library->branchcode }
2501         }
2502     );
2503
2504     my $patron_3 = $builder->build_object(
2505         {
2506             class => 'Koha::Patrons',
2507             value => { flags => 0, branchcode => $library->branchcode }
2508         }
2509     );
2510     $builder->build(
2511         {
2512             source => 'UserPermission',
2513             value  => {
2514                 borrowernumber => $patron_3->borrowernumber,
2515                 module_bit     => 11,
2516                 code           => 'order_manage',
2517             },
2518         }
2519     );
2520
2521     is_deeply(
2522         [
2523             Koha::Patrons->search( { branchcode => $library->branchcode } )
2524               ->filter_by_have_permission('suggestions.suggestions_manage')
2525               ->get_column('borrowernumber')
2526         ],
2527         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2528         'Superlibrarian and patron with suggestions.suggestions_manage'
2529     );
2530
2531     is_deeply(
2532         [
2533             Koha::Patrons->search( { branchcode => $library->branchcode } )
2534               ->filter_by_have_permission('acquisition.order_manage')
2535               ->get_column('borrowernumber')
2536         ],
2537         [ $patron_1->borrowernumber, $patron_3->borrowernumber ],
2538         'Superlibrarian and patron with acquisition.order_manage'
2539     );
2540
2541     is_deeply(
2542         [
2543             Koha::Patrons->search( { branchcode => $library->branchcode } )
2544               ->filter_by_have_permission('parameters.manage_cities')
2545               ->get_column('borrowernumber')
2546         ],
2547         [ $patron_1->borrowernumber ],
2548         'Only Superlibrarian is returned'
2549     );
2550
2551     is_deeply(
2552         [
2553             Koha::Patrons->search( { branchcode => $library->branchcode } )
2554               ->filter_by_have_permission('suggestions')
2555               ->get_column('borrowernumber')
2556         ],
2557         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2558         'Superlibrarian and patron with suggestions'
2559     );
2560
2561     throws_ok {
2562         Koha::Patrons->search( { branchcode => $library->branchcode } )
2563           ->filter_by_have_permission('dont_exist.subperm');
2564     } 'Koha::Exceptions::ObjectNotFound';
2565
2566
2567     $schema->storage->txn_rollback;
2568 };
2569
2570 $schema->storage->txn_rollback;