Bug 34932: Patron.t - Pass borrowernumber of manager to userenv
[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     # Not sure how this is useful, but AddIssue pass this variable to different other subroutines
662     $patron = Koha::Patrons->find( $patron->borrowernumber )->unblessed;
663
664     t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} });
665
666     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
667     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
668     AddIssue( $patron, $item_3->barcode );
669
670     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
671     $checkouts = $patron->checkouts;
672     is( $checkouts->count, 3, 'checkouts should return 3 issues for that patron' );
673     is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' );
674     $pending_checkouts = $patron->pending_checkouts;
675     is( $pending_checkouts->count, 3, 'pending_checkouts should return 3 issues for that patron' );
676     is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' );
677
678     my $first_checkout = $pending_checkouts->next;
679     is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_3->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' );
680
681     my $overdues = $patron->overdues;
682     is( $overdues->count, 2, 'Patron should have 2 overdues');
683     is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' );
684     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
685     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
686
687
688     C4::Circulation::AddReturn( $item_1->barcode );
689     C4::Circulation::AddReturn( $item_2->barcode );
690     $old_checkouts = $patron->old_checkouts;
691     is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' );
692     is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' );
693
694     # Clean stuffs
695     Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete;
696     $patron->delete;
697 };
698
699 subtest 'get_routing_lists' => sub {
700     plan tests => 5;
701
702     my $biblio = Koha::Biblio->new()->store();
703     my $subscription = Koha::Subscription->new({
704         biblionumber => $biblio->biblionumber,
705         }
706     )->store;
707
708     my $patron = $builder->build( { source => 'Borrower' } );
709     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
710
711     is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' );
712
713     my $routinglist_count = Koha::Subscription::Routinglists->count;
714     my $routinglist = Koha::Subscription::Routinglist->new({
715         borrowernumber   => $patron->borrowernumber,
716         ranking          => 5,
717         subscriptionid   => $subscription->subscriptionid
718     })->store;
719
720     is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1");
721
722     my $routinglists = $patron->get_routing_lists;
723     is ($routinglists->next->ranking, 5, "Retrieves ranking: 5");
724     is( ref($routinglists),   'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' );
725
726     my $subscription2 = Koha::Subscription->new({
727         biblionumber => $biblio->biblionumber,
728         }
729     )->store;
730     my $routinglist2 = Koha::Subscription::Routinglist->new({
731         borrowernumber   => $patron->borrowernumber,
732         ranking          => 1,
733         subscriptionid   => $subscription2->subscriptionid
734     })->store;
735
736     is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2");
737
738     $patron->delete; # Clean up for later tests
739
740 };
741
742 subtest 'get_age' => sub {
743     plan tests => 31;
744
745     # Following tests implicitly assume timezone UTC
746     delete $C4::Context::context->{tz};
747     local %ENV;
748     $ENV{TZ} = 'Etc/UTC';
749
750     my $patron = $builder->build( { source => 'Borrower' } );
751     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
752
753     my @dates = (
754         {
755             today            => '2020-02-28',
756             has_12           => { date => '2007-08-27', expected_age => 12 },
757             almost_18        => { date => '2002-03-01', expected_age => 17 },
758             has_18_today     => { date => '2002-02-28', expected_age => 18 },
759             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
760             almost_16        => { date => '2004-02-29', expected_age => 15 },
761             has_16_today     => { date => '2004-02-28', expected_age => 16 },
762             had_16_yesterday => { date => '2004-02-27', expected_age => 16 },
763             new_born         => { date => '2020-01-27', expected_age => 0 },
764         },
765         {
766             today            => '2020-02-29',
767             has_12           => { date => '2007-08-27', expected_age => 12 },
768             almost_18        => { date => '2002-03-01', expected_age => 17 },
769             has_18_today     => { date => '2002-02-28', expected_age => 18 },
770             had_18_yesterday => { date => '2002-02-27', expected_age => 18 },
771             almost_16        => { date => '2004-03-01', expected_age => 15 },
772             has_16_today     => { date => '2004-02-29', expected_age => 16 },
773             had_16_yesterday => { date => '2004-02-28', expected_age => 16 },
774             new_born         => { date => '2020-01-27', expected_age => 0 },
775         },
776         {
777             today            => '2020-03-01',
778             has_12           => { date => '2007-08-27', expected_age => 12 },
779             almost_18        => { date => '2002-03-02', expected_age => 17 },
780             has_18_today     => { date => '2002-03-01', expected_age => 18 },
781             had_18_yesterday => { date => '2002-02-28', expected_age => 18 },
782             almost_16        => { date => '2004-03-02', expected_age => 15 },
783             has_16_today     => { date => '2004-03-01', expected_age => 16 },
784             had_16_yesterday => { date => '2004-02-29', expected_age => 16 },
785         },
786         {
787             today            => '2019-01-31',
788             has_12           => { date => '2006-08-27', expected_age => 12 },
789             almost_18        => { date => '2001-02-01', expected_age => 17 },
790             has_18_today     => { date => '2001-01-31', expected_age => 18 },
791             had_18_yesterday => { date => '2001-01-30', expected_age => 18 },
792             almost_16        => { date => '2003-02-01', expected_age => 15 },
793             has_16_today     => { date => '2003-01-31', expected_age => 16 },
794             had_16_yesterday => { date => '2003-01-30', expected_age => 16 },
795         },
796     );
797
798     $patron->dateofbirth( undef );
799     is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' );
800
801     for my $date ( @dates ) {
802
803         my $dt = dt_from_string($date->{today});
804
805         Time::Fake->offset( $dt->epoch );
806
807         for my $k ( keys %$date ) {
808             next if $k eq 'today';
809
810             my $dob = $date->{$k};
811             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
812             is(
813                 $patron->get_age,
814                 $dob->{expected_age},
815                 sprintf(
816                     "Today=%s, dob=%s, should be %d",
817                     $date->{today}, $dob->{date}, $dob->{expected_age}
818                 )
819             );
820         }
821
822         Time::Fake->reset;
823
824     }
825
826     $patron->delete;
827
828     # Remove timezone change
829     delete $C4::Context::context->{tz};
830 };
831
832 subtest 'is_valid_age' => sub {
833     plan tests => 10;
834
835     # Following tests implicitly assume timezone UTC
836     delete $C4::Context::context->{tz};
837     local %ENV;
838     $ENV{TZ} = 'Etc/UTC';
839
840     my $dt = dt_from_string('2020-02-28');
841
842     Time::Fake->offset( $dt->epoch );
843
844     my $category = $builder->build({
845         source => 'Category',
846         value => {
847             categorycode        => 'AGE_5_10',
848             dateofbirthrequired => 5,
849             upperagelimit       => 10
850         }
851     });
852     $category = Koha::Patron::Categories->find( $category->{categorycode} );
853
854     my $patron = $builder->build({
855         source => 'Borrower',
856         value => {
857             categorycode        => $category->categorycode
858         }
859     });
860     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
861
862
863     $patron->dateofbirth( undef );
864     is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category');
865
866     my @dates = (
867         {
868             today => '2020-02-28',
869             add_m12_m6_m1 =>
870               { date => '2007-08-27', expected_age => 12, valid => 0 },
871             add_m3_m6_m1 =>
872               { date => '2016-08-27', expected_age => 3, valid => 0 },
873             add_m7_m6_m1 =>
874               { date => '2013-02-28', expected_age => 7, valid => 1 },
875             add_m5_0_0 =>
876               { date => '2015-02-28', expected_age => 5, valid => 1 },
877             add_m5_0_p1 =>
878               { date => '2015-03-01', expected_age => 4, valid => 0 },
879             add_m5_0_m1 =>
880               { date => '2015-02-27', expected_age => 5, valid => 1 },
881             add_m11_0_0 =>
882               { date => '2009-02-28', expected_age => 11, valid => 0 },
883             add_m11_0_p1 =>
884               { date => '2009-03-01', expected_age => 10, valid => 1 },
885             add_m11_0_m1 =>
886               { date => '2009-02-27', expected_age => 11, valid => 0 },
887         },
888     );
889
890     for my $date ( @dates ) {
891
892         my $dt = dt_from_string($date->{today});
893
894         Time::Fake->offset( $dt->epoch );
895
896         for my $k ( sort keys %$date ) {
897             next if $k eq 'today';
898
899             my $dob = $date->{$k};
900             $patron->dateofbirth( dt_from_string( $dob->{date}, 'iso' ) );
901             is(
902                 $patron->is_valid_age,
903                 $dob->{valid},
904                 sprintf(
905                     "Today=%s, dob=%s, is %s, should be valid=%s in category %s",
906                     $date->{today}, $dob->{date}, $dob->{expected_age}, $dob->{valid}, $category->categorycode
907                 )
908             );
909         }
910
911         Time::Fake->reset;
912
913     }
914
915     $patron->delete;
916     $category->delete;
917
918     # Remove timezone change
919     delete $C4::Context::context->{tz};
920 };
921
922 subtest 'account' => sub {
923     plan tests => 1;
924
925     my $patron = $builder->build({source => 'Borrower'});
926
927     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
928     my $account = $patron->account;
929     is( ref($account),   'Koha::Account', 'account should return a Koha::Account object' );
930
931     $patron->delete;
932 };
933
934 subtest 'search_upcoming_membership_expires' => sub {
935     plan tests => 9;
936
937     my $expiry_days = 15;
938     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days );
939     my $nb_of_days_before = 1;
940     my $nb_of_days_after = 2;
941
942     my $builder = t::lib::TestBuilder->new();
943
944     my $library = $builder->build({ source => 'Branch' });
945
946     # before we add borrowers to this branch, add the expires we have now
947     # note that this pertains to the current mocked setting of the pref
948     # for this reason we add the new branchcode to most of the tests
949     my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count;
950
951     my $patron_1 = $builder->build({
952         source => 'Borrower',
953         value  => {
954             branchcode              => $library->{branchcode},
955             dateexpiry              => dt_from_string->add( days => $expiry_days )
956         },
957     });
958
959     my $patron_2 = $builder->build({
960         source => 'Borrower',
961         value  => {
962             branchcode              => $library->{branchcode},
963             dateexpiry              => dt_from_string->add( days => $expiry_days - $nb_of_days_before )
964         },
965     });
966
967     my $patron_3 = $builder->build({
968         source => 'Borrower',
969         value  => {
970             branchcode              => $library->{branchcode},
971             dateexpiry              => dt_from_string->add( days => $expiry_days + $nb_of_days_after )
972         },
973     });
974
975     # Test without extra parameters
976     my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires();
977     is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' );
978
979     # Test with branch
980     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
981     is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' );
982     my $expired = $upcoming_mem_expires->next;
983     is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' );
984     is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' );
985     is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' );
986
987     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 );
988     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
989     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' );
990
991     # Test MembershipExpiryDaysNotice == undef
992     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef );
993     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} });
994     is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' );
995
996     # Test the before parameter
997     t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 );
998     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before });
999     is( $upcoming_mem_expires->count, 2, 'Expect two results for before');
1000     # Test after parameter also
1001     $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after });
1002     is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' );
1003     Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete;
1004 };
1005
1006 subtest 'holds and old_holds' => sub {
1007     plan tests => 6;
1008
1009     my $library = $builder->build( { source => 'Branch' } );
1010     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1011     my $item_1 = $builder->build_sample_item(
1012         {
1013             library      => $library->{branchcode},
1014             biblionumber => $biblionumber_1,
1015         }
1016     );
1017     my $item_2 = $builder->build_sample_item(
1018         {
1019             library      => $library->{branchcode},
1020             biblionumber => $biblionumber_1,
1021         }
1022     );
1023     my $biblionumber_2 = $builder->build_sample_biblio->biblionumber;
1024     my $item_3 = $builder->build_sample_item(
1025         {
1026             library      => $library->{branchcode},
1027             biblionumber => $biblionumber_2,
1028         }
1029     );
1030
1031     my $patron = $builder->build(
1032         {
1033             source => 'Borrower',
1034             value  => { branchcode => $library->{branchcode} }
1035         }
1036     );
1037
1038     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1039     my $holds = $patron->holds;
1040     is( ref($holds), 'Koha::Holds',
1041         'Koha::Patron->holds should return a Koha::Holds objects' );
1042     is( $holds->count, 0, 'There should not be holds placed by this patron yet' );
1043
1044     C4::Reserves::AddReserve(
1045         {
1046             branchcode     => $library->{branchcode},
1047             borrowernumber => $patron->borrowernumber,
1048             biblionumber   => $biblionumber_1
1049         }
1050     );
1051     # In the future
1052     C4::Reserves::AddReserve(
1053         {
1054             branchcode      => $library->{branchcode},
1055             borrowernumber  => $patron->borrowernumber,
1056             biblionumber    => $biblionumber_2,
1057             expiration_date => dt_from_string->add( days => 2 )
1058         }
1059     );
1060
1061     $holds = $patron->holds;
1062     is( $holds->count, 2, 'There should be 2 holds placed by this patron' );
1063
1064     my $old_holds = $patron->old_holds;
1065     is( ref($old_holds), 'Koha::Old::Holds',
1066         'Koha::Patron->old_holds should return a Koha::Old::Holds objects' );
1067     is( $old_holds->count, 0, 'There should not be any old holds yet');
1068
1069     my $hold = $holds->next;
1070     $hold->cancel;
1071
1072     $old_holds = $patron->old_holds;
1073     is( $old_holds->count, 1, 'There should  be 1 old (cancelled) hold');
1074
1075     $old_holds->delete;
1076     $holds->delete;
1077     $patron->delete;
1078 };
1079
1080 subtest 'search_patrons_to_anonymise' => sub {
1081
1082     plan tests => 5;
1083
1084     # TODO create a subroutine in t::lib::Mocks
1085     my $branch = $builder->build({ source => 'Branch' });
1086     my $userenv_patron = $builder->build_object({
1087         class  => 'Koha::Patrons',
1088         value  => { branchcode => $branch->{branchcode}, flags => 0 },
1089     });
1090     t::lib::Mocks::mock_userenv({ patron => $userenv_patron });
1091
1092     my $anonymous = $builder->build( { source => 'Borrower', }, );
1093
1094     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->{borrowernumber} );
1095
1096     subtest 'Anonymous Patron should be undeleteable' => sub {
1097         plan tests => 2;
1098
1099         my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1100         throws_ok { $anonymous_patron->delete(); }
1101             'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron',
1102             'Attempt to delete anonymous patron throws exception.';
1103         $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} );
1104         is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" );
1105     };
1106
1107     subtest 'patron privacy is 1 (default)' => sub {
1108         plan tests => 9;
1109
1110         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1111         my $patron = $builder->build(
1112             {   source => 'Borrower',
1113                 value  => { privacy => 1, }
1114             }
1115         );
1116         my $item_1 = $builder->build_sample_item;
1117         my $issue_1 = $builder->build(
1118             {   source => 'Issue',
1119                 value  => {
1120                     borrowernumber => $patron->{borrowernumber},
1121                     itemnumber     => $item_1->itemnumber,
1122                 },
1123             }
1124         );
1125         my $item_2 = $builder->build_sample_item;
1126         my $issue_2 = $builder->build(
1127             {   source => 'Issue',
1128                 value  => {
1129                     borrowernumber => $patron->{borrowernumber},
1130                     itemnumber     => $item_2->itemnumber,
1131                 },
1132             }
1133         );
1134
1135         my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') );
1136         my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') );
1137         is( $returned_1 && $returned_2, 1, 'The items should have been returned' );
1138
1139         my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } );
1140         is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' );
1141
1142         my $rows_affected = Koha::Old::Checkouts->search(
1143             {
1144                 borrowernumber => [
1145                     Koha::Patrons->search_patrons_to_anonymise(
1146                         { before => '2011-11-12' }
1147                     )->get_column('borrowernumber')
1148                 ],
1149                 returndate => { '<' => '2011-10-11', }
1150             }
1151         )->anonymize;
1152         ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' );
1153
1154         $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1155         is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' );
1156
1157         my $dbh = C4::Context->dbh;
1158         my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|);
1159         $sth->execute($item_1->itemnumber);
1160         my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1161         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' );
1162         $sth->execute($item_2->itemnumber);
1163         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1164         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' );
1165
1166         $rows_affected = Koha::Old::Checkouts->search(
1167             {
1168                 borrowernumber => [
1169                     Koha::Patrons->search_patrons_to_anonymise(
1170                         { before => '2011-11-12' }
1171                     )->get_column('borrowernumber')
1172                 ],
1173                 returndate => { '<' => '2011-11-12', }
1174             }
1175         )->anonymize;
1176         $sth->execute($item_2->itemnumber);
1177         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1178         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' );
1179
1180         my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|);
1181         $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber );
1182         $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber );
1183         $rows_affected = Koha::Old::Checkouts->search(
1184             {
1185                 borrowernumber => [
1186                     Koha::Patrons->search_patrons_to_anonymise->get_column(
1187                         'borrowernumber')
1188                 ]
1189             }
1190         )->anonymize;
1191         $sth->execute($item_1->itemnumber);
1192         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1193         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' );
1194         $sth->execute($item_2->itemnumber);
1195         ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array;
1196         is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' );
1197
1198         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1199     };
1200
1201     subtest 'patron privacy is 0 (forever)' => sub {
1202         plan tests => 2;
1203
1204         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1205         my $patron = $builder->build(
1206             {   source => 'Borrower',
1207                 value  => { privacy => 0, }
1208             }
1209         );
1210         my $item = $builder->build_sample_item;
1211         my $issue = $builder->build(
1212             {   source => 'Issue',
1213                 value  => {
1214                     borrowernumber => $patron->{borrowernumber},
1215                     itemnumber     => $item->itemnumber,
1216                 },
1217             }
1218         );
1219
1220         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1221         is( $returned, 1, 'The item should have been returned' );
1222
1223         my $dbh = C4::Context->dbh;
1224         my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q|
1225             SELECT borrowernumber FROM old_issues where itemnumber = ?
1226         |, undef, $item->itemnumber);
1227         is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' );
1228         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1229     };
1230
1231     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1232
1233     subtest 'AnonymousPatron is not defined' => sub {
1234
1235         plan tests => 2;
1236
1237         t::lib::Mocks::mock_preference('IndependentBranches', 0);
1238         my $patron = $builder->build(
1239             {   source => 'Borrower',
1240                 value  => { privacy => 1, }
1241             }
1242         );
1243         my $item = $builder->build_sample_item;
1244         my $issue = $builder->build(
1245             {   source => 'Issue',
1246                 value  => {
1247                     borrowernumber => $patron->{borrowernumber},
1248                     itemnumber     => $item->itemnumber,
1249                 },
1250             }
1251         );
1252
1253         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1254         is( $returned, 1, 'The item should have been returned' );
1255         my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } );
1256         ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' );
1257
1258         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1259     };
1260
1261     subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub {
1262         plan tests => 1;
1263         t::lib::Mocks::mock_preference( 'IndependentBranches', 1 );
1264         my $patron = $builder->build(
1265             {   source => 'Borrower',
1266                 value  => { privacy => 1 }    # Another branchcode than the logged in librarian
1267             }
1268         );
1269         my $item = $builder->build_sample_item;
1270         my $issue = $builder->build(
1271             {   source => 'Issue',
1272                 value  => {
1273                     borrowernumber => $patron->{borrowernumber},
1274                     itemnumber     => $item->itemnumber,
1275                 },
1276             }
1277         );
1278
1279         my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') );
1280         is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 );
1281         Koha::Patrons->find( $patron->{borrowernumber})->delete;
1282     };
1283
1284     Koha::Patrons->find( $anonymous->{borrowernumber})->delete;
1285     $userenv_patron->delete;
1286
1287     # Reset IndependentBranches for further tests
1288     t::lib::Mocks::mock_preference('IndependentBranches', 0);
1289 };
1290
1291 subtest 'libraries_where_can_see_patrons + can_see_patron_infos + search_limited' => sub {
1292     plan tests => 3;
1293
1294     # group1
1295     #   + library_11
1296     #   + library_12
1297     # group2
1298     #   + library21
1299     $nb_of_patrons = Koha::Patrons->search->count;
1300     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store;
1301     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store;
1302     my $library_11 = $builder->build( { source => 'Branch' } );
1303     my $library_12 = $builder->build( { source => 'Branch' } );
1304     my $library_21 = $builder->build( { source => 'Branch' } );
1305     $library_11 = Koha::Libraries->find( $library_11->{branchcode} );
1306     $library_12 = Koha::Libraries->find( $library_12->{branchcode} );
1307     $library_21 = Koha::Libraries->find( $library_21->{branchcode} );
1308     Koha::Library::Group->new(
1309         { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store;
1310     Koha::Library::Group->new(
1311         { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store;
1312     Koha::Library::Group->new(
1313         { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store;
1314
1315     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 4, ?)|); # 4 for borrowers
1316     # 2 patrons from library_11 (group1)
1317     # patron_11_1 see patron's infos from outside its group
1318     # Setting flags => undef to not be considered as superlibrarian
1319     my $patron_11_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1320     $patron_11_1 = Koha::Patrons->find( $patron_11_1->{borrowernumber} );
1321     $sth->execute( $patron_11_1->borrowernumber, 'edit_borrowers' );
1322     $sth->execute( $patron_11_1->borrowernumber, 'view_borrower_infos_from_any_libraries' );
1323     # patron_11_2 can only see patron's info from its group
1324     my $patron_11_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_11->branchcode, flags => undef, }});
1325     $patron_11_2 = Koha::Patrons->find( $patron_11_2->{borrowernumber} );
1326     $sth->execute( $patron_11_2->borrowernumber, 'edit_borrowers' );
1327     # 1 patron from library_12 (group1)
1328     my $patron_12 = $builder->build({ source => 'Borrower', value => { branchcode => $library_12->branchcode, flags => undef, }});
1329     $patron_12 = Koha::Patrons->find( $patron_12->{borrowernumber} );
1330     # 1 patron from library_21 (group2) can only see patron's info from its group
1331     my $patron_21 = $builder->build({ source => 'Borrower', value => { branchcode => $library_21->branchcode, flags => undef, }});
1332     $patron_21 = Koha::Patrons->find( $patron_21->{borrowernumber} );
1333     $sth->execute( $patron_21->borrowernumber, 'edit_borrowers' );
1334
1335     # Pfiou, we can start now!
1336     subtest 'libraries_where_can_see_patrons' => sub {
1337         plan tests => 3;
1338
1339         my @branchcodes;
1340
1341         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1342         @branchcodes = $patron_11_1->libraries_where_can_see_patrons;
1343         is_deeply( \@branchcodes, [], q|patron_11_1 has view_borrower_infos_from_any_libraries => No restriction| );
1344
1345         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1346         @branchcodes = $patron_11_2->libraries_where_can_see_patrons;
1347         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| );
1348
1349         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1350         @branchcodes = $patron_21->libraries_where_can_see_patrons;
1351         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| );
1352     };
1353     subtest 'can_see_patron_infos' => sub {
1354         plan tests => 6;
1355
1356         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1357         is( $patron_11_1->can_see_patron_infos( $patron_11_2 ), 1, q|patron_11_1 can see patron_11_2, from its library| );
1358         is( $patron_11_1->can_see_patron_infos( $patron_12 ),   1, q|patron_11_1 can see patron_12, from its group| );
1359         is( $patron_11_1->can_see_patron_infos( $patron_21 ),   1, q|patron_11_1 can see patron_11_2, from another group| );
1360
1361         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1362         is( $patron_11_2->can_see_patron_infos( $patron_11_1 ), 1, q|patron_11_2 can see patron_11_1, from its library| );
1363         is( $patron_11_2->can_see_patron_infos( $patron_12 ),   1, q|patron_11_2 can see patron_12, from its group| );
1364         is( $patron_11_2->can_see_patron_infos( $patron_21 ),   0, q|patron_11_2 can NOT see patron_21, from another group| );
1365     };
1366     subtest 'search_limited' => sub {
1367         plan tests => 6;
1368
1369         t::lib::Mocks::mock_userenv({ patron => $patron_11_1 });
1370         my $total_number_of_patrons = $nb_of_patrons + 4; #we added four in these tests
1371         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons' );
1372         is( Koha::Patrons->search_limited->count, $total_number_of_patrons, 'patron_11_1 is allowed to see all patrons' );
1373
1374         t::lib::Mocks::mock_userenv({ patron => $patron_11_2 });
1375         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1376         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' );
1377
1378         t::lib::Mocks::mock_userenv({ patron => $patron_21 });
1379         is( Koha::Patrons->search->count, $total_number_of_patrons, 'Non-limited search should return all patrons');
1380         is( Koha::Patrons->search_limited->count, 1, 'patron_21 is not allowed to see patrons from other groups, only himself' );
1381     };
1382     $patron_11_1->delete;
1383     $patron_11_2->delete;
1384     $patron_12->delete;
1385     $patron_21->delete;
1386 };
1387
1388 subtest 'account_locked' => sub {
1389     plan tests => 13;
1390     my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } });
1391     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1392     for my $value ( undef, '', 0 ) {
1393         t::lib::Mocks::mock_preference('FailedloginAttempts', $value);
1394         $patron->login_attempts(0)->store;
1395         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1396         $patron->login_attempts(1)->store;
1397         is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' );
1398         $patron->login_attempts(-1)->store;
1399         is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' );
1400     }
1401
1402     t::lib::Mocks::mock_preference('FailedloginAttempts', 3);
1403     $patron->login_attempts(2)->store;
1404     is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' );
1405     $patron->login_attempts(3)->store;
1406     is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' );
1407     $patron->login_attempts(4)->store;
1408     is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' );
1409     $patron->login_attempts(-1)->store;
1410     is( $patron->account_locked, 1, 'Administrative lockout triggered' );
1411
1412     $patron->delete;
1413 };
1414
1415 subtest 'is_child | is_adult' => sub {
1416     plan tests => 8;
1417     my $category = $builder->build_object(
1418         {
1419             class => 'Koha::Patron::Categories',
1420             value => { category_type => 'A' }
1421         }
1422     );
1423     my $patron_adult = $builder->build_object(
1424         {
1425             class => 'Koha::Patrons',
1426             value => { categorycode => $category->categorycode }
1427         }
1428     );
1429     $category = $builder->build_object(
1430         {
1431             class => 'Koha::Patron::Categories',
1432             value => { category_type => 'I' }
1433         }
1434     );
1435     my $patron_adult_i = $builder->build_object(
1436         {
1437             class => 'Koha::Patrons',
1438             value => { categorycode => $category->categorycode }
1439         }
1440     );
1441     $category = $builder->build_object(
1442         {
1443             class => 'Koha::Patron::Categories',
1444             value => { category_type => 'C' }
1445         }
1446     );
1447     my $patron_child = $builder->build_object(
1448         {
1449             class => 'Koha::Patrons',
1450             value => { categorycode => $category->categorycode }
1451         }
1452     );
1453     $category = $builder->build_object(
1454         {
1455             class => 'Koha::Patron::Categories',
1456             value => { category_type => 'O' }
1457         }
1458     );
1459     my $patron_other = $builder->build_object(
1460         {
1461             class => 'Koha::Patrons',
1462             value => { categorycode => $category->categorycode }
1463         }
1464     );
1465     is( $patron_adult->is_adult, 1, 'Patron from category A should be considered adult' );
1466     is( $patron_adult_i->is_adult, 1, 'Patron from category I should be considered adult' );
1467     is( $patron_child->is_adult, 0, 'Patron from category C should not be considered adult' );
1468     is( $patron_other->is_adult, 0, 'Patron from category O should not be considered adult' );
1469
1470     is( $patron_adult->is_child, 0, 'Patron from category A should be considered child' );
1471     is( $patron_adult_i->is_child, 0, 'Patron from category I should be considered child' );
1472     is( $patron_child->is_child, 1, 'Patron from category C should not be considered child' );
1473     is( $patron_other->is_child, 0, 'Patron from category O should not be considered child' );
1474
1475     # Clean up
1476     $patron_adult->delete;
1477     $patron_adult_i->delete;
1478     $patron_child->delete;
1479     $patron_other->delete;
1480 };
1481
1482 subtest 'overdues' => sub {
1483     plan tests => 7;
1484
1485     my $library = $builder->build( { source => 'Branch' } );
1486     my $biblionumber_1 = $builder->build_sample_biblio->biblionumber;
1487     my $item_1 = $builder->build_sample_item(
1488         {
1489             library      => $library->{branchcode},
1490             biblionumber => $biblionumber_1,
1491         }
1492     );
1493     my $item_2 = $builder->build_sample_item(
1494         {
1495             library      => $library->{branchcode},
1496             biblionumber => $biblionumber_1,
1497         }
1498     );
1499     my $item_3 = $builder->build_sample_item(
1500         {
1501             library      => $library->{branchcode},
1502         }
1503     );
1504
1505     my $patron = $builder->build(
1506         {
1507             source => 'Borrower',
1508             value  => { branchcode => $library->{branchcode} }
1509         }
1510     );
1511
1512     t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} });
1513
1514     AddIssue( $patron, $item_1->barcode, DateTime->now->subtract( days => 1 ) );
1515     AddIssue( $patron, $item_2->barcode, DateTime->now->subtract( days => 5 ) );
1516     AddIssue( $patron, $item_3->barcode );
1517
1518     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
1519     my $overdues = $patron->overdues;
1520     is( $overdues->count, 2, 'Patron should have 2 overdues');
1521     is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' );
1522     is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' );
1523
1524     my $o = $overdues->reset->next;
1525     my $unblessed_overdue = $o->unblessed_all_relateds;
1526     is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' );
1527     is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' );
1528     is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' );
1529     is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' );
1530
1531     # Clean stuffs
1532     $patron->checkouts->delete;
1533     $patron->delete;
1534 };
1535
1536 subtest 'userid_is_valid' => sub {
1537     plan tests => 9;
1538
1539     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1540     my $patron_category = $builder->build_object(
1541         {
1542             class => 'Koha::Patron::Categories',
1543             value => { category_type => 'P', enrolmentfee => 0 }
1544         }
1545     );
1546     my %data = (
1547         cardnumber   => "123456789",
1548         firstname    => "Tomasito",
1549         surname      => "None",
1550         categorycode => $patron_category->categorycode,
1551         branchcode   => $library->branchcode,
1552     );
1553
1554     my $expected_userid_patron_1 = 'tomasito.none';
1555     my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1556     my $patron_1       = Koha::Patrons->find($borrowernumber);
1557     is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" );
1558     is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' );
1559
1560     $patron_1->userid( 'tomasito.non' );
1561     is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test?
1562         1, 'recently created userid -> unique (borrowernumber passed)' );
1563
1564     $patron_1->userid( 'tomasitoxxx' );
1565     is( $patron_1->has_valid_userid,
1566         1, 'non-existent userid -> unique (borrowernumber passed)' );
1567     $patron_1->discard_changes; # We compare with the original userid later
1568
1569     my $patron_not_in_storage = Koha::Patron->new( { userid => '' } );
1570     is( $patron_not_in_storage->has_valid_userid,
1571         0, 'userid exists for another patron, patron is not in storage yet' );
1572
1573     $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } );
1574     is( $patron_not_in_storage->has_valid_userid,
1575         1, 'non-existent userid, patron is not in storage yet' );
1576
1577     # Regression tests for BZ12226
1578     my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } );
1579     is( $db_patron->has_valid_userid,
1580         0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' );
1581
1582     # Add a new borrower with the same userid but different cardnumber
1583     $data{cardnumber} = "987654321";
1584     my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber;
1585     my $patron_2 = Koha::Patrons->find($new_borrowernumber);
1586     $patron_2->userid($patron_1->userid);
1587     is( $patron_2->has_valid_userid,
1588         0, 'The userid is already in used, it cannot be used for another patron' );
1589
1590     my $new_userid = 'a_user_id';
1591     $data{cardnumber} = "234567890";
1592     $data{userid}     = 'a_user_id';
1593     $borrowernumber   = Koha::Patron->new(\%data)->store->borrowernumber;
1594     my $patron_3 = Koha::Patrons->find($borrowernumber);
1595     is( $patron_3->userid, $new_userid,
1596         'Koha::Patron->store should insert the given userid' );
1597
1598     # Cleanup
1599     $patron_1->delete;
1600     $patron_2->delete;
1601     $patron_3->delete;
1602 };
1603
1604 $nb_of_patrons = Koha::Patrons->search->count;
1605 $retrieved_patron_1->delete;
1606 is( Koha::Patrons->search->count, $nb_of_patrons - 1, 'Delete should have deleted the patron' );
1607
1608 subtest 'BorrowersLog tests' => sub {
1609     plan tests => 4;
1610
1611     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1612     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1613
1614     my $cardnumber = $patron->cardnumber;
1615     $patron->set( { cardnumber => 'TESTCARDNUMBER' });
1616     $patron->store;
1617
1618     my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1619     my $log_info = from_json( $logs[0]->info );
1620     is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' );
1621     is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' );
1622     is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' );
1623
1624     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', 1 );
1625     $patron->track_login();
1626     @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } );
1627     is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivity we should not spam the logs');
1628 };
1629
1630 $schema->storage->txn_rollback;
1631
1632 subtest 'Test Koha::Patrons::merge' => sub {
1633     plan tests => 110;
1634
1635     my $schema = Koha::Database->new()->schema();
1636
1637     my $resultsets = $Koha::Patron::RESULTSET_PATRON_ID_MAPPING;
1638
1639     $schema->storage->txn_begin;
1640
1641     my $keeper  = $builder->build_object({ class => 'Koha::Patrons' });
1642     my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1643     my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber};
1644
1645     my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron');
1646     my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber};
1647     t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron );
1648
1649     while (my ($r, $field) = each(%$resultsets)) {
1650         $builder->build({ source => $r, value => { $field => $keeper->id } });
1651         $builder->build({ source => $r, value => { $field => $loser_1 } });
1652         $builder->build({ source => $r, value => { $field => $loser_2 } });
1653
1654         my $keeper_rs =
1655           $schema->resultset($r)->search( { $field => $keeper->id } );
1656         is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" );
1657
1658         my $loser_1_rs =
1659           $schema->resultset($r)->search( { $field => $loser_1 } );
1660         is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" );
1661
1662         my $loser_2_rs =
1663           $schema->resultset($r)->search( { $field => $loser_2 } );
1664         is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" );
1665     }
1666
1667     my $results = $keeper->merge_with([ $loser_1, $loser_2 ]);
1668
1669     while (my ($r, $field) = each(%$resultsets)) {
1670         my $keeper_rs =
1671           $schema->resultset($r)->search( {$field => $keeper->id } );
1672         is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" );
1673     }
1674
1675     is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' );
1676     is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' );
1677     is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' );
1678
1679     $anonymous_patron = Koha::Patrons->find($anonymous_patron);
1680     $results = $anonymous_patron->merge_with( [ $keeper->id ] );
1681     is( $results, undef, "Anonymous patron cannot have other patrons merged into it" );
1682     is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" );
1683
1684     subtest 'extended attributes' => sub {
1685         plan tests => 8;
1686
1687         my $keep_patron =
1688           $builder->build_object( { class => 'Koha::Patrons' } );
1689         my $merge_patron =
1690           $builder->build_object( { class => 'Koha::Patrons' } );
1691
1692         my $attribute_type_normal_1 = $builder->build_object(
1693             {
1694                 class => 'Koha::Patron::Attribute::Types',
1695                 value => { repeatable => 0, unique_id => 0 }
1696             }
1697         );
1698         my $attribute_type_normal_2 = $builder->build_object(
1699             {
1700                 class => 'Koha::Patron::Attribute::Types',
1701                 value => { repeatable => 0, unique_id => 0 }
1702             }
1703         );
1704
1705         my $attribute_type_repeatable = $builder->build_object(
1706             {
1707                 class => 'Koha::Patron::Attribute::Types',
1708                 value => { repeatable => 1, unique_id => 0 }
1709             }
1710         );
1711
1712         my $attr_keep = [
1713             {
1714                 code      => $attribute_type_normal_1->code,
1715                 attribute => 'from attr 1'
1716             },
1717             {
1718                 code      => $attribute_type_repeatable->code,
1719                 attribute => 'from attr repeatable'
1720             }
1721         ];
1722
1723         my $attr_merge = [
1724             {
1725                 code      => $attribute_type_normal_2->code,
1726                 attribute => 'to attr 2'
1727             },
1728             {
1729                 code      => $attribute_type_repeatable->code,
1730                 attribute => 'to attr repeatable'
1731             },
1732         ];
1733
1734         $keep_patron->extended_attributes($attr_keep);
1735         $merge_patron->extended_attributes($attr_merge);
1736
1737         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1738         my $merged_attributes = $keep_patron->extended_attributes;
1739         is( $merged_attributes->count, 4 );
1740
1741         sub compare_attributes {
1742             my ( $got, $expected, $code ) = @_;
1743
1744             is_deeply(
1745                 [
1746                     sort $got->search( { code => $code } )
1747                       ->get_column('attribute')
1748                 ],
1749                 $expected
1750             );
1751         }
1752         compare_attributes(
1753             $merged_attributes,
1754             ['from attr 1'],
1755             $attribute_type_normal_1->code
1756         );
1757         compare_attributes(
1758             $merged_attributes,
1759             ['to attr 2'],
1760             $attribute_type_normal_2->code
1761         );
1762         compare_attributes(
1763             $merged_attributes,
1764             [ 'from attr repeatable', 'to attr repeatable' ],
1765             $attribute_type_repeatable->code
1766         );
1767
1768         # Cleanup
1769         $keep_patron->delete;
1770         $merge_patron->delete;
1771
1772         # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep
1773         $keep_patron =
1774           $builder->build_object( { class => 'Koha::Patrons' } );
1775         $merge_patron =
1776           $builder->build_object( { class => 'Koha::Patrons' } );
1777
1778         $keep_patron->extended_attributes($attr_keep);
1779         $merge_patron->extended_attributes(
1780             [
1781                 @$attr_merge,
1782                 {
1783                     code      => $attribute_type_normal_1->code,
1784                     attribute => 'yet another attribute for non-repeatable'
1785                 }
1786             ]
1787         );
1788
1789         $keep_patron->merge_with( [ $merge_patron->borrowernumber ] );
1790         $merged_attributes = $keep_patron->extended_attributes;
1791         is( $merged_attributes->count, 4 );
1792         compare_attributes(
1793             $merged_attributes,
1794             ['from attr 1'],
1795             $attribute_type_normal_1->code
1796         );
1797         compare_attributes(
1798             $merged_attributes,
1799             ['to attr 2'],
1800             $attribute_type_normal_2->code
1801         );
1802         compare_attributes(
1803             $merged_attributes,
1804             [ 'from attr repeatable', 'to attr repeatable' ],
1805             $attribute_type_repeatable->code
1806         );
1807
1808     };
1809
1810     t::lib::Mocks::mock_preference( 'AnonymousPatron', '' );
1811     $schema->storage->txn_rollback;
1812 };
1813
1814 subtest '->store' => sub {
1815     plan tests => 11;
1816     my $schema = Koha::Database->new->schema;
1817     $schema->storage->txn_begin;
1818
1819     my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'});
1820     my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'});
1821
1822     throws_ok { $patron_2->userid( $patron_1->userid )->store; }
1823         'Koha::Exceptions::Patron::InvalidUserid',
1824         'Koha::Patron->store raises an exception on duplicate ID';
1825
1826     # Clear userid and check regeneration
1827     $patron_2->userid(undef)->store;
1828     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1829     $patron_2->userid('')->store;
1830     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1831     $patron_2->userid(0)->store;
1832     like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid
1833
1834     # Test password
1835     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1836     my $password = 'password';
1837     $patron_1->set_password({ password => $password });
1838     like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' );
1839     my $digest = $patron_1->password;
1840     $patron_1->surname('xxx')->store;
1841     is( $patron_1->password, $digest, 'Password should not have changed on ->store');
1842
1843     # Test uppercasesurnames
1844     t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 );
1845     my $surname = lc $patron_1->surname;
1846     $patron_1->surname($surname)->store;
1847     isnt( $patron_1->surname, $surname,
1848         'Surname converts to uppercase on store.');
1849     t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 );
1850     $patron_1->surname($surname)->store;
1851     is( $patron_1->surname, $surname,
1852         'Surname remains unchanged on store.');
1853
1854     # Test relationship
1855     $patron_1->relationship("")->store;
1856     is( $patron_1->relationship, undef, );
1857
1858     $schema->storage->txn_rollback;
1859
1860     subtest 'skip updated_on for BorrowersLog' => sub {
1861         plan tests => 1;
1862         $schema->storage->txn_begin;
1863         t::lib::Mocks::mock_preference('BorrowersLog', 1);
1864         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1865         $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store;
1866         my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber });
1867         is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed);
1868         $schema->storage->txn_rollback;
1869     };
1870
1871     subtest 'create user usage' => sub {
1872         plan tests => 1;
1873         $schema->storage->txn_begin;
1874
1875         my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1876         my $patron_category = $builder->build_object(
1877             {
1878                 class => 'Koha::Patron::Categories',
1879                 value => { category_type => 'P', enrolmentfee => 0 }
1880             }
1881         );
1882         my %data = (
1883             cardnumber   => "123456789",
1884             firstname    => "Tômàsító",
1885             surname      => "Ñoné",
1886             password     => 'Funk3y',
1887             categorycode => $patron_category->categorycode,
1888             branchcode   => $library->branchcode,
1889         );
1890
1891         # Enable notifying patrons of password changes for these tests
1892         t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1893         my $new_patron     = Koha::Patron->new( \%data )->store();
1894         my $queued_notices = Koha::Notice::Messages->search(
1895             { borrowernumber => $new_patron->borrowernumber }
1896         );
1897         is(
1898             $queued_notices->count, 0,
1899             "No notice queued when NotifyPasswordChange enabled and this is a new patron"
1900         );
1901
1902         $schema->storage->txn_rollback;
1903     };
1904 };
1905
1906 subtest '->set_password' => sub {
1907
1908     plan tests => 16;
1909
1910     t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro|email' );
1911
1912     $schema->storage->txn_begin;
1913
1914     my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { login_attempts => 3 } } );
1915
1916     # Disable logging password changes for these tests
1917     t::lib::Mocks::mock_preference( 'BorrowersLog', 0 );
1918
1919     # Disable notifying patrons of password changes for these tests
1920     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 );
1921
1922     # Password-length tests
1923     t::lib::Mocks::mock_preference( 'minPasswordLength', undef );
1924     throws_ok { $patron->set_password({ password => 'ab' }); }
1925         'Koha::Exceptions::Password::TooShort',
1926         'minPasswordLength is undef, fall back to 3, fail test';
1927     is( "$@",
1928         'Password length (2) is shorter than required (3)',
1929         'Exception parameters passed correctly'
1930     );
1931
1932     t::lib::Mocks::mock_preference( 'minPasswordLength', 2 );
1933     throws_ok { $patron->set_password({ password => 'ab' }); }
1934         'Koha::Exceptions::Password::TooShort',
1935         'minPasswordLength is 2, fall back to 3, fail test';
1936
1937     t::lib::Mocks::mock_preference( 'minPasswordLength', 5 );
1938     throws_ok { $patron->set_password({ password => 'abcb' }); }
1939         'Koha::Exceptions::Password::TooShort',
1940         'minPasswordLength is 5, fail test';
1941
1942     # Trailing spaces tests
1943     throws_ok { $patron->set_password({ password => 'abcD12d   ' }); }
1944         'Koha::Exceptions::Password::WhitespaceCharacters',
1945         'Password contains trailing spaces, exception is thrown';
1946
1947     # Require strong password tests
1948     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 );
1949     throws_ok { $patron->set_password({ password => 'abcd   a' }); }
1950         'Koha::Exceptions::Password::TooWeak',
1951         'Password is too weak, exception is thrown';
1952
1953     # Refresh patron from DB, just to make sure
1954     $patron->discard_changes;
1955     is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' );
1956
1957     $patron->set_password({ password => 'abcD12 34' });
1958     $patron->discard_changes;
1959
1960     is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' );
1961
1962     lives_ok { $patron->set_password({ password => 'abcd   a', skip_validation => 1 }) }
1963         'Password is weak, but skip_validation was passed, so no exception thrown';
1964
1965     # Completeness
1966     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1967     $patron->login_attempts(3)->store;
1968     my $old_digest = $patron->password;
1969     $patron->set_password({ password => 'abcd   a' });
1970     $patron->discard_changes;
1971
1972     isnt( $patron->password, $old_digest, 'Password has been updated' );
1973     ok( checkpw_hash('abcd   a', $patron->password), 'Password hash is correct' );
1974     is( $patron->login_attempts, 0, 'Login attemps have been reset' );
1975
1976     my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1977     is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' );
1978
1979     # Enable logging password changes
1980     t::lib::Mocks::mock_preference( 'BorrowersLog', 1 );
1981     $patron->set_password({ password => 'abcd   b' });
1982
1983     $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count;
1984     is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' );
1985
1986     # Enable notifying patrons of password changes
1987     t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 );
1988     $patron->set_password({ password => 'abcd   c' });
1989     my $queued_notices = Koha::Notice::Messages->search({ borrowernumber => $patron->borrowernumber });
1990     is( $queued_notices->count, 1, "One notice queued when NotifyPasswordChange enabled" );
1991     my $THE_notice = $queued_notices->next;
1992     is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address."); #FIXME Mock sending mail
1993     $schema->storage->txn_rollback;
1994 };
1995
1996 $schema->storage->txn_begin;
1997 subtest 'filter_by_expiration_date' => sub {
1998     plan tests => 3;
1999     my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count;
2000     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2001     $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store;
2002     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' );
2003     $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store;
2004     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' );
2005     $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store;
2006     is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' );
2007 };
2008
2009 subtest 'search_unsubscribed' => sub {
2010     plan tests => 4;
2011
2012     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2013     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' );
2014     is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' );
2015
2016     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2017     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2018
2019     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 );
2020     Koha::Patron::Consents->delete; # for correct counts
2021     Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string })->store;
2022     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' );
2023
2024     # Add another refusal but shift the period
2025     t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 );
2026     Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING',  refused_on => dt_from_string->subtract(days=>2) })->store;
2027     is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' );
2028
2029     # Try another (special) attempts setting
2030     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 );
2031     # Lockout is now disabled
2032     # Patron2 still matches: refused earlier, not locked
2033     is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' );
2034 };
2035
2036 subtest 'search_anonymize_candidates' => sub {
2037     plan tests => 7;
2038     my $patron1 = $builder->build_object({ class => 'Koha::Patrons' });
2039     my $patron2 = $builder->build_object({ class => 'Koha::Patrons' });
2040     $patron1->anonymized(0);
2041     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2042     $patron2->anonymized(0);
2043     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2044
2045     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} );
2046     is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' );
2047
2048     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 );
2049     my $cnt = Koha::Patrons->search_anonymize_candidates->count;
2050     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2051     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2052     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' );
2053
2054     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 );
2055     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2056     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2057     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2058     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2059     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2060     is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' );
2061
2062     t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 );
2063     $patron1->dateexpiry( dt_from_string->add(days => 1) )->store;
2064     $patron2->dateexpiry( dt_from_string->add(days => 1) )->store;
2065     $cnt = Koha::Patrons->search_anonymize_candidates->count;
2066     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2067     $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store;
2068     is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' );
2069
2070     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2071     $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2072     $patron1->login_attempts(0)->store;
2073     $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store;
2074     $patron2->login_attempts(0)->store;
2075     $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count;
2076     $patron1->login_attempts(3)->store;
2077     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2078         $cnt+1, 'Locked flag' );
2079
2080     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2081     # Patron 1 still on 3 == locked
2082     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2083         $cnt+1, 'Still expect same number for FailedLoginAttempts empty' );
2084     $patron1->login_attempts(0)->store;
2085     # Patron 1 unlocked
2086     is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count,
2087         $cnt, 'Patron 1 unlocked' );
2088 };
2089
2090 subtest 'search_anonymized' => sub {
2091     plan tests => 3;
2092     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2093
2094     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', q{} );
2095     is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' );
2096
2097     t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 );
2098     $patron1->dateexpiry( dt_from_string );
2099     $patron1->anonymized(0)->store;
2100     my $cnt = Koha::Patrons->search_anonymized->count;
2101     $patron1->anonymized(1)->store;
2102     is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' );
2103     $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store;
2104     is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' );
2105 };
2106
2107 subtest 'lock' => sub {
2108     plan tests => 8;
2109
2110     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2111     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2112     my $hold = $builder->build_object({
2113         class => 'Koha::Holds',
2114         value => { borrowernumber => $patron1->borrowernumber },
2115     });
2116
2117     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 );
2118     my $expiry = dt_from_string->add(days => 1);
2119     $patron1->dateexpiry( $expiry );
2120     $patron1->lock;
2121     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2122     is( $patron1->dateexpiry, $expiry, 'Not expired yet' );
2123     is( $patron1->holds->count, 1, 'No holds removed' );
2124
2125     $patron1->lock({ expire => 1, remove => 1});
2126     isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' );
2127     is( $patron1->holds->count, 0, 'Holds removed' );
2128
2129     # Disable lockout feature
2130     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} );
2131     $patron1->login_attempts(0);
2132     $patron1->dateexpiry( $expiry );
2133     $patron1->store;
2134     $patron1->lock;
2135     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' );
2136
2137     # Trivial wrapper test (Koha::Patrons->lock)
2138     $patron1->login_attempts(0)->store;
2139     Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock;
2140     $patron1->discard_changes; # refresh
2141     $patron2->discard_changes;
2142     is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' );
2143     is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' );
2144 };
2145
2146 subtest 'anonymize' => sub {
2147     plan tests => 10;
2148
2149     my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } );
2150     my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } );
2151
2152     # First try patron with issues
2153     my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } });
2154     warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues';
2155     $issue->delete;
2156
2157     t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' );
2158     my $surname = $patron1->surname; # expect change, no clear
2159     my $branchcode = $patron1->branchcode; # expect skip
2160     $patron1->anonymize;
2161     is($patron1->anonymized, 1, 'Check flag' );
2162
2163     is( $patron1->dateofbirth, undef, 'Birth date cleared' );
2164     is( $patron1->firstname, undef, 'First name cleared' );
2165     isnt( $patron1->surname, $surname, 'Surname changed' );
2166     ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' );
2167     is( $patron1->branchcode, $branchcode, 'Branch code skipped' );
2168     is( $patron1->email, undef, 'Email was mandatory, must be cleared' );
2169
2170     # Test wrapper in Koha::Patrons
2171     $patron1->surname($surname)->store; # restore
2172     my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize;
2173     $patron1->discard_changes; # refresh
2174     isnt( $patron1->surname, $surname, 'Surname patron1 changed again' );
2175     $patron2->discard_changes; # refresh
2176     is( $patron2->firstname, undef, 'First name patron2 cleared' );
2177 };
2178
2179 subtest 'queue_notice' => sub {
2180     plan tests => 11;
2181
2182     my $dbh = C4::Context->dbh;
2183     t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'email' );
2184     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
2185     my $branch = $builder->build_object( { class => 'Koha::Libraries' } );
2186     my $letter_e = $builder->build_object( {
2187         class => 'Koha::Notice::Templates',
2188         value => {
2189             branchcode => $branch->branchcode,
2190             message_transport_type => 'email',
2191             lang => 'default'
2192         }
2193     });
2194     my $letter_p = $builder->build_object( {
2195         class => 'Koha::Notice::Templates',
2196         value => {
2197             code => $letter_e->code,
2198             module => $letter_e->module,
2199             branchcode => $branch->branchcode,
2200             message_transport_type => 'print',
2201             lang => 'default'
2202         }
2203     });
2204     my $letter_s = $builder->build_object( {
2205         class => 'Koha::Notice::Templates',
2206         value => {
2207             code => $letter_e->code,
2208             module => $letter_e->module,
2209             branchcode => $branch->branchcode,
2210             message_transport_type => 'sms',
2211             lang => 'default'
2212         }
2213     });
2214
2215     my $letter_params = {
2216         letter_code => $letter_e->code,
2217         branchcode  => $letter_e->branchcode,
2218         module      => $letter_e->module,
2219         borrowernumber => $patron->borrowernumber,
2220         tables => {
2221             borrowers => $patron->borrowernumber,
2222         }
2223     };
2224     my @mtts = ('email');
2225
2226     is( $patron->queue_notice(), undef, "Nothing is done if no params passed");
2227     is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter");
2228     is_deeply(
2229         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2230         {sent => ['email'] }, "Email sent"
2231     );
2232     $patron->email("")->store;
2233     is_deeply(
2234         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2235         {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email"
2236     );
2237     push @mtts, 'sms';
2238     is_deeply(
2239         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2240         {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent"
2241     );
2242     $patron->smsalertnumber("")->store;
2243     my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2244     is_deeply(
2245         $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }),
2246         {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent"
2247     );
2248     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one");
2249
2250     # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data
2251     $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 );
2252     my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef);
2253     $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' );
2254
2255     is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent");
2256
2257     $patron->email(q|awesome@ismymiddle.name|)->store;
2258     is_deeply(
2259         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }),
2260         {sent => ['email'] }, "Email sent when using borrower preferences"
2261     );
2262     $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count;
2263     is_deeply(
2264         $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }),
2265         {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode"
2266     );
2267     is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode");
2268 };
2269
2270 subtest 'filter_by_amount_owed' => sub {
2271     plan tests => 6;
2272
2273     my $library = $builder->build({source => 'Branch' });
2274     my $category = $builder->build({source => 'Category' });
2275
2276     my $new_patron_cf_1 = Koha::Patron->new(
2277         {
2278             cardnumber   => 'test_cn_cf_1',
2279             branchcode   => $library->{branchcode},
2280             categorycode => $category->{categorycode},
2281             surname      => 'surname for patron1',
2282             firstname    => 'firstname for patron1',
2283             userid       => 'a_nonexistent_userid_cf_1',
2284         }
2285     )->store;
2286     my $new_patron_cf_2 = Koha::Patron->new(
2287         {
2288             cardnumber   => 'test_cn_cf_2',
2289             branchcode   => $library->{branchcode},
2290             categorycode => $category->{categorycode},
2291             surname      => 'surname for patron2',
2292             firstname    => 'firstname for patron2',
2293             userid       => 'a_nonexistent_userid_cf_2',
2294         }
2295     )->store;
2296     my $new_patron_cf_3 = Koha::Patron->new(
2297         {
2298             cardnumber   => 'test_cn_cf_3',
2299             branchcode   => $library->{branchcode},
2300             categorycode => $category->{categorycode},
2301             surname      => 'surname for patron3',
2302             firstname    => 'firstname for patron3',
2303             userid       => 'a_nonexistent_userid_cf_3',
2304         }
2305     )->store;
2306
2307     my $results = Koha::Patrons->search(
2308         {
2309             'me.borrowernumber' => [
2310                 $new_patron_cf_1->borrowernumber,
2311                 $new_patron_cf_2->borrowernumber,
2312                 $new_patron_cf_3->borrowernumber
2313             ]
2314         }
2315     );
2316
2317     my $fine1 = $builder->build(
2318         {
2319             source => 'Accountline',
2320             value  => {
2321                 borrowernumber    => $new_patron_cf_1->borrowernumber,
2322                 amountoutstanding => 12.00,
2323                 amount            => 12.00,
2324                 debit_type_code   => 'OVERDUE',
2325                 branchcode        => $library->{branchcode}
2326             },
2327         }
2328     );
2329     my $fine2 = $builder->build(
2330         {
2331             source => 'Accountline',
2332             value  => {
2333                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2334                 amountoutstanding => 8.00,
2335                 amount            => 8.00,
2336                 debit_type_code   => 'OVERDUE',
2337                 branchcode        => $library->{branchcode}
2338
2339             },
2340         }
2341     );
2342     my $fine3 = $builder->build(
2343         {
2344             source => 'Accountline',
2345             value  => {
2346                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2347                 amountoutstanding => 10.00,
2348                 amount            => 10.00,
2349                 debit_type_code   => 'OVERDUE',
2350                 branchcode        => $library->{branchcode}
2351             },
2352         }
2353     );
2354
2355     my $filtered = $results->filter_by_amount_owed();
2356     is( ref($filtered), 'Koha::Patrons',
2357 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context'
2358     );
2359
2360     my $lower_limit = 12.00;
2361     my $upper_limit = 16.00;
2362
2363     # Catch user with 1 x 12.00 fine and user with no fines.
2364     $filtered =
2365       $results->filter_by_amount_owed( { less_than => $upper_limit } );
2366     is( $filtered->_resultset->as_subselect_rs->count, 2,
2367 "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons"
2368     );
2369
2370     # Catch user with 1 x 8.00 and 1 x 10.00 fine
2371     $filtered =
2372       $results->filter_by_amount_owed( { more_than => $lower_limit } );
2373     is( $filtered->_resultset->as_subselect_rs->count, 1,
2374 "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons"
2375     );
2376
2377     # User with 2 fines falls above upper limit - Excluded,
2378     # user with 1 fine falls below lower limit - Excluded
2379     # and user with no fines falls below lower limit - Excluded.
2380     $filtered = $results->filter_by_amount_owed(
2381         { more_than => $lower_limit, less_than => $upper_limit } );
2382     is( $filtered->_resultset->as_subselect_rs->count, 0,
2383 "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons"
2384     );
2385
2386     my $library2 = $builder->build({source => 'Branch' });
2387     my $fine4 = $builder->build(
2388         {
2389             source => 'Accountline',
2390             value  => {
2391                 borrowernumber    => $new_patron_cf_2->borrowernumber,
2392                 amountoutstanding => 10.00,
2393                 amount            => 10.00,
2394                 debit_type_code   => 'HOLD',
2395                 branchcode        => $library2->{branchcode}
2396             },
2397         }
2398     );
2399
2400     # Catch only the user with a HOLD fee over 6.00
2401     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } );
2402     is( $filtered->_resultset->as_subselect_rs->count, 1,
2403 "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron"
2404     );
2405
2406     # Catch only the user with a fee over 6.00 at the specified library
2407     $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } );
2408     is( $filtered->_resultset->as_subselect_rs->count, 1,
2409 "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron"
2410     );
2411 };
2412
2413 subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => sub {
2414     plan tests => 2;
2415
2416     $schema->storage->txn_begin;
2417     my $dbh = $schema->storage->dbh;
2418
2419     $dbh->do("DELETE FROM library_groups");
2420
2421     # group1
2422     #   library_1A
2423     #   library_1B
2424     # group2
2425     #   library_2A
2426     my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store;
2427     my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store;
2428     my $library_1A = $builder->build( { source => 'Branch' } );
2429     my $library_1B = $builder->build( { source => 'Branch' } );
2430     my $library_2A = $builder->build( { source => 'Branch' } );
2431     $library_1A = Koha::Libraries->find( $library_1A->{branchcode} );
2432     $library_1B = Koha::Libraries->find( $library_1B->{branchcode} );
2433     $library_2A = Koha::Libraries->find( $library_2A->{branchcode} );
2434     Koha::Library::Group->new( { branchcode => $library_1A->branchcode, parent_id => $group_1->id } )->store;
2435     Koha::Library::Group->new( { branchcode => $library_1B->branchcode, parent_id => $group_1->id } )->store;
2436     Koha::Library::Group->new( { branchcode => $library_2A->branchcode, parent_id => $group_2->id } )->store;
2437
2438     my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|); # 9 for editcatalogue
2439     # 2 patrons from library_1A (group1)
2440     # patron_1A_1 see patron's infos from outside its group
2441     # Setting flags => undef to not be considered as superlibrarian
2442     my $patron_1A_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2443     $patron_1A_1 = Koha::Patrons->find( $patron_1A_1->{borrowernumber} );
2444     $sth->execute( $patron_1A_1->borrowernumber, 'edit_items' );
2445     $sth->execute( $patron_1A_1->borrowernumber, 'edit_any_item' );
2446     # patron_1A_2 can only see patron's info from its group
2447     my $patron_1A_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }});
2448     $patron_1A_2 = Koha::Patrons->find( $patron_1A_2->{borrowernumber} );
2449     $sth->execute( $patron_1A_2->borrowernumber, 'edit_items' );
2450     # 1 patron from library_1B (group1)
2451     my $patron_1B = $builder->build({ source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, }});
2452     $patron_1B = Koha::Patrons->find( $patron_1B->{borrowernumber} );
2453     # 1 patron from library_2A (group2) can only see patron's info from its group
2454     my $patron_2A = $builder->build({ source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, }});
2455     $patron_2A = Koha::Patrons->find( $patron_2A->{borrowernumber} );
2456     $sth->execute( $patron_2A->borrowernumber, 'edit_items' );
2457
2458     subtest 'libraries_where_can_edit_items' => sub {
2459         plan tests => 3;
2460
2461         my @branchcodes;
2462
2463         @branchcodes = $patron_1A_1->libraries_where_can_edit_items;
2464         is_deeply( \@branchcodes, [], "patron_1A_1 has edit_any_item => No restrictions" );
2465
2466         @branchcodes = $patron_1A_2->libraries_where_can_edit_items;
2467         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" );
2468
2469         @branchcodes = $patron_2A->libraries_where_can_edit_items;
2470         is_deeply( \@branchcodes, [$library_2A->branchcode], "patron_2A doesn't have edit_any_item => Can only see patron's from its group" );
2471     };
2472
2473     subtest 'can_edit_items_from' => sub {
2474         plan tests => 6;
2475
2476         t::lib::Mocks::mock_userenv({ patron => $patron_1A_1 });
2477         is( $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, "patron_1A_1 can see patron_1A_2, from its library" );
2478         is( $patron_1A_1->can_edit_items_from( $library_1B->id ),   1, "patron_1A_1 can see patron_1B, from its group" );
2479         is( $patron_1A_1->can_edit_items_from( $library_2A->id ),   1, "patron_1A_1 can see patron_1A_2, from another group" );
2480
2481         t::lib::Mocks::mock_userenv({ patron => $patron_1A_2 });
2482         is( $patron_1A_2->can_edit_items_from( $library_1A->id ),   1, "patron_1A_2 can see patron_1A_1, from its library" );
2483         is( $patron_1A_2->can_edit_items_from( $library_1B->id ),   1, "patron_1A_2 can see patron_1B, from its group" );
2484         is( $patron_1A_2->can_edit_items_from( $library_2A->id ),   0, "patron_1A_2 can NOT see patron_2A, from another group" );
2485     };
2486 };
2487
2488 subtest 'filter_by_have_permission' => sub {
2489     plan tests => 5;
2490
2491     $schema->storage->txn_begin;
2492
2493     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
2494     my $patron_1 = $builder->build_object(
2495         {
2496             class => 'Koha::Patrons',
2497             value => { flags => 1, branchcode => $library->branchcode }
2498         }
2499     );
2500
2501     my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions
2502         {
2503             class => 'Koha::Patrons',
2504             value => { flags => 4096, branchcode => $library->branchcode }
2505         }
2506     );
2507
2508     my $patron_3 = $builder->build_object(
2509         {
2510             class => 'Koha::Patrons',
2511             value => { flags => 0, branchcode => $library->branchcode }
2512         }
2513     );
2514     $builder->build(
2515         {
2516             source => 'UserPermission',
2517             value  => {
2518                 borrowernumber => $patron_3->borrowernumber,
2519                 module_bit     => 11,
2520                 code           => 'order_manage',
2521             },
2522         }
2523     );
2524
2525     is_deeply(
2526         [
2527             Koha::Patrons->search( { branchcode => $library->branchcode } )
2528               ->filter_by_have_permission('suggestions.suggestions_manage')
2529               ->get_column('borrowernumber')
2530         ],
2531         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2532         'Superlibrarian and patron with suggestions.suggestions_manage'
2533     );
2534
2535     is_deeply(
2536         [
2537             Koha::Patrons->search( { branchcode => $library->branchcode } )
2538               ->filter_by_have_permission('acquisition.order_manage')
2539               ->get_column('borrowernumber')
2540         ],
2541         [ $patron_1->borrowernumber, $patron_3->borrowernumber ],
2542         'Superlibrarian and patron with acquisition.order_manage'
2543     );
2544
2545     is_deeply(
2546         [
2547             Koha::Patrons->search( { branchcode => $library->branchcode } )
2548               ->filter_by_have_permission('parameters.manage_cities')
2549               ->get_column('borrowernumber')
2550         ],
2551         [ $patron_1->borrowernumber ],
2552         'Only Superlibrarian is returned'
2553     );
2554
2555     is_deeply(
2556         [
2557             Koha::Patrons->search( { branchcode => $library->branchcode } )
2558               ->filter_by_have_permission('suggestions')
2559               ->get_column('borrowernumber')
2560         ],
2561         [ $patron_1->borrowernumber, $patron_2->borrowernumber ],
2562         'Superlibrarian and patron with suggestions'
2563     );
2564
2565     throws_ok {
2566         Koha::Patrons->search( { branchcode => $library->branchcode } )
2567           ->filter_by_have_permission('dont_exist.subperm');
2568     } 'Koha::Exceptions::ObjectNotFound';
2569
2570
2571     $schema->storage->txn_rollback;
2572 };
2573
2574 $schema->storage->txn_rollback;